You can use an async result and a delegate for this. If you read up on the documentation it should make it pretty clear what to do. I can write up some sample code if you like and attach it to this answer.
Action isExcelInteractive = IsExcelInteractive;
private async void btnOk_Click(object sender, EventArgs e)
{
IAsyncResult result = isExcelInteractive.BeginInvoke(ItIsDone, null);
result.AsyncWaitHandle.WaitOne();
Console.WriteLine("YAY");
}
static void IsExcelInteractive(){
while (something_is_false) // do your check here
{
if(something_is_true)
return true;
}
Thread.Sleep(1);
}
void ItIsDone(IAsyncResult result)
{
this.isExcelInteractive.EndInvoke(result);
}
Apologies if this code isn't 100% complete, I don't have Visual Studio on this computer, but hopefully it gets you where you need to get to.
run command
ng serve --host=0.0.0.0 --disable-host-check
this will disable host check and allow to access from outside(instead of localhost) with IP address
You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.
A lazy way that works for me,
$ brew install coreutils
$ ln -s /usr/local/bin/greadlink /usr/local/bin/readlink
$ which readlink
/usr/local/bin/readlink
/usr/bin/readlink
This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End
and End Sub
are not the same. They don't perform the same task.
End
puts a stop to ALL code execution and you should almost always use Exit Sub
(or Exit Function
, respectively).
End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)
See also the MSDN dox for the End Statement
When executed, the
End
statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use theStop
statement instead. You can then resume execution while preserving the value of those variables.Note The
End
statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.
Nor is End Sub
and Exit Sub
the same. End Sub
can't be called in the same way Exit Sub
can be, because the compiler doesn't allow it.
This again means you have to Exit Sub
, which is a perfectly legal operation:
Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.
Additionally, and once you get the feel for how procedures work, obviously, End Sub
does not clear any global variables. But it does clear local (Dim'd) variables:
End Sub
Terminates the definition of this procedure.
Simple & clear:
String manType = hasMoney() ? "rich" : "poor";
long version:
String manType;
if (hasMoney()) {
manType = "rich";
} else {
manType = "poor";
}
or how I'm using it to be clear for other code readers:
String manType = "poor";
if (hasMoney())
manType = "rich";
You should take a look at Popcorn.js - a javascript framework for interacting with Html5 : http://popcornjs.org/documentation
As others have mentioned: CSS-3 says that you can use the rgba(...)
syntax to specify a border color with an opacity (alpha) value.
here's a quick example if you'd like to check it.
It works in Safari and Chrome (probably works in all webkit browsers).
It works in Firefox
I doubt that it works at all in IE, but I suspect that there is some filter or behavior that will make it work.
There's also this stackoverflow post, which suggests some other issues--namely, that the border renders on-top-of any background color (or background image) that you've specified; thus limiting the usefulness of border alpha in many cases.
You cannot open a connection directly to a path on a remote host using fsockopen
. The url www.mydomain.net/1/file.php
contains a path, when the only valid value for that first parameter is the host, www.mydomain.net
.
If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.
If you only want to send an HTTP request and ignore the response, you could use fsockopen()
and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen()
, it might look something like this:
$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n");
That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.
I wrote a mixin for some syntactic sugar ;)
Maybe someone likes this way of writing if-then-else better than using guards
depends on Less 1.7.0
https://github.com/pixelass/more-or-less/blob/master/less/fn/_if.less
.if(isnumber(2), {
.-then(){
log {
isnumber: true;
}
}
.-else(){
log {
isnumber: false;
}
}
});
.if(lightness(#fff) gt (20% * 2), {
.-then(){
log {
is-light: true;
}
}
});
using on example from above
.if(@debug, {
.-then(){
header {
background-color: yellow;
#title {
background-color: orange;
}
}
article {
background-color: red;
}
}
});
You can use join()
to wait for all threads to finish. Keep all objects of threads in the global ArrayList at the time of creating threads. After that keep it in loop like below:
for (int i = 0; i < 10; i++)
{
Thread T1 = new Thread(new ThreadTest(i));
T1.start();
arrThreads.add(T1);
}
for (int i = 0; i < arrThreads.size(); i++)
{
arrThreads.get(i).join();
}
Check here for complete details: http://www.letmeknows.com/2017/04/24/wait-for-threads-to-finish-java
Use array_walk_recursive function for multi-denominational array.
array_walk_recursive($data, function (&$v, $k) {
if($k == 'transaction_date'){
$v = date('d/m/Y',$v);
}
});
Yes, bool is a built-in type.
WIN32 is C code, not C++, and C does not have a bool, so they provide their own typedef BOOL.
You will have to use a flag shared between the main thread and the BackgroundWorker, such as BackgroundWorker.CancellationPending
. When you want the BackgroundWorker to exit, just set the flag using BackgroundWorker.CancelAsync().
MSDN has a sample: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancellationpending.aspx
Try something like this:
$txt = "user id date";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
Building up upon Manish Jain
's answer (which is meant for Web API 2 which simplifies things):
1) Use validation structures to response as many validation errors as possible. These structures can also be used to response to requests coming from forms.
public class FieldError
{
public String FieldName { get; set; }
public String FieldMessage { get; set; }
}
// a result will be able to inform API client about some general error/information and details information (related to invalid parameter values etc.)
public class ValidationResult<T>
{
public bool IsError { get; set; }
/// <summary>
/// validation message. It is used as a success message if IsError is false, otherwise it is an error message
/// </summary>
public string Message { get; set; } = string.Empty;
public List<FieldError> FieldErrors { get; set; } = new List<FieldError>();
public T Payload { get; set; }
public void AddFieldError(string fieldName, string fieldMessage)
{
if (string.IsNullOrWhiteSpace(fieldName))
throw new ArgumentException("Empty field name");
if (string.IsNullOrWhiteSpace(fieldMessage))
throw new ArgumentException("Empty field message");
// appending error to existing one, if field already contains a message
var existingFieldError = FieldErrors.FirstOrDefault(e => e.FieldName.Equals(fieldName));
if (existingFieldError == null)
FieldErrors.Add(new FieldError {FieldName = fieldName, FieldMessage = fieldMessage});
else
existingFieldError.FieldMessage = $"{existingFieldError.FieldMessage}. {fieldMessage}";
IsError = true;
}
public void AddEmptyFieldError(string fieldName, string contextInfo = null)
{
AddFieldError(fieldName, $"No value provided for field. Context info: {contextInfo}");
}
}
public class ValidationResult : ValidationResult<object>
{
}
2) Service layer will return ValidationResult
s, regardless of operation being successful or not. E.g:
public ValidationResult DoSomeAction(RequestFilters filters)
{
var ret = new ValidationResult();
if (filters.SomeProp1 == null) ret.AddEmptyFieldError(nameof(filters.SomeProp1));
if (filters.SomeOtherProp2 == null) ret.AddFieldError(nameof(filters.SomeOtherProp2 ), $"Failed to parse {filters.SomeOtherProp2} into integer list");
if (filters.MinProp == null) ret.AddEmptyFieldError(nameof(filters.MinProp));
if (filters.MaxProp == null) ret.AddEmptyFieldError(nameof(filters.MaxProp));
// validation affecting multiple input parameters
if (filters.MinProp > filters.MaxProp)
{
ret.AddFieldError(nameof(filters.MinProp, "Min prop cannot be greater than max prop"));
ret.AddFieldError(nameof(filters.MaxProp, "Check"));
}
// also specify a global error message, if we have at least one error
if (ret.IsError)
{
ret.Message = "Failed to perform DoSomeAction";
return ret;
}
ret.Message = "Successfully performed DoSomeAction";
return ret;
}
3) API Controller will construct the response based on service function result
One option is to put virtually all parameters as optional and perform custom validation which return a more meaningful response. Also, I am taking care not to allow any exception to go beyond the service boundary.
[Route("DoSomeAction")]
[HttpPost]
public HttpResponseMessage DoSomeAction(int? someProp1 = null, string someOtherProp2 = null, int? minProp = null, int? maxProp = null)
{
try
{
var filters = new RequestFilters
{
SomeProp1 = someProp1 ,
SomeOtherProp2 = someOtherProp2.TrySplitIntegerList() ,
MinProp = minProp,
MaxProp = maxProp
};
var result = theService.DoSomeAction(filters);
return !result.IsError ? Request.CreateResponse(HttpStatusCode.OK, result) : Request.CreateResponse(HttpStatusCode.BadRequest, result);
}
catch (Exception exc)
{
Logger.Log(LogLevel.Error, exc, "Failed to DoSomeAction");
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError("Failed to DoSomeAction - internal error"));
}
}
From SourceTree, click on Tools->Options. Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.
Then switch to the "Diff" tab. On the lower half, use the drop down to select the external program you want to use to do the diffs and merging. I've installed KDiff3 and like it well enough. When you're done, click OK.
Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.
I accidentally ran our (largeish) application on a 64bit VM rather than a 32bit VM and didn't notice until some external libraries (called by JNI) started failing.
Data serialized on a 32bit platform was read in on the 64bit platform with no issues at all.
What sort of issues are you getting? Do some things work and not others? Have you tried attaching JConsole etc and have a peak around?
If you have a very big VM you may find that GC issues in 64 bit can affect you.
The proper way to do this requires leveraging the SAM registry hive (on Windows 10, this requires NT AUTHORITY\SYSTEM
privileges). The information you require is in the the key: HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users\Names
.
Each subkey is the username, and the default value in each subkey is a binary integer. This value (converted to decimal) actually corresponds to the last chunk of the of the SID.
Take "Administrator" for example, by default it is associated with the integer 0x1f4 (or 500).
So, in theory you could take the build a list of SIDS based on the subkey names of the HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList
key and/or HKEY_USERS
key, parse out the the value after the last hyphen (-), and compare that to the info from the SAM hive.
If you don't have NT AUTHORITY\SYSTEM
privileges, the next best way to approach this may be to follow the other method described in the answers here.
$row['Value']
is probably a string. Try using intval($row['Value'])
.
Also, make sure you set $sum = 0
before the loop.
Or, better yet, add SUM(Value) AS Val_Sum
to your SQL query.
Addition to the accepted answer:
struct immutableint { immutableint(int i) : i_(i) {} const int& get() const { return i_; } private: int i_; };
I'd argue that this example is not okay and should be avoided if possible. Why? It is very easy to end-up with a dangling reference.
To illustrate the point with an example:
struct Foo
{
Foo(int i = 42) : boo_(i) {}
immutableint boo()
{
return boo_;
}
private:
immutableint boo_;
};
entering the danger-zone:
Foo foo;
const int& dangling = foo.boo().get(); // dangling reference!
Raw strings are not a different kind of string. They are a different way of describing a string in your source code. Once the string is created, it is what it is.
import os
from os.path import join as join_paths
def mk_dir_recursive(dir_path):
if os.path.isdir(dir_path):
return
h, t = os.path.split(dir_path) # head/tail
if not os.path.isdir(h):
mk_dir_recursive(h)
new_path = join_paths(h, t)
if not os.path.isdir(new_path):
os.mkdir(new_path)
based on @Dave C's answer but with a bug fixed where part of the tree already exists
add these in php file where your ajax url call
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
Simple, use array_intersect()
instead:
$result = array_intersect($array1, $array2);
If you use php-fpm
, the php_admin_value will NOT work and gives an Internal Server Error.
Instead use this in your .htaccess
. It disables the parser in that folder and all subfolders:
<FilesMatch ".+\.*$">
SetHandler !
</FilesMatch>
A fleshed out version of Michael Foukarakis post (since I don't have the "reputation" to add a comment to that post yet):
#include <stdio.h>
#include <string.h>
void print(unsigned char *byte_array, int byte_array_size)
{
int i = 0;
printf("0x");
for(; i < byte_array_size; i++)
{
printf("%02x", byte_array[i]);
}
printf("\n");
}
int convert(const char *hex_str, unsigned char *byte_array, int byte_array_max)
{
int hex_str_len = strlen(hex_str);
int i = 0, j = 0;
// The output array size is half the hex_str length (rounded up)
int byte_array_size = (hex_str_len+1)/2;
if (byte_array_size > byte_array_max)
{
// Too big for the output array
return -1;
}
if (hex_str_len % 2 == 1)
{
// hex_str is an odd length, so assume an implicit "0" prefix
if (sscanf(&(hex_str[0]), "%1hhx", &(byte_array[0])) != 1)
{
return -1;
}
i = j = 1;
}
for (; i < hex_str_len; i+=2, j++)
{
if (sscanf(&(hex_str[i]), "%2hhx", &(byte_array[j])) != 1)
{
return -1;
}
}
return byte_array_size;
}
void main()
{
char *examples[] = { "", "5", "D", "5D", "5Df", "deadbeef10203040b00b1e50", "02invalid55" };
unsigned char byte_array[128];
int i = 0;
for (; i < sizeof(examples)/sizeof(char *); i++)
{
int size = convert(examples[i], byte_array, 128);
if (size < 0)
{
printf("Failed to convert '%s'\n", examples[i]);
}
else if (size == 0)
{
printf("Nothing to convert for '%s'\n", examples[i]);
}
else
{
print(byte_array, size);
}
}
}
Add this line
AddHandler application/x-httpd-php .html
to httpd.conf
file for what you want to do.
But remember, if you do this then your web server will be very slow, because it will be parsing even static code which will not contain php code.
So the better way will be to make the file extension .phtml
instead of just .html
.
The CPP Section of the GCC Manual indicates that header files may be located in the following directories:
GCC looks in several different places for headers. On a normal Unix system, if you do not instruct it otherwise, it will look for headers requested with #include in:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
For C++ programs, it will also look in /usr/include/g++-v3, first.
Almost everywhere you look, people refer to the about:config and the security.fileuri.strict_origin_policy. Sometimes also the network.http.refere.XOriginPolicy.
For me, none of these seem to have any effect.
This comment implies there is no built-in way in Firefox to do this (as of 2/8/14).
You just need to declare a
as a global in thread2
, so that you aren't modifying an a
that is local to that function.
def thread2(threadname):
global a
while True:
a += 1
time.sleep(1)
In thread1
, you don't need to do anything special, as long as you don't try to modify the value of a
(which would create a local variable that shadows the global one; use global a
if you need to)>
def thread1(threadname):
#global a # Optional if you treat a as read-only
while a < 10:
print a
think works
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));
The zoo
package has the function of as.yearmon
can help to convert.
require(zoo)
df$ym<-as.yearmon(df$date, "%Y %m")
I used to reset the IFS value and rollback when done.
# backup IFS value
O_IFS=$IFS
# reset IFS value
IFS=""
FILES=(
"2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg"
)
for file in ${FILES[@]}; do
echo ${file}
done
# rollback IFS value
IFS=${O_IFS}
Possible output from the loop:
2011-09-04 21.43.02.jpg
2011-09-05 10.23.14.jpg
2011-09-09 12.31.16.jpg
2011-09-11 08.43.12.jpg
I had the same problem and used Glide library instead. Cache is out of the box there. https://github.com/bumptech/glide
if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
If compileOptions doesn't work, try this
Disable 'Instant Run'.
Android Studio -> File -> Settings -> Build, Execution, Deployment -> Instant Run -> Disable checkbox
Thank you, in PostgreSQL this works for boolean
SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects
Another helpful but simple solution might be restarting your computer after doing the download if Python is in the PATH variable. This has been a mistake I usually make when downloading Python onto a new machine.
After restarting my machine then Windows will often recognize Python in the PATH variable.
Lets use the titanic dataset from the seaborn package as an example
# Load dataset (pip install seaborn)
>> import seaborn.apionly as sns
>> titanic = sns.load_dataset('titanic')
using the column names
>> titanic.loc[:,['sex','age','fare']]
using the column indices
>> titanic.iloc[:,[2,3,6]]
using ix (Older than Pandas <.20 version)
>> titanic.ix[:,[‘sex’,’age’,’fare’]]
or
>> titanic.ix[:,[2,3,6]]
using the reindex method
>> titanic.reindex(columns=['sex','age','fare'])
Objects aren't passed at all. By default, the argument is evaluated and its value is passed, by value, as the initial value of the parameter of the method you're calling. Now the important point is that the value is a reference for reference types - a way of getting to an object (or null). Changes to that object will be visible from the caller. However, changing the value of the parameter to refer to a different object will not be visible when you're using pass by value, which is the default for all types.
If you want to use pass-by-reference, you must use out
or ref
, whether the parameter type is a value type or a reference type. In that case, effectively the variable itself is passed by reference, so the parameter uses the same storage location as the argument - and changes to the parameter itself are seen by the caller.
So:
public void Foo(Image image)
{
// This change won't be seen by the caller: it's changing the value
// of the parameter.
image = Image.FromStream(...);
}
public void Foo(ref Image image)
{
// This change *will* be seen by the caller: it's changing the value
// of the parameter, but we're using pass by reference
image = Image.FromStream(...);
}
public void Foo(Image image)
{
// This change *will* be seen by the caller: it's changing the data
// within the object that the parameter value refers to.
image.RotateFlip(...);
}
I have an article which goes into a lot more detail in this. Basically, "pass by reference" doesn't mean what you think it means.
There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.
By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler)
method call you are also able to register a signal handler, but probably not for signals like INT
or TERM
as they are used by the JVM.
To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.
What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid
system call.
I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.
rake db:rollback STEP=1
Is a way to do this, if the migration you want to rollback is the last one applied. You can substitute 1 for however many migrations you want to go back.
For example:
rake db:rollback STEP=5
Will also rollback all the migration that happened later (4, 3, 2 and also 1).
To roll back all migrations back to (and including) a target migration, use: (This corrected command was added AFTER all the comments pointing out the error in the original post)
rake db:migrate VERSION=20100905201547
In order to rollback ONLY ONE specific migration (OUT OF ORDER) use:
rake db:migrate:down VERSION=20100905201547
Note that this will NOT rollback any interceding migrations -- only the one listed. If that is not what you intended, you can safely run rake db:migrate
and it will re-run only that one, skipping any others that were not previously rolled back.
And if you ever want to migrate a single migration out of order, there is also its inverse db:migrate:up
:
rake db:migrate:up VERSION=20100905201547
I recently started receiving this error inside of my internal NLog failures log, with Visual Studio 2013. The solution has been using NLog v2.0.0 for several years. Within the last month, our main log stopped working. To fix this I updated NLog to the newest version (v3.1.0) via Nuget. The security exception is now gone and ALL of the log messages are appearing again.
Additionally, I later found another Security exception and was able to fix it by following the instructions on this post in another thread.
try this, it will not work for the first selection, then it will work nice :)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error GoTo 10
If Target.Count > 1 Then GoTo 10
Target.Value = lastcel(Target.Value)
10
End Sub
Function lastcel(lC_vAl As String) As String
Static vlu
lastcel = vlu
vlu = lC_vAl
End Function
Sorting html table column on page load
var table = $('table#all_items_table');
var rows = table.find('tr:gt(0)').toArray().sort(comparer(3));
for (var i = 0; i < rows.length; i++) {
table.append(rows[i])
}
function comparer(index) {
return function (a, b) {
var v1= getCellValue(a, index),
v2= getCellValue(b, index);
return $.isNumeric(v2) && $.isNumeric(v1) ? v2 - v1: v2.localeCompare(v1)
}
}
function getCellValue(row, index) {
return parseFloat($(row).children('td').eq(index).html().replace(/,/g,'')); //1234234.45645->1234234
}
You need to enable 'INDENT' and set the indent amount for the transformer:
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
Update:
Reference : How to strip whitespace-only text nodes from a DOM before serialization?
(Many thanks to all members especially @marc-novakowski, @james-murty and @saad):
A ScrollView is a special type of FrameLayout in that it allows users to scroll through a list of views that occupy more space than the physical display.I just add some attributes .
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:scrollbars = "vertical"
android:scrollbarStyle="insideInset"
>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
>
<!-- Add here which you want -->
</TableLayout>
</ScrollView>
Here, I summarize a few ways which may return different results to your question, so be careful:
# First assign your "id"s to an R object.
# Here's a hypothetical example:
id <- c("a","b","b","c","c","c","d","d","d","d")
#To return ALL MINUS ONE duplicated values:
id[duplicated(id)]
## [1] "b" "c" "c" "d" "d" "d"
#To return ALL duplicated values by specifying fromLast argument:
id[duplicated(id) | duplicated(id, fromLast=TRUE)]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
#Yet another way to return ALL duplicated values, using %in% operator:
id[ id %in% id[duplicated(id)] ]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
Hope these help. Good luck.
I had similar requirement of running a LAMP stack, Mongo DB and my own services
Docker is OS based virtualisation, which is why it isolates its container around a running process, hence it requires least one process running in FOREGROUND.
So you provide your own startup script as the entry point, thus your startup script becomes an extended Docker image script, in which you can stack any number of the services as far as AT LEAST ONE FOREGROUND SERVICE IS STARTED, WHICH TOO TOWARDS THE END
So my Docker image file has two line below in the very end:
COPY myStartupScript.sh /usr/local/myscripts/myStartupScript.sh
CMD ["/bin/bash", "/usr/local/myscripts/myStartupScript.sh"]
In my script I run all MySQL, MongoDB, Tomcat etc. In the end I run my Apache as a foreground thread.
source /etc/apache2/envvars
/usr/sbin/apache2 -DFOREGROUND
This enables me to start all my services and keep the container alive with the last service started being in the foreground
Hope it helps
UPDATE: Since I last answered this question, new things have come up like Docker compose, which can help you run each service on its own container, yet bind all of them together as dependencies among those services, try knowing more about docker-compose and use it, it is more elegant way unless your need does not match with it.
Well it depends on your OS - actually I did not test it on MS Windows - but Conque is one of the best plugins out there.
Actually, it can be better, but works.
When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For example:
inputChangeHandler(event) {_x000D_
this.setState({ [event.target.name]: event.target.value });_x000D_
}
_x000D_
The accepted answer is invalid with the double EXEC (only need the first EXEC):
DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue
And you still need to call PRINT (at least in Visual Studio).
public class ImageTransformation {
public static final String PNG = "png";
public static byte[] resize(FileItem fileItem, int width, int height) {
try {
ResampleOp resampleOp = new ResampleOp(width, height);
BufferedImage scaledImage = resampleOp.filter(ImageIO.read(fileItem.getInputStream()), null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(scaledImage, PNG, baos);
return baos.toByteArray();
} catch (Exception ex) {
throw new MapsException("An error occured during image resizing.", ex);
}
}
public static byte[] resizeAdjustMax(FileItem fileItem, int maxWidth, int maxHeight) {
try {
BufferedInputStream bis = new BufferedInputStream(fileItem.getInputStream());
BufferedImage bufimg = ImageIO.read(bis);
//check size of image
int img_width = bufimg.getWidth();
int img_height = bufimg.getHeight();
if(img_width > maxWidth || img_height > maxHeight) {
float factx = (float) img_width / maxWidth;
float facty = (float) img_height / maxHeight;
float fact = (factx>facty) ? factx : facty;
img_width = (int) ((int) img_width / fact);
img_height = (int) ((int) img_height / fact);
}
return resize(fileItem,img_width, img_height);
} catch (Exception ex) {
throw new MapsException("An error occured during image resizing.", ex);
}
}
}
In C/C++ sizeof
. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof
a pointer--to the first element of an array or to a single object--gives the size of the pointer, not the object(s) pointed to. Either way, sizeof
does not give the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,
for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )
As for doing it the C++11 way, the best way to do it is probably
for(const string &text : texts)
cout << "value of text: " << text << endl;
This lets the compiler figure out how many iterations you need.
EDIT: as others have pointed out, std::array
is preferred in C++11 over raw arrays; however, none of the other answers addressed why sizeof
is failing the way it is, so I still think this is the better answer.
No. Python Strings are immutable.
>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
It is, however, possible to create a new string that has the inserted character:
>>> s[:4] + '-' + s[4:]
'3558-79ACB6'
Here is example:
You have a.bat:
@echo off
if exist b.bat goto RUNB
goto END
:RUNB
b.bat
:END
and b.bat called conditionally from a.bat:
@echo off
echo "This is b.bat"
var sec_to_hms = function(sec){
var min, hours;
sec = sec - (min = Math.floor(sec/60))*60;
min = min - (hours = Math.floor(min/60))*60;
return (hours?hours+':':'') + ((min+'').padStart(2, '0')) + ':'+ ((sec+'').padStart(2, '0'));
}
alert(sec_to_hms(2442542));
public static T[] Concat<T>(this T[] first, params T[][] arrays)
{
int length = first.Length;
foreach (T[] array in arrays)
{
length += array.Length;
}
T[] result = new T[length];
length = first.Length;
Array.Copy(first, 0, result, 0, first.Length);
foreach (T[] array in arrays)
{
Array.Copy(array, 0, result, length, array.Length);
length += array.Length;
}
return result;
}
Please keep in mind that the answers here assume that the length of the file is less than or equal to Integer.MAX_VALUE
(2147483647).
If you are reading in from a file, you can do something like this:
File file = new File("myFile");
byte[] fileData = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData);
dis.close();
Java 7 adds some new features in the java.nio.file package that can be used to make this example a few lines shorter. See the readAllBytes() method in the java.nio.file.Files class. Here is a short example:
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
// ...
Path p = FileSystems.getDefault().getPath("", "myFile");
byte [] fileData = Files.readAllBytes(p);
Android has support for this starting in Api level 26 (8.0.0, Oreo).
Try the following
Dictionary<int, DateTime> existingItems =
(from ObjType ot in TableObj).ToDictionary(x => x.Key);
Or the fully fledged type inferenced version
var existingItems = TableObj.ToDictionary(x => x.Key);
If you want to access redis
from the host (127.0.0.1), you have to use the ports
command.
redis:
build:
context: .
dockerfile: Dockerfile-redis
ports:
- "6379:6379"
Updated answer for a .NET Core Web Api project...
Right-click on your project, select "Properties," go to "Debug" and untick the "Launch browser" checkbox (enabled by default).
OFFSET
is nothing but a keyword to indicate starting cursor in table
SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)
you would get the same result form
SELECT column FROM table LIMIT 8, 18
visual representation (R
is one record in the table in some order)
OFFSET LIMIT rest of the table
__||__ _______||_______ __||__
/ \ / \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
\________________/
||
your result
In a hacky way it can be done for channels which one attempts to write to by recovering the raised panic. But you cannot check if a read channel is closed without reading from it.
Either you will
v <- c
)v, ok <- c
)v, ok <- c
)v <- c
)Only the last one technically doesn't read from the channel, but that's of little use.
XAMPP by default uses http://localhost/phpmyadmin
It also requires you start both Apache and MySQL from the control panel (or as a service).
In the XAMPP Control Panel, clicking [ Admin ] on the MySQL line will open your default browser at the configured URL for the phpMyAdmin application.
If you get a phpMyAdmin error stating "Cannot connect: invalid settings." You will need to make sure your MySQL config file has a matching port for server and client. If it is not the standard 3306 port, you will also need to change your phpMyAdmin config file under apache (config.inc.php) to meet the new port settings. (127.0.0.1 becomes 127.0.0.1:<port>)
(Background: I have some experience implementing C and C++ compilers.)
Variable-length arrays in C99 were basically a misstep. In order to support VLAs, C99 had to make the following concessions to common sense:
sizeof x
is no longer always a compile-time constant; the compiler must sometimes generate code to evaluate a sizeof
-expression at runtime.
Allowing two-dimensional VLAs (int A[x][y]
) required a new syntax for declaring functions that take 2D VLAs as parameters: void foo(int n, int A[][*])
.
Less importantly in the C++ world, but extremely important for C's target audience of embedded-systems programmers, declaring a VLA means chomping an arbitrarily large chunk of your stack. This is a guaranteed stack-overflow and crash. (Anytime you declare int A[n]
, you're implicitly asserting that you have 2GB of stack to spare. After all, if you know "n
is definitely less than 1000 here", then you would just declare int A[1000]
. Substituting the 32-bit integer n
for 1000
is an admission that you have no idea what the behavior of your program ought to be.)
Okay, so let's move to talking about C++ now. In C++, we have the same strong distinction between "type system" and "value system" that C89 does… but we've really started to rely on it in ways that C has not. For example:
template<typename T> struct S { ... };
int A[n];
S<decltype(A)> s; // equivalently, S<int[n]> s;
If n
weren't a compile-time constant (i.e., if A
were of variably modified type), then what on earth would be the type of S
? Would S
's type also be determined only at runtime?
What about this:
template<typename T> bool myfunc(T& t1, T& t2) { ... };
int A1[n1], A2[n2];
myfunc(A1, A2);
The compiler must generate code for some instantiation of myfunc
. What should that code look like? How can we statically generate that code, if we don't know the type of A1
at compile time?
Worse, what if it turns out at runtime that n1 != n2
, so that !std::is_same<decltype(A1), decltype(A2)>()
? In that case, the call to myfunc
shouldn't even compile, because template type deduction should fail! How could we possibly emulate that behavior at runtime?
Basically, C++ is moving in the direction of pushing more and more decisions into compile-time: template code generation, constexpr
function evaluation, and so on. Meanwhile, C99 was busy pushing traditionally compile-time decisions (e.g. sizeof
) into the runtime. With this in mind, does it really even make sense to expend any effort trying to integrate C99-style VLAs into C++?
As every other answerer has already pointed out, C++ provides lots of heap-allocation mechanisms (std::unique_ptr<int[]> A = new int[n];
or std::vector<int> A(n);
being the obvious ones) when you really want to convey the idea "I have no idea how much RAM I might need." And C++ provides a nifty exception-handling model for dealing with the inevitable situation that the amount of RAM you need is greater than the amount of RAM you have. But hopefully this answer gives you a good idea of why C99-style VLAs were not a good fit for C++ — and not really even a good fit for C99. ;)
For more on the topic, see N3810 "Alternatives for Array Extensions", Bjarne Stroustrup's October 2013 paper on VLAs. Bjarne's POV is very different from mine; N3810 focuses more on finding a good C++ish syntax for the things, and on discouraging the use of raw arrays in C++, whereas I focused more on the implications for metaprogramming and the typesystem. I don't know if he considers the metaprogramming/typesystem implications solved, solvable, or merely uninteresting.
A good blog post that hits many of these same points is "Legitimate Use of Variable Length Arrays" (Chris Wellons, 2019-10-27).
There are different ways. If you just want to check if one list contains any element from the other list, you can do this..
not set(list1).isdisjoint(list2)
I believe using isdisjoint
is better than intersection
for Python 2.6 and above.
You have to free()
the allocated memory in exact reverse order of how it was allocated using malloc()
.
Note that You should free the memory only after you are done with your usage of the allocated pointers.
memory allocation for 1D arrays:
buffer = malloc(num_items*sizeof(double));
memory deallocation for 1D arrays:
free(buffer);
memory allocation for 2D arrays:
double **cross_norm=(double**)malloc(150 * sizeof(double *));
for(i=0; i<150;i++)
{
cross_norm[i]=(double*)malloc(num_items*sizeof(double));
}
memory deallocation for 2D arrays:
for(i=0; i<150;i++)
{
free(cross_norm[i]);
}
free(cross_norm);
Use Calendar.getInstance().get(Calendar.MONTH)+1
to get current month.
I could use the GetBody
from Request package.
Look this comment in source code from request.go in net/http:
GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."
GetBody func() (io.ReadCloser, error)
This way you can get the body request without make it empty.
Sample:
getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
// Do something return err
}
http.DefaultClient.Do(request)
Path Variables dialog has nothing to do with the environment variables.
Environment variables can be specified in your OS or customized in the Run configuration:
Easy way: use the following CDN:
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-material-icons/0.5.0/angular-material-icons.min.js"></script>
Inject ngMdIcons to your angularjs application:
angular.module('demoapp', ['ngMdIcons']);
Use ng-md-icon directive in your html, specifying fill-color through css:
<ng-md-icon icon="..." style="fill: ..." size="..."></ng-md-icon>
use the xclip
which is command line interface to X selections
apt-get install xclip
echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out
cat /tmp/test.xclip.out # "test xclip"
enjoy.
I had this same problem on RHEL6. It turns out that the mysql.ini file in /etc/php.d only had a module name but needed a full path name. On my RHEL6 system the entry that works is:
; Enable mysql extension module
extension=/usr/lib64/php/modules/mysql.so
After modifying the file, I restarted apache and everything worked.
After struggling for an hour, I just unchecked the "Automatically manage signing" and went back to the old school way of specifying my profiles. Probably not the best thing to do but works.
This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)
window.onbeforeunload = function () {
return "Are you sure?";
}
$(function () {
$('input[type="checkbox"]').click(function () {
window.onbeforeunload = function () { };
});
});
I know its not relevant to this post but might help others converting HTML to PDF on client side. This is a simple solution if you use kendo. It also preserves the css (most of the cases).
var generatePDF = function() {_x000D_
kendo.drawing.drawDOM($("#formConfirmation")).then(function(group) {_x000D_
kendo.drawing.pdf.saveAs(group, "Converted PDF.pdf");_x000D_
});_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<br/>_x000D_
<button class="btn btn-primary" onclick="generatePDF()"><i class="fa fa-save"></i> Save as PDF</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<div id="formConfirmation">_x000D_
_x000D_
<div class="container theme-showcase" role="main">_x000D_
<!-- Main jumbotron for a primary marketing message or call to action -->_x000D_
<div class="jumbotron">_x000D_
<h1>Theme example</h1>_x000D_
<p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>_x000D_
</div>_x000D_
<div class="page-header">_x000D_
<h1>Buttons</h1>_x000D_
</div>_x000D_
<p>_x000D_
<button type="button" class="btn btn-lg btn-default">Default</button>_x000D_
<button type="button" class="btn btn-lg btn-primary">Primary</button>_x000D_
<button type="button" class="btn btn-lg btn-success">Success</button>_x000D_
<button type="button" class="btn btn-lg btn-info">Info</button>_x000D_
<button type="button" class="btn btn-lg btn-warning">Warning</button>_x000D_
<button type="button" class="btn btn-lg btn-danger">Danger</button>_x000D_
<button type="button" class="btn btn-lg btn-link">Link</button>_x000D_
</p>_x000D_
<p>_x000D_
<button type="button" class="btn btn-default">Default</button>_x000D_
<button type="button" class="btn btn-primary">Primary</button>_x000D_
<button type="button" class="btn btn-success">Success</button>_x000D_
<button type="button" class="btn btn-info">Info</button>_x000D_
<button type="button" class="btn btn-warning">Warning</button>_x000D_
<button type="button" class="btn btn-danger">Danger</button>_x000D_
<button type="button" class="btn btn-link">Link</button>_x000D_
</p>_x000D_
<p>_x000D_
<button type="button" class="btn btn-sm btn-default">Default</button>_x000D_
<button type="button" class="btn btn-sm btn-primary">Primary</button>_x000D_
<button type="button" class="btn btn-sm btn-success">Success</button>_x000D_
<button type="button" class="btn btn-sm btn-info">Info</button>_x000D_
<button type="button" class="btn btn-sm btn-warning">Warning</button>_x000D_
<button type="button" class="btn btn-sm btn-danger">Danger</button>_x000D_
<button type="button" class="btn btn-sm btn-link">Link</button>_x000D_
</p>_x000D_
<p>_x000D_
<button type="button" class="btn btn-xs btn-default">Default</button>_x000D_
<button type="button" class="btn btn-xs btn-primary">Primary</button>_x000D_
<button type="button" class="btn btn-xs btn-success">Success</button>_x000D_
<button type="button" class="btn btn-xs btn-info">Info</button>_x000D_
<button type="button" class="btn btn-xs btn-warning">Warning</button>_x000D_
<button type="button" class="btn btn-xs btn-danger">Danger</button>_x000D_
<button type="button" class="btn btn-xs btn-link">Link</button>_x000D_
</p>_x000D_
<div class="page-header">_x000D_
<h1>Tables</h1>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<table class="table">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>#</th>_x000D_
<th>First Name</th>_x000D_
<th>Last Name</th>_x000D_
<th>Username</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Mark</td>_x000D_
<td>Otto</td>_x000D_
<td>@mdo</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>Jacob</td>_x000D_
<td>Thornton</td>_x000D_
<td>@fat</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>Larry</td>_x000D_
<td>the Bird</td>_x000D_
<td>@twitter</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<table class="table table-striped">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>#</th>_x000D_
<th>First Name</th>_x000D_
<th>Last Name</th>_x000D_
<th>Username</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Mark</td>_x000D_
<td>Otto</td>_x000D_
<td>@mdo</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>Jacob</td>_x000D_
<td>Thornton</td>_x000D_
<td>@fat</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>Larry</td>_x000D_
<td>the Bird</td>_x000D_
<td>@twitter</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<table class="table table-bordered">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>#</th>_x000D_
<th>First Name</th>_x000D_
<th>Last Name</th>_x000D_
<th>Username</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td rowspan="2">1</td>_x000D_
<td>Mark</td>_x000D_
<td>Otto</td>_x000D_
<td>@mdo</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Mark</td>_x000D_
<td>Otto</td>_x000D_
<td>@TwBootstrap</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>Jacob</td>_x000D_
<td>Thornton</td>_x000D_
<td>@fat</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td colspan="2">Larry the Bird</td>_x000D_
<td>@twitter</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
<div class="col-md-6">_x000D_
<table class="table table-condensed">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>#</th>_x000D_
<th>First Name</th>_x000D_
<th>Last Name</th>_x000D_
<th>Username</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>Mark</td>_x000D_
<td>Otto</td>_x000D_
<td>@mdo</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td>_x000D_
<td>Jacob</td>_x000D_
<td>Thornton</td>_x000D_
<td>@fat</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td colspan="2">Larry the Bird</td>_x000D_
<td>@twitter</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
<div class="page-header">_x000D_
<h1>Thumbnails</h1>_x000D_
</div>_x000D_
<img data-src="holder.js/200x200" class="img-thumbnail" alt="A generic square placeholder image with a white border around it, making it resemble a photograph taken with an old instant camera">_x000D_
<div class="page-header">_x000D_
<h1>Labels</h1>_x000D_
</div>_x000D_
<h1>_x000D_
<span class="label label-default">Default</span>_x000D_
<span class="label label-primary">Primary</span>_x000D_
<span class="label label-success">Success</span>_x000D_
<span class="label label-info">Info</span>_x000D_
<span class="label label-warning">Warning</span>_x000D_
<span class="label label-danger">Danger</span>_x000D_
</h1>_x000D_
<h2>_x000D_
<span class="label label-default">Default</span>_x000D_
<span class="label label-primary">Primary</span>_x000D_
<span class="label label-success">Success</span>_x000D_
<span class="label label-info">Info</span>_x000D_
<span class="label label-warning">Warning</span>_x000D_
<span class="label label-danger">Danger</span>_x000D_
</h2>_x000D_
<h3>_x000D_
<span class="label label-default">Default</span>_x000D_
<span class="label label-primary">Primary</span>_x000D_
<span class="label label-success">Success</span>_x000D_
<span class="label label-info">Info</span>_x000D_
<span class="label label-warning">Warning</span>_x000D_
<span class="label label-danger">Danger</span>_x000D_
</h3>_x000D_
<h4>_x000D_
<span class="label label-default">Default</span>_x000D_
<span class="label label-primary">Primary</span>_x000D_
<span class="label label-success">Success</span>_x000D_
<span class="label label-info">Info</span>_x000D_
<span class="label label-warning">Warning</span>_x000D_
<span class="label label-danger">Danger</span>_x000D_
</h4>_x000D_
<h5>_x000D_
<span class="label label-default">Default</span>_x000D_
<span class="label label-primary">Primary</span>_x000D_
<span class="label label-success">Success</span>_x000D_
<span class="label label-info">Info</span>_x000D_
<span class="label label-warning">Warning</span>_x000D_
<span class="label label-danger">Danger</span>_x000D_
</h5>_x000D_
<h6>_x000D_
<span class="label label-default">Default</span>_x000D_
<span class="label label-primary">Primary</span>_x000D_
<span class="label label-success">Success</span>_x000D_
<span class="label label-info">Info</span>_x000D_
<span class="label label-warning">Warning</span>_x000D_
<span class="label label-danger">Danger</span>_x000D_
</h6>_x000D_
<p>_x000D_
<span class="label label-default">Default</span>_x000D_
<span class="label label-primary">Primary</span>_x000D_
<span class="label label-success">Success</span>_x000D_
<span class="label label-info">Info</span>_x000D_
<span class="label label-warning">Warning</span>_x000D_
<span class="label label-danger">Danger</span>_x000D_
</p>_x000D_
<div class="page-header">_x000D_
<h1>Badges</h1>_x000D_
</div>_x000D_
<p>_x000D_
<a href="#">Inbox <span class="badge">42</span></a>_x000D_
</p>_x000D_
<ul class="nav nav-pills" role="tablist">_x000D_
<li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a>_x000D_
</li>_x000D_
<li role="presentation"><a href="#">Profile</a>_x000D_
</li>_x000D_
<li role="presentation"><a href="#">Messages <span class="badge">3</span></a>_x000D_
</li>_x000D_
</ul>_x000D_
<div class="page-header">_x000D_
<h1>Dropdown menus</h1>_x000D_
</div>_x000D_
<div class="dropdown theme-dropdown clearfix">_x000D_
<a id="dropdownMenu1" href="#" class="sr-only dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">_x000D_
<li class="active"><a href="#">Action</a>_x000D_
</li>_x000D_
<li><a href="#">Another action</a>_x000D_
</li>_x000D_
<li><a href="#">Something else here</a>_x000D_
</li>_x000D_
<li role="separator" class="divider"></li>_x000D_
<li><a href="#">Separated link</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div class="page-header">_x000D_
<h1>Navs</h1>_x000D_
</div>_x000D_
<ul class="nav nav-tabs" role="tablist">_x000D_
<li role="presentation" class="active"><a href="#">Home</a>_x000D_
</li>_x000D_
<li role="presentation"><a href="#">Profile</a>_x000D_
</li>_x000D_
<li role="presentation"><a href="#">Messages</a>_x000D_
</li>_x000D_
</ul>_x000D_
<ul class="nav nav-pills" role="tablist">_x000D_
<li role="presentation" class="active"><a href="#">Home</a>_x000D_
</li>_x000D_
<li role="presentation"><a href="#">Profile</a>_x000D_
</li>_x000D_
<li role="presentation"><a href="#">Messages</a>_x000D_
</li>_x000D_
</ul>_x000D_
<div class="page-header">_x000D_
<h1>Navbars</h1>_x000D_
</div>_x000D_
<nav class="navbar navbar-default">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Project name</a>_x000D_
</div>_x000D_
<div class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="#">Home</a>_x000D_
</li>_x000D_
<li><a href="#about">About</a>_x000D_
</li>_x000D_
<li><a href="#contact">Contact</a>_x000D_
</li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">Action</a>_x000D_
</li>_x000D_
<li><a href="#">Another action</a>_x000D_
</li>_x000D_
<li><a href="#">Something else here</a>_x000D_
</li>_x000D_
<li role="separator" class="divider"></li>_x000D_
<li class="dropdown-header">Nav header</li>_x000D_
<li><a href="#">Separated link</a>_x000D_
</li>_x000D_
<li><a href="#">One more separated link</a>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<!--/.nav-collapse -->_x000D_
</div>_x000D_
</nav>_x000D_
<nav class="navbar navbar-inverse">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Project name</a>_x000D_
</div>_x000D_
<div class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="#">Home</a>_x000D_
</li>_x000D_
<li><a href="#about">About</a>_x000D_
</li>_x000D_
<li><a href="#contact">Contact</a>_x000D_
</li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#">Action</a>_x000D_
</li>_x000D_
<li><a href="#">Another action</a>_x000D_
</li>_x000D_
<li><a href="#">Something else here</a>_x000D_
</li>_x000D_
<li role="separator" class="divider"></li>_x000D_
<li class="dropdown-header">Nav header</li>_x000D_
<li><a href="#">Separated link</a>_x000D_
</li>_x000D_
<li><a href="#">One more separated link</a>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<!--/.nav-collapse -->_x000D_
</div>_x000D_
</nav>_x000D_
<div class="page-header">_x000D_
<h1>Alerts</h1>_x000D_
</div>_x000D_
<div class="alert alert-success" role="alert">_x000D_
<strong>Well done!</strong> You successfully read this important alert message._x000D_
</div>_x000D_
<div class="alert alert-info" role="alert">_x000D_
<strong>Heads up!</strong> This alert needs your attention, but it's not super important._x000D_
</div>_x000D_
<div class="alert alert-warning" role="alert">_x000D_
<strong>Warning!</strong> Best check yo self, you're not looking too good._x000D_
</div>_x000D_
<div class="alert alert-danger" role="alert">_x000D_
<strong>Oh snap!</strong> Change a few things up and try submitting again._x000D_
</div>_x000D_
<div class="page-header">_x000D_
<h1>Progress bars</h1>_x000D_
</div>_x000D_
<div class="progress">_x000D_
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"><span class="sr-only">60% Complete</span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="progress">_x000D_
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"><span class="sr-only">40% Complete (success)</span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="progress">_x000D_
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"><span class="sr-only">20% Complete</span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="progress">_x000D_
<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete (warning)</span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="progress">_x000D_
<div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"><span class="sr-only">80% Complete (danger)</span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="progress">_x000D_
<div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete</span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="progress">_x000D_
<div class="progress-bar progress-bar-success" style="width: 35%"><span class="sr-only">35% Complete (success)</span>_x000D_
</div>_x000D_
<div class="progress-bar progress-bar-warning" style="width: 20%"><span class="sr-only">20% Complete (warning)</span>_x000D_
</div>_x000D_
<div class="progress-bar progress-bar-danger" style="width: 10%"><span class="sr-only">10% Complete (danger)</span>_x000D_
</div>_x000D_
</div>_x000D_
<div class="page-header">_x000D_
<h1>List groups</h1>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-sm-4">_x000D_
<ul class="list-group">_x000D_
<li class="list-group-item">Cras justo odio</li>_x000D_
<li class="list-group-item">Dapibus ac facilisis in</li>_x000D_
<li class="list-group-item">Morbi leo risus</li>_x000D_
<li class="list-group-item">Porta ac consectetur ac</li>_x000D_
<li class="list-group-item">Vestibulum at eros</li>_x000D_
</ul>_x000D_
</div>_x000D_
<!-- /.col-sm-4 -->_x000D_
<div class="col-sm-4">_x000D_
<div class="list-group">_x000D_
<a href="#" class="list-group-item active">_x000D_
Cras justo odio_x000D_
</a>_x000D_
<a href="#" class="list-group-item">Dapibus ac facilisis in</a>_x000D_
<a href="#" class="list-group-item">Morbi leo risus</a>_x000D_
<a href="#" class="list-group-item">Porta ac consectetur ac</a>_x000D_
<a href="#" class="list-group-item">Vestibulum at eros</a>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.col-sm-4 -->_x000D_
<div class="col-sm-4">_x000D_
<div class="list-group">_x000D_
<a href="#" class="list-group-item active">_x000D_
<h4 class="list-group-item-heading">List group item heading</h4>_x000D_
<p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
</a>_x000D_
<a href="#" class="list-group-item">_x000D_
<h4 class="list-group-item-heading">List group item heading</h4>_x000D_
<p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
</a>_x000D_
<a href="#" class="list-group-item">_x000D_
<h4 class="list-group-item-heading">List group item heading</h4>_x000D_
<p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
</a>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.col-sm-4 -->_x000D_
</div>_x000D_
<div class="page-header">_x000D_
<h1>Panels</h1>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-sm-4">_x000D_
<div class="panel panel-default">_x000D_
<div class="panel-heading">_x000D_
<h3 class="panel-title">Panel title</h3>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
Panel content_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-primary">_x000D_
<div class="panel-heading">_x000D_
<h3 class="panel-title">Panel title</h3>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
Panel content_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.col-sm-4 -->_x000D_
<div class="col-sm-4">_x000D_
<div class="panel panel-success">_x000D_
<div class="panel-heading">_x000D_
<h3 class="panel-title">Panel title</h3>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
Panel content_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-info">_x000D_
<div class="panel-heading">_x000D_
<h3 class="panel-title">Panel title</h3>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
Panel content_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.col-sm-4 -->_x000D_
<div class="col-sm-4">_x000D_
<div class="panel panel-warning">_x000D_
<div class="panel-heading">_x000D_
<h3 class="panel-title">Panel title</h3>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
Panel content_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-danger">_x000D_
<div class="panel-heading">_x000D_
<h3 class="panel-title">Panel title</h3>_x000D_
</div>_x000D_
<div class="panel-body">_x000D_
Panel content_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!-- /.col-sm-4 -->_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).
Just a precision to Ellis Whitehead's answer. $locationProvider.html5Mode(true);
won't work with new version of angularjs without specifying the base URL for the application with a <base href="">
tag or setting the parameter requireBase
to false
If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
string connectionString= ServerName + DatabaseName + SecurityType;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
connection.Open();
bulkCopy.DestinationTableName = "TableName";
try {
bulkCopy.WriteToServer(dataTableName);
} catch (Exception e) {
Console.Write(e.Message);
}
}
Please note that the structure of the database table and the table name should be the same or it will throw an exception.
Here's a nice easy way I found:
h <- hist(g, breaks = 10, density = 10,
col = "lightgray", xlab = "Accuracy", main = "Overall")
xfit <- seq(min(g), max(g), length = 40)
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g))
yfit <- yfit * diff(h$mids[1:2]) * length(g)
lines(xfit, yfit, col = "black", lwd = 2)
Schemas contains Databases.
Databases are part of a Schema.
So, schemas > databases.
Schemas contains views, stored procedure(s), database(s), trigger(s) etc.
I could fix it by changing it to
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
}
in build.gradle file
This should display the image inline:
.content-dir-item img.mail {
display: inline-block;
*display: inline; /* for older IE */
*zoom: 1; /* for older IE */
}
I think this is the clearest way:
require 'open-uri'
File.write 'image.png', open('http://example.com/image.png').read
There are two related error messages that may tell you something is wrong with declarations and/or imports.
The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.
The second you might see, if you had a method in your States class like:
- (void)logout:(NSTimer *)timer
after adding the #import is this:
No visible @interface for "States" declares the selector 'logout:'
If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.
So in your case, you would need a:
- (void)logout:(NSTimer *)timer;
in your States class's .h to make one or both of these related errors disappear.
I have the same need and use a generic method (inside an ArrayUtils class):
public static <T> String[] toStringArray(T[] array) {
String[] result=new String[array.length];
for(int i=0; i<array.length; i++){
result[i]=array[i].toString();
}
return result;
}
And just define a STATIC inside the enum...
public static final String[] NAMES = ArrayUtils.toStringArray(values());
Java enums really miss a names() and get(index) methods, they are really helpful.
CAST uses ANSI standard. In case of portability, this will work on other platforms. CONVERT is specific to sql server. But is very strong function. You can specify different styles for dates
You can set timeouts on the underlying HTTP client. If you don't specify a client, Retrofit will create one with default connect and read timeouts. To set your own timeouts, you need to configure your own client and supply it to the RestAdapter.Builder
.
An option is to use the OkHttp client, also from Square.
1. Add the library dependency
In the build.gradle, include this line:
compile 'com.squareup.okhttp:okhttp:x.x.x'
Where x.x.x
is the desired library version.
2. Set the client
For example, if you want to set a timeout of 60 seconds, do this way for Retrofit before version 2 and Okhttp before version 3 (FOR THE NEWER VERSIONS, SEE THE EDITS):
public RestAdapter providesRestAdapter(Gson gson) {
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
return new RestAdapter.Builder()
.setEndpoint(BuildConfig.BASE_URL)
.setConverter(new GsonConverter(gson))
.setClient(new OkClient(okHttpClient))
.build();
}
EDIT 1
For okhttp versions since 3.x.x
, you have to set the dependency this way:
compile 'com.squareup.okhttp3:okhttp:x.x.x'
And set the client using the builder pattern:
final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build();
More info in Timeouts
EDIT 2
Retrofit versions since 2.x.x
also uses the builder pattern, so change the return block above to this:
return new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
If using a code like my providesRestAdapter
method, then change the method return type to Retrofit.
More info in Retrofit 2 — Upgrade Guide from 1.9
ps: If your minSdkVersion is greater than 8, you can use TimeUnit.MINUTES
:
okHttpClient.setReadTimeout(1, TimeUnit.MINUTES);
okHttpClient.setConnectTimeout(1, TimeUnit.MINUTES);
For more details about the units, see TimeUnit.
You may not need to do with group by , using sort_values
+ drop_duplicates
df.sort_values('count').drop_duplicates(['Sp','Mt'],keep='last')
Out[190]:
Sp Mt Value count
0 MM1 S1 a 3
2 MM1 S3 cb 5
8 MM4 S2 uyi 7
3 MM2 S3 mk 8
4 MM2 S4 bg 10
Also almost same logic by using tail
df.sort_values('count').groupby(['Sp', 'Mt']).tail(1)
Out[52]:
Sp Mt Value count
0 MM1 S1 a 3
2 MM1 S3 cb 5
8 MM4 S2 uyi 7
3 MM2 S3 mk 8
4 MM2 S4 bg 10
in my case there was only on issue, just put "gulp":"gulp" in the script portion, of package.json, and then use command npm run gulp.
You may have some "plain text" somewhere in php files that is interpreted as script output. It may be even a newline before or after the php script tag specifier (less-than + question mark + "php").
Besides, if I remember correctly, according to http specification, the "Location" header accepts only full URLs, not relative locations. Have that in mind too.
Try this
$(document).ready(function () {
$("#ckbCheckAll").click(function () {
$("#checkBoxes input").prop('checked', $(this).prop('checked'));
});
});
That should do it :)
The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:
date_1m_fwd <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1
Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.
Still you can perform the add month using basic R codes as follows:
library(data.table)
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]
Hope it helps.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
package
will add packaged jar
or war
to your target
folder, We can check it when, we empty the target folder (using mvn clean
) and then run mvn package
.
install
will do all the things that package
does, additionally it will add packaged jar
or war
in local repository as well. We can confirm it by checking in your .m2
folder.
Actually, this is the proper way to get what you want, unless you can use MS SQL 2014 (which finally enables custom format strings for date times).
To get yyyymm
instead of yyyym
, you can use this little trick:
select
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ right('00' + cast(datepart(month, getdate()) as varchar(2)), 2)
It's faster and more reliable than gettings parts of convert(..., 112)
.
When there is no way to modify CSS code and preload images with CSS rules for :before
or :after
pseudo elements another approach with JavaScript code traversing CSS rules of loaded stylesheets can be used. In order to make it working scripts should be included after stylesheets in HTML, for example, before closing body
tag or just after stylesheets.
getUrls() {
const urlRegExp = /url\(('|")?([^'"()]+)('|")\)?/;
let urls = [];
for (let i = 0; i < document.styleSheets.length; i++) {
let cssRules = document.styleSheets[i].cssRules;
for (let j = 0; j < cssRules.length; j++) {
let cssRule = cssRules[j];
if (!cssRule.selectorText) {
continue;
}
for (let k = 0; k < cssRule.style.length; k++) {
let property = cssRule.style[k],
urlMatch = cssRule.style[property].match(urlRegExp);
if (urlMatch !== null) {
urls.push(urlMatch[2]);
}
}
}
}
return urls;
}
preloadImages() {
return new Promise(resolve => {
let urls = getUrls(),
loadedCount = 0;
const onImageLoad = () => {
loadedCount++;
if (urls.length === loadedCount) {
resolve();
}
};
for (var i = 0; i < urls.length; i++) {
let image = new Image();
image.src = urls[i];
image.onload = onImageLoad;
}
});
}
document.addEventListener('DOMContentLoaded', () => {
preloadImages().then(() => {
// CSS images are loaded here
});
});
If you are using Docker make sure you are not using the same port in another service, in my case i was mistakenly using the same port for both PostgreSQL and Redis.
That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:
While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g.
field1=value1&field1=value2&field2=value3
).[4][5]
Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.
foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]
The request.getParameter("foo")
will also work on it, but it'll return only the first value.
String foo = request.getParameter("foo"); // value1
And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces []
in order to trigger the language to return an array of values instead of a single value.
foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true
In case you still use foo=value1&foo=value2&foo=value3
, then it'll return only the first value.
$foo = $_GET["foo"]; // value1
echo is_array($foo); // false
Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3
to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.
String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]
Use the open source okHttp
library from Square. okHttp
works from Android 2.3 and up and has an Apache 2.0 license on GitHub.
Sending POST data is as simple as adding the following in an AsyncTask:
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("email", emailString) // A sample POST field
.add("comment", commentString) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("https://yourdomain.org/callback.php") // The URL to send the data to
.post(formBody)
.build();
okHttp
also has a namespace on maven, so adding it to your Android Studio project is simple. Just add compile 'com.squareup.okhttp3:okhttp:3.11.0'
to your app's build.gradle.
Complete Code
Add the following to your activity:
public class CallAPI extends AsyncTask<String, String, String> {
String emailString;
String commentString;
public CallAPI(String email, String commnt){
emailString = email;
commentString = commnt;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("email", emailString) // A sample POST field
.add("comment", commentString) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("https://yourdomain.org/callback.php") // The URL to send the data to
.post(formBody)
.build();
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
And call it using:
new CallAPI(emailString, commentString).execute();
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
For linux environments, you can use xdg-open
. It is installed by default on most distributions. The benefit over the accepted answer is that it opens the user's preferred browser.
$ xdg-open https://google.com
$ xdg-open steam://run/10
Of course you can wrap this in a system()
call.
If you want to know what impact has single object context for WPF / WinForm application check this article. It is about NHibernate Session but the idea is same.
Edit:
When you use EF it by default loads each entity only once per context. The first query creates entity instace and stores it internally. Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query. This is called Identity map pattern. You can force the object context to reload the entity but it will reload a single shared instance.
Any changes made to the entity are not persisted until you call SaveChanges
on the context. You can do changes in multiple entities and store them at once. This is called Unit of Work pattern. You can't selectively say which modified attached entity you want to save.
Combine these two patterns and you will see some interesting effects. You have only one instance of entity for the whole application. Any changes to the entity affect the whole application even if changes are not yet persisted (commited). In the most times this is not what you want. Suppose that you have an edit form in WPF application. You are working with the entity and you decice to cancel complex editation (changing values, adding related entities, removing other related entities, etc.). But the entity is already modified in shared context. What will you do? Hint: I don't know about any CancelChanges or UndoChanges on ObjectContext
.
I think we don't have to discuss server scenario. Simply sharing single entity among multiple HTTP requests or Web service calls makes your application useless. Any request can just trigger SaveChanges
and save partial data from another request because you are sharing single unit of work among all of them. This will also have another problem - context and any manipulation with entities in the context or a database connection used by the context is not thread safe.
Even for a readonly application a global context is not a good choice because you probably want fresh data each time you query the application.
finally I found... it will work nice when table displays only 3 rows... if rows are more change should be accordingly...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * theCell = (UITableViewCell *)[tableView
cellForRowAtIndexPath:indexPath];
CGPoint tableViewCenter = [tableView contentOffset];
tableViewCenter.y += myTable.frame.size.height/2;
[tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
[tableView reloadData];
}
I wish I still had a link to the source that lead me in this direction, but this is the code that ended up working for me. By looking over the JavaDoc for X509TrustManager it looks like the way the TrustManager
s work is by returning nothing on successful validation, otherwise throwing an exception. Thus, with a null implementation, it is treated as a successful validation. Then you remove all other implementations.
import javax.net.ssl.*;
import java.security.*;
import java.security.cert.X509Certificate;
public final class SSLUtil{
private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers(){
return null;
}
public void checkClientTrusted( X509Certificate[] certs, String authType ){}
public void checkServerTrusted( X509Certificate[] certs, String authType ){}
}
};
public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init( null, UNQUESTIONING_TRUST_MANAGER, null );
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
// Return it to the initial state (discovered by reflection, now hardcoded)
SSLContext.getInstance("SSL").init( null, null, null );
}
private SSLUtil(){
throw new UnsupportedOperationException( "Do not instantiate libraries.");
}
}
Click on settings in top tool bar;
Click on debugger;
In tree, highlight "gdb/cdb debugger" by clicking it
Click "create configuration"
Add "gdb.exe" (no quotes) as a configuration
Delete default configuration
Click on gdb.exe
that you created in the tree (it should be the only one) and a dialogue will appear to the right for "executable path" with a button to the right.
Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe
(it sort of finds itself).
something like this? http://codepen.io/Nunotmp/pen/wKjvB
You can add an empty div
and use absolute positioning.
to escape non-alphanumeric characters of string variables, including dots, you could use re.escape
:
import re
expression = 'whatever.v1.dfc'
escaped_expression = re.escape(expression)
print(escaped_expression)
output:
whatever\.v1\.dfc
you can use the escaped expression to find/match the string literally.
First Issue: You want to run Mysql server from Mysql and from Xampp also want to browse phpmyadmin so that you can operate database.Then follow the rules:
From "Xampp/phpmyadmin" directory in config.inc.php file find the below code. And follow the given instructions below. I have tried like this and I was successful to run both localhost/phpMyAdmin on browser, MySQL Command prompt as well as MySQL query browser.
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'pma';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['controluser'] = 'user_name/root';
$cfg['Servers'][$i]['controlpass'] = 'passwaord';
And replace the above each statement with the below each corresponding code.
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'Muhammad Ashikuzzaman';
$cfg['Servers'][$i]['controluser'] = 'root';
$cfg['Servers'][$i]['controlpass'] = 'Muhammad Ashikuzzaman';
Second Issue: Way 1 : You can quit Skype first. And when Apche server is started then again you can run Skype. If you want to run Apache in another port then replace in xampp/apache/conf/httpd.conf "ServerName localhost:80" by "ServerName localhost:81" At line 184. After that even it may not work. Then replace
#Listen 0.0.0.0:80
#Listen [::]:80
Listen 80
by
#Listen 0.0.0.0:81
#Listen [::]:81
Listen 81
at line 45
Way 2 : If you want to use port 80. Then follow this. In Windows 8 “World Wide Publishing Service is using this port and stopping this service will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop. If you don't find there then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.
If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80.
And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.
Here's some more good practices around Timer use:
http://tech.puredanger.com/2008/09/22/timer-rules/
In general, I'd use Timer for quick and dirty stuff and Executor for more robust usage.
Installing angular cli globally solved my problem.
npm install -g @angular/cli
I found the solution, Thanks all for reply.
category = (Categoies)AutoMapper.Mapper.Map(viewModel, category, typeof(CategoriesViewModel), typeof(Categoies));
But, I have already dont know the reason. I cant understand fully.
1) create a .gitignore file, so to do that, you just create a .txt file and change the extention as following:
then you have to change the name writing the following line on the cmd:
rename git.txt .gitignore
where git.txt is the name of the file you've just created.
Then you can open the file and write all the files you don´t want to add on the repository. For example mine looks like this:
#OS junk files
[Tt]humbs.db
*.DS_Store
#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
*.pyc
*.xml
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad
#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*
#Project files
[Bb]uild/
#Subversion files
.svn
# Office Temp Files
~$*
Once you have this, you need to add it to your git repository. You have to save the file where your repository is.
Then in your git bash you have to write the following line:
If the respository already exists then you have to do the following:
1) git rm -r --cached . 2) git add . 3) git commit -m ".gitignore is now working"
If the step 2 dowsn´t work then you should write the hole route of the files that you would like to add.
Hope it helps!
On my Mac:
/System/Library/Frameworks/JavaVM.framework/Home/
btw, did you tried which java
?
One way to make sure it is correct is by using character instead of ascii code.
if ((a >= 65) && (a <= 90))
what you want is to lower a case. it's better to use something like if (a >= 'A' && a <= 'Z')
. You don't have to remind all ascii code :)
It seems like you want barplot(prop.table(table(animals)))
:
However, this is not a histogram.
Same situation with pycharm community edition, so, as for cmd, you must restart your ide in order to reload path variables. Restart your ide and it should be fine.
I used this:
HTMLDatetoIsoDate(htmlDate){
let year = Number(htmlDate.toString().substring(0, 4))
let month = Number(htmlDate.toString().substring(5, 7))
let day = Number(htmlDate.toString().substring(8, 10))
return new Date(year, month - 1, day)
}
isoDateToHtmlDate(isoDate){
let date = new Date(isoDate);
let dtString = ''
let monthString = ''
if (date.getDate() < 10) {
dtString = '0' + date.getDate();
} else {
dtString = String(date.getDate())
}
if (date.getMonth()+1 < 10) {
monthString = '0' + Number(date.getMonth()+1);
} else {
monthString = String(date.getMonth()+1);
}
return date.getFullYear()+'-' + monthString + '-'+dtString
}
Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/
ORA-00907: missing right parenthesis
This is one of several generic error messages which indicate our code contains one or more syntax errors. Sometimes it may mean we literally have omitted a right bracket; that's easy enough to verify if we're using an editor which has a match bracket capability (most text editors aimed at coders do). But often it means the compiler has come across a keyword out of context. Or perhaps it's a misspelled word, a space instead of an underscore or a missing comma.
Unfortunately the possible reasons why our code won't compile is virtually infinite and the compiler just isn't clever enough to distinguish them. So it hurls a generic, slightly cryptic, message like ORA-00907: missing right parenthesis
and leaves it to us to spot the actual bloomer.
The posted script has several syntax errors. First I will discuss the error which triggers that ORA-0097 but you'll need to fix them all.
Foreign key constraints can be declared in line with the referencing column or at the table level after all the columns have been declared. These have different syntaxes; your scripts mix the two and that's why you get the ORA-00907.
In-line declaration doesn't have a comma and doesn't include the referencing column name.
CREATE TABLE historys_T (
history_record VARCHAR2 (8),
customer_id VARCHAR2 (8)
CONSTRAINT historys_T_FK FOREIGN KEY REFERENCES T_customers ON DELETE CASCADE,
order_id VARCHAR2 (10) NOT NULL,
CONSTRAINT fk_order_id_orders REFERENCES orders ON DELETE CASCADE)
Table level constraints are a separate component, and so do have a comma and do mention the referencing column.
CREATE TABLE historys_T (
history_record VARCHAR2 (8),
customer_id VARCHAR2 (8),
order_id VARCHAR2 (10) NOT NULL,
CONSTRAINT historys_T_FK FOREIGN KEY (customer_id) REFERENCES T_customers ON DELETE CASCADE,
CONSTRAINT fk_order_id_orders FOREIGN KEY (order_id) REFERENCES orders ON DELETE CASCADE)
Here is a list of other syntax errors:
HISTORYS_T
before you have created the referenced ORDERS
table.LIBRARY_T
and FORMAT_T
). DATE DEFAULT sysdate
.Looking at our own code with a cool eye is a skill we all need to gain to be successful as developers. It really helps to be familiar with Oracle's documentation. A side-by-side comparison of your code and the examples in the SQL Reference would have helped you resolved these syntax errors in considerably less than two days. Find it here (11g) and here (12c).
As well as syntax errors, your scripts contain design mistakes. These are not failures, but bad practice which should not become habits.
HISTORY_T
has constraints called historys_T_FK
and fk_order_id_orders
, neither of which is helpful. A useful convention is <child_table>_<parent_table>_fk
. So history_customer_fk
and history_order_fk
respectively.LIBRARY_T
and FORMATS
. You could do this by creating the constraints in separate statement but don't: you will have problems when inserting rows and even worse problems with deletions. You should reconsider your data model and find a way to model the relationship between the two tables so that one is the parent and the other the child. Or perhaps you need a different kind of relationship, such as an intersection table.LIBRARY_T
is ugly. Try to find a more expressive name which doesn't require a needless suffix to avoid a keyword clash.T_CUSTOMERS
is even uglier, being both inconsistent with your other tables and completely unnecessary, as customers
is not a keyword.Naming things is hard. You wouldn't believe the wrangles I've had about table names over the years. The most important thing is consistency. If I look at a data dictionary and see tables called T_CUSTOMERS
and LIBRARY_T
my first response would be confusion. Why are these tables named with different conventions? What conceptual difference does this express? So, please, decide on a naming convention and stick to. Make your table names either all singular or all plural. Avoid prefixes and suffixes as much as possible; we already know it's a table, we don't need a T_
or a _TAB
.
The model (@Model
) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.
What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor
will suffice.
However, you will want to change your foreach loop to a for loop. The final solution will look something like this:
for (int i = 0 ; i < Model.Post; i++)
{
<br/>
<b>Posted by :</b> @Model.Post[i].Username <br/>
<span>@Model.Post[i].Content</span> <br/>
if(Model.loginuser == Model.username)
{
@Html.HiddenFor(model => model.Post[i].PostID)
@Html.TextAreaFor(model => model.addcomment.Content)
<button type="submit">Add Comment</button>
}
}
You could just try the scandir(Path)
function. it is fast and easy to implement
Syntax:
$files = scandir("somePath");
This Function returns a list of file into an Array.
to view the result, you can try
var_dump($files);
Or
foreach($files as $file)
{
echo $file."< br>";
}
public class AesCryptoService
{
private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");
public static string EncryptStringToBytes_Aes(string plainText)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
public static string DecryptStringFromBytes_Aes(string Text)
{
if (Text == null || Text.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
string plaintext = null;
byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>
@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"
Removes (deletes) a directory.
RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path /S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree. /Q Quiet mode, do not ask if ok to remove a directory tree with /S
There are some "catchy interview" questions, such as why you get equals! if you execute the below piece of code.
String s1 = "testString";
String s2 = "testString";
if(s1 == s2) System.out.println("equals!");
If you want to compare Strings you should use equals()
. The above will print equals because the testString
is already interned for you by the compiler. You can intern the strings yourself using intern method as is shown in previous answers....
Redirecting stdout to a file might also be useful for this purpose:
from contextlib import redirect_stdout
with open('test.txt', 'w') as f:
with redirect_stdout(f):
for i in range(mylst.size):
print(mylst[i])
SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;
In case if someone is having an issue using extract.
Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error.
You can select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT'
to see what error(s) the trigger actually gets and why it won't compile. In this case it appears you're missing a semicolon at the end of the insert
line:
INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger')
So make it:
CREATE OR REPLACE TRIGGER newAlert
AFTER INSERT OR UPDATE ON Alerts
BEGIN
INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger');
END;
/
If you get a compilation warning when you do that you can do show errors
if you're in SQL*Plus or SQL Developer, or query user_errors
again.
Of course, this assumes your Users
tables does have those column names, and they are all varchar2
... but presumably you'll be doing something more interesting with the trigger really.
It can be done using % operator. i.e. SELECT 50 % 5
If you are using a nodeJS server, you can use this library, it worked fine for me https://github.com/expressjs/cors
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
and after you can do an npm update
.
This can happen when trying to install a debug/unsigned APK on top of a signed release APK from the Play store.
H:\>adb install -r "Signed.apk"
2909 KB/s (220439 bytes in 0.074s)
pkg: /data/local/tmp/Signed.apk
Success
H:\>adb install -r "AppName.apk"
2753 KB/s (219954 bytes in 0.078s)
pkg: /data/local/tmp/AppName.apk
Failure [INSTALL_FAILED_VERSION_DOWNGRADE]
The solution to this is to uninstall and then reinstall or re run it from the IDE.
The problem I was having, which I think is similar to this, is that master was too far ahead of my branch point for the history to be useful. (Navigating to the branch point would take too long.)
After some trial and error, this gave me roughly what I wanted:
git log --graph --decorate --oneline --all ^master^!
we can simply use:
public void animStart(View view) {
if(count==0){
Log.d("count", String.valueOf(count));
i1.animate().alpha(0f).setDuration(2000);
i2.animate().alpha(1f).setDuration(2000);
count =1;
}
else if(count==1){
Log.d("count", String.valueOf(count));
count =0;
i2.animate().alpha(0f).setDuration(2000);
i1.animate().alpha(1f).setDuration(2000);
}
}
where i1 and i2 are defined in the onCreateView() as:
i1 = (ImageView)findViewById(R.id.firstImage);
i2 = (ImageView)findViewById(R.id.secondImage);
count is a class variable initilaized to 0.
The XML file is :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/secondImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="animStart"
android:src="@drawable/second" />
<ImageView
android:id="@+id/firstImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="animStart"
android:src="@drawable/first" />
</RelativeLayout>
@drawable/first and @drawable/second are the images in the drawable folder in res.
Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.
How to create a resource:
In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.
How to use a resource:
Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.
There is a static class called Properties.Resources
that gives you access to all your resources, so my code ended up being as simple as:
paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
Done! Finished! Everything is simple when you know how, isn't it?
This worked for me with a string-array named shoes
loaded from the projects resources:
Spinner spinnerCountShoes = (Spinner)findViewById(R.id.spinner_countshoes);
ArrayAdapter<String> spinnerCountShoesArrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.shoes));
spinnerCountShoes.setAdapter(spinnerCountShoesArrayAdapter);
This is my resource file (res/values/arrays.xml
) with the string-array named shoes
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="shoes">
<item>0</item>
<item>5</item>
<item>10</item>
<item>100</item>
<item>1000</item>
<item>10000</item>
</string-array>
</resources>
With this method it's easier to make it multilingual (if necessary).
The Separator
you are using is a UI component. You would be better using a simple String sep = ", "
.
A bit old question but I found myself needing this also and that the suggestions above were inaduquate - and as such - developed a thin wrapper myself: https://github.com/hofmeister/MatchIt
Very useful post, to add NSDictionary support as well one small change
static inline BOOL isEmpty(id thing) {
return thing == nil
|| [thing isKindOfClass:[NSNull class]]
|| ([thing respondsToSelector:@selector(length)]
&& ![thing respondsToSelector:@selector(count)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [thing count] == 0);
}
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysqli_query($link, $sqlimage);
while($rows=mysqli_fetch_assoc($imageresult1))
{
echo "<img src = 'Image/".$row['image'].'" />';
}
java.lang.String
class has method substring
not substr
, thats the error in your program.
Moreover you can do this in one single line if you are ok in using regular expression.
a.replaceAll("\\s+","");
In linux you can use this commande :
for exemple i want to delete "*.py~" so my command should be ==>
find . -name "*.py~" -exec rm -f {} \;
Found on dotnet-snippets.de
With reflection this works and sets the real RootFolder!
using System;
using System.Reflection;
using System.Windows.Forms;
namespace YourNamespace
{
public class RootFolderBrowserDialog
{
#region Public Properties
/// <summary>
/// The description of the dialog.
/// </summary>
public string Description { get; set; } = "Chose folder...";
/// <summary>
/// The ROOT path!
/// </summary>
public string RootPath { get; set; } = "";
/// <summary>
/// The SelectedPath. Here is no initialization possible.
/// </summary>
public string SelectedPath { get; private set; } = "";
#endregion Public Properties
#region Public Methods
/// <summary>
/// Shows the dialog...
/// </summary>
/// <returns>OK, if the user selected a folder or Cancel, if no folder is selected.</returns>
public DialogResult ShowDialog()
{
var shellType = Type.GetTypeFromProgID("Shell.Application");
var shell = Activator.CreateInstance(shellType);
var folder = shellType.InvokeMember(
"BrowseForFolder", BindingFlags.InvokeMethod, null,
shell, new object[] { 0, Description, 0, RootPath, });
if (folder is null)
{
return DialogResult.Cancel;
}
else
{
var folderSelf = folder.GetType().InvokeMember(
"Self", BindingFlags.GetProperty, null,
folder, null);
SelectedPath = folderSelf.GetType().InvokeMember(
"Path", BindingFlags.GetProperty, null,
folderSelf, null) as string;
// maybe ensure that SelectedPath is set
return DialogResult.OK;
}
}
#endregion Public Methods
}
}
The easiest way is to use JarURLConnection class :
String className = getClass().getSimpleName() + ".class";
String classPath = getClass().getResource(className).toString();
if (!classPath.startsWith("jar")) {
return DEFAULT_PROPERTY_VALUE;
}
URL url = new URL(classPath);
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
Manifest manifest = jarConnection.getManifest();
Attributes attributes = manifest.getMainAttributes();
return attributes.getValue(PROPERTY_NAME);
Because in some cases ...class.getProtectionDomain().getCodeSource().getLocation();
gives path with vfs:/
, so this should be handled additionally.
The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.
SUMMARY
class_weight="balanced"
works decent in the absence of you wanting to optimize manuallyclass_weight="balanced"
you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
NB
The result might differ when using RF or GBM. sklearn does not have class_weight="balanced"
for GBM but lightgbm has LGBMClassifier(is_unbalance=False)
CODE
# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd
# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same
# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last
print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%
print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE
try this:
$('div[id^="player_"]')
This error getting because of the compiler not getting 'Context' class in your application. So, you can add it manually by Add --> Class and inherit it with 'DbContext' Class For Example :
public class MyDbContext : DbContext
{
public DbSet<Customer> Customer { get; set; }
public MyDbContext()
{
}
}
The XPath turns into this:
Get me all of the div elements that have an id equal to container.
As for getting the first etc, you have two options.
Turn it into a .findElement()
- this will just return the first one for you anyway.
or
To explicitly do this in XPath, you'd be looking at:
(//div[@id='container'])[1]
for the first one, for the second etc:
(//div[@id='container'])[2]
Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:
(//div[@id='container'])[last()]
Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.
As for getting the parent 'node', well, you can use parent:
//div[@id='container']/parent::*
That would get the div's direct parent.
You could then go further and say I want the first *div* with an id of container, and I want his parent:
(//div[@id='container'])[1]/parent::*
Hope that helps!
After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:
In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:
http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html
Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.
Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .
Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:
@Resource
private SessionContext sessionContext;
With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation
EJB.
I also looked around for the best way to logout. The best one that I've found is using a Servlet:
@WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
public class LogoutServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
// Destroys the session for this user.
if (session != null)
session.invalidate();
// Redirects back to the initial page.
response.sendRedirect(request.getContextPath());
}
}
Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.
Ciao,
Vítor Souza
I find it a lot cleaner to pass an @INPUT variable if you have access to the child component code:
The idea is that the parent tells the child what its state of appearance should be, and the child decides how to display the state. It's a nice architecture
SCSS Way:
.active {
::ng-deep md-list-item {
background-color: #eee;
}
}
Better way: - use selected
variable:
<md-list>
<a
*ngFor="let convo of conversations"
routerLink="/conversations/{{convo.id}}/messages"
#rla="routerLinkActive"
routerLinkActive="active">
<app-conversation
[selected]="rla.isActive"
[convo]="convo"></app-conversation>
</a>
</md-list>
Adding to olliej's answer, you can convert from an int back to a string with NSNumber
's stringValue
:
[[NSNumber numberWithInt:myInt] stringValue]
stringValue
on an NSNumber
invokes descriptionWithLocale:nil
, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:@"%d",myInt]
will give you a properly localized reprsentation of myInt
.
Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.
With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
And here's the output:
Quoting this article https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
Maximum Path Length Limitation
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)
Now we see that it is 1+2+256+1 or [drive][:\][path][null] = 260. One could assume that 256 is a reasonable fixed string length from the DOS days. And going back to the DOS APIs we realize that the system tracked the current path per drive, and we have 26 (32 with symbols) maximum drives (and current directories).
The INT 0x21 AH=0x47 says “This function returns the path description without the drive letter and the initial backslash.” So we see that the system stores the CWD as a pair (drive, path) and you ask for the path by specifying the drive (1=A, 2=B, …), if you specify a 0 then it assumes the path for the drive returned by INT 0x21 AH=0x15 AL=0x19. So now we know why it is 260 and not 256, because those 4 bytes are not stored in the path string.
Why a 256 byte path string, because 640K is enough RAM.
I'm assuming that id
is supposed to be an incrementing value.
You need to set this, or else if you have a non-nullable column, with no default value, if you provide no value it will error.
To set up auto-increment in SQL Server Management Studio:
Design
Column Properties
Indentity Specification
, set (Is Identity)=Yes
and Indentity Increment=1
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
use this
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Default"]];
a {
outline: 0;
}
But read this before change it:
For Change The color
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="?attr/colorPrimary"
/>
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
myToolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(), R.color.Auth_Background));
setSupportActionBar(myToolbar);
Python's *.py file is just a text file in which you write some lines of code. When you try to execute this file using say "python filename.py"
This command invokes Python Virtual Machine. Python Virtual Machine has 2 components: "compiler" and "interpreter". Interpreter cannot directly read the text in *.py file, so this text is first converted into a byte code which is targeted to the PVM (not hardware but PVM). PVM executes this byte code. *.pyc file is also generated, as part of running it which performs your import operation on file in shell or in some other file.
If this *.pyc file is already generated then every next time you run/execute your *.py file, system directly loads your *.pyc file which won't need any compilation(This will save you some machine cycles of processor).
Once the *.pyc file is generated, there is no need of *.py file, unless you edit it.
The solution is simple. Sometimes the Eclipse Windows → Preferences → Java → Installed JREs pointing to C:\Program files\Java\jre
.
When I changed it to C:\Program files\Java\JDK 6.0\jre
it is worked 100%.
PHPWord can generate Word documents in docx format. It can also use an existing .docx file as a template - template variables can be added to the document in the format ${varname}
It has an LGPL license and the examples that came with the code worked nicely for me.
Try
/etc/init.d/tomcat stop
(maybe you have to write something after tomcat
, just press tab one time)
Edit: And you also need to do it as root.
The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.
This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.
If you still want to use ad-hoc transactions, you can always execute
BEGIN TRANSACTION
within SSMS, and than the system waits for you to commit the data.
If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in
Tools -> Options -> Query Execution -> SQL Server -> ANSI
Would sending the mail as plain-text sort this?
"How to Send a Plain Text Message in Outlook":
- Select Actions | New Mail Message Using | Plain Text from the menu in Outlook.
- Create your message as usual.
- Click Send to deliver it.
Being plain text it shouldn't screw up your code, with "smart" quotes, auto-capitalisation and such.
Another possible option, if this is a common problem within the company perhaps you could setup an internal code-paste site, there's plenty of open-source ones around, like Open Pastebin
The solutions of Fabricio works just fine.
A very common usecase of calc is add 100% width and adding some margin around the element.
One can do so with:
@someMarginVariable: 15px;
margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);
width: -o-calc(~"100% - "@someMarginVariable*2);
Or can use a mixin like:
.fullWidthMinusMarginPaddingMixin(@marginSize,@paddingSize) {
@minusValue: (@marginSize+@paddingSize)*2;
padding: @paddingSize;
margin: @marginSize;
width: calc(~"100% - "@minusValue);
width: -moz-calc(~"100% - "@minusValue);
width: -webkit-calc(~"100% - "@minusValue);
width: -o-calc(~"100% - "@minusValue);
}
The issue of changing the context path of a Spring application is handled very well in the post titled Spring Boot Change Context Path
Basically the post discusses multiple ways of realizing this viz.
via constructor of a Runnable or Thread class
class MyThread extends Thread {
private String to;
public MyThread(String to) {
this.to = to;
}
@Override
public void run() {
System.out.println("hello " + to);
}
}
public static void main(String[] args) {
new MyThread("world!").start();
}
I know there are several answers, but i think the best and most simple is using a state "To change" is the state purpose.
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
style: {
backgroundColor: "white"
}
};
}
onPress = function() {
this.setState({style: {backgroundColor: "red"}});
}
render() {
return (
...
<View style={this.state.style}></View>
...
)
}
}
With delay and fade :
setTimeout(function(){
$(".alert").each(function(index){
$(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
$(this).remove();
});
});
},2000);
When you have own struct
, you could have own convert-to-string function.
package main
import (
"fmt"
)
type Color struct {
Red int `json:"red"`
Green int `json:"green"`
Blue int `json:"blue"`
}
func (c Color) String() string {
return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}
func main() {
c := Color{Red: 123, Green: 11, Blue: 34}
fmt.Println(c) //[123, 11, 34]
}
First, set up a loading image in a div. Next, get the div element. Then, set a function that edits the css to make the visibility to "hidden". Now, in the <body>
, put the onload to the function name.
I've just had a very similar problem, where I couldn't get npm to work behind our proxy server.
My username is of the form "domain\username" - including the slash in the proxy configuration resulted in a forward slash appearing. So entering this:
npm config set proxy "http://domain\username:password@servername:port/"
then running this npm config get proxy
returns this:
http://domain/username:password@servername:port/
Therefore to fix the problem I instead URL encoded the backslash, so entered this:
npm config set proxy "http://domain%5Cusername:password@servername:port/"
and with this the proxy access was fixed.
Following the @greg0ire suggestion in comments:
<input type="submit" name="add_tag" value="Lägg till tag" />
In your server side, you'll do something like:
if (request.getParameter("add_tag") != null)
tags.addTag( /*...*/ );
(Since I don't know that language (java?), there may be syntax errors.)
I would prefer the <button>
solution, but it doesn't work as expected on IE < 9.
EDIT: I haven't tried this, so I can't vouch for it! And you already know you shouldn't be doing this, so please don't do it. BUT...
Try looking here: http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx
The key bit is this bit which I have attempted to tweak for your purposes:
DECLARE @SQL varchar(500)
SELECT @SQL = 'osql -S' +@@servername +' -E -q "exec dbName..sprocName "'
EXEC master..xp_cmdshell @SQL
In my case, I forgot to tell the type controller that the response is a JSON object. response.setContentType("application/json");
Tested these options with python3.5 and pip 9.0.3:
pip install --target /myfolder [packages]
Installs ALL packages including dependencies under /myfolder. Does not take into account that dependent packages are already installed elsewhere in Python. You will find packages from /myfolder/[package_name]. In case you have multiple Python versions, this doesn't take that into account (no Python version in package folder name).
pip install --prefix /myfolder [packages]
Checks are dependencies already installed. Will install packages into /myfolder/lib/python3.5/site-packages/[packages]
pip install --root /myfolder [packages]
Checks dependencies like --prefix but install location will be /myfolder/usr/local/lib/python3.5/site-packages/[package_name].
pip install --user [packages]
Will install packages into $HOME: /home/[USER]/.local/lib/python3.5/site-packages Python searches automatically from this .local path so you don't need to put it to your PYTHONPATH.
=> In most of the cases --user is the best option to use. In case home folder can't be used because of some reason then --prefix.
Or you can try ignoreElements()
as well
Thanks everyone who helped. After doing some research myself (I'm the guy who asked the question), here is what I found to make sense most:
Database column type: the timezone-agnostic number of milliseconds since 1970 represented as decimal(20)
because 2^64 has 20 digits and disk space is cheap; let's be straightforward. Also, I will use neither DEFAULT CURRENT_TIMESTAMP
, nor triggers. I want no magic in the DB.
Java field type: long
. The Unix timestamp is well supported across various libs, long
has no Y2038 problems, timestamp arithmetic is fast and easy (mainly operator <
and operator +
, assuming no days/months/years are involved in the calculations). And, most importantly, both primitive long
s and java.lang.Long
s are immutable—effectively passed by value—unlike java.util.Date
s; I'd be really pissed off to find something like foo.getLastUpdate().setTime(System.currentTimeMillis())
when debugging somebody else's code.
The ORM framework should be responsible for filling in the data automatically.
I haven't tested this yet, but only looking at the docs I assume that @Temporal
will do the job; not sure about whether I might use @Version
for this purpose. @PrePersist
and @PreUpdate
are good alternatives to control that manually. Adding that to the layer supertype (common base class) for all entities, is a cute idea provided that you really want timestamping for all of your entities.
You can also get the 500 error if you add your own assembly that contains the ApiController by overriding GetAssemblies of the DefaultAssembliesResolver and it is already in the array from base.GetAssemblies()
Case in point:
public class MyAssembliesResolver : DefaultAssembliesResolver
{
public override ICollection<Assembly> GetAssemblies()
{
var baseAssemblies = base.GetAssemblies();
var assemblies = new List<Assembly>(baseAssemblies);
assemblies.Add(Assembly.GetAssembly(typeof(MyAssembliesResolver)));
return new List<Assembly>(assemblies);
}
}
if the above code is in the same assembly as your Controller, that assembly will be in the list twice and will generate a 500 error since the Web API doesn't know which one to use.
There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false,"
code line in main .dart file. So I think these methods are effective:
"Dart DevTools"
from extensions. After installation, you can easily find "Dart DevTools"
text icon at the bottom of the VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown in this screenshot.NOTE:-- Dart DevTools is a dart language debugger extension in VS Code
Dart DevTools
is already installed in your VS Code, then you can directly open the google chrome and open this URL = "127.0.0.1: ZZZZZ/?hide=debugger&port=XXXXX"
NOTE:-- In this link replace "XXXXX" by 5 digit port-id (on which your flutter app is running) which will vary whenever you use "flutter run"
command and replace "ZZZZZ" by your global(unchangeable) 5 digit debugger-id
NOTE:-- these dart dev tools are only for "Google Chrome Browser"
A good option is to transform the number into a string and then split it.
// Decimal number
let number = 3.2;
// Convert it into a string
let string = number.toString();
// Split the dot
let array = string.split('.');
// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber = +array[0]; // 3
let secondNumber = +array[1]; // 2
let [firstNumber, secondNumber] = [+number.toString().split('.')[0], +number.toString().split('.')[1]];
If your exe takes arguments,
start MyApp.exe -arg1 -arg2
Straightforward way to make deep copy of original list is to add all element from one list to another list.
ArrayList<Object> originalList = new ArrayList<Object>();
ArrayList<Object> duplicateList = new ArrayList<Object>();
for(Object o : originalList) {
duplicateList.add(o);
}
Now If you make any changes to originalList it will not impact duplicateList.
I set CurrentCulture
and CurrentUICulture
my custom base controller
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
}
First, reset any changes
This will undo any changes you've made to tracked files and restore deleted files:
git reset HEAD --hard
Second, remove new files
This will delete any new files that were added since the last commit:
git clean -fd
Files that are not tracked due to .gitignore
are preserved; they will not be removed
Warning: using -x
instead of -fd
would delete ignored files. You probably don't want to do this.
In single line to print the element or array.
print $_ for (@array);
NOTE: remember that $_ is internally referring to the element of @array in loop. Any changes made in $_ will reflect in @array; ex.
my @array = qw( 1 2 3 );
for (@array) {
$_ = $_ *2 ;
}
print "@array";
output: 2 4 6
StudentList studentList = mapper.readValue(jsonString,StudentList.class);
Change this to this one
StudentList studentList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
Yes - it means you're using \n
as the line break instead of \r\n
. Notepad only understands the latter.
(Note that Environment.NewLine
suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n
, you should specify it explicitly.)
Please Try this code margin-left:60px
instead of left:60px
please take a look: http://jsfiddle.net/hbirjand/2LtBh/2/
as @Shomz said,transition must be changed to transition:margin 1s linear;
instead of transition:all 1s linear;
Q1:
$(document).ready(function() {
var totalMinutes = $('.totalMin').html();
var hours = Math.floor(totalMinutes / 60);
var minutes = totalMinutes % 60;
$('.convertedHour').html(hours);
$('.convertedMin').html(minutes);
});
Q2:
$(document).ready(function() {
var minutes = 0;
$('.min').each(function() {
minutes = parseInt($(this).html()) + minutes;
});
var realmin = minutes % 60
var hours = Math.floor(minutes / 60)
$('.hour').each(function() {
hours = parseInt($(this).html()) + hours;
});
$('.totalHour').html(hours);
$('.totalMin').html(realmin);
});
num1 = 20 * someBoolValue or num1
The name of the resource is the name space plus the "pseudo" name space of the path to the file. The "pseudo" name space is made by the sub folder structure using \ (backslashes) instead of . (dots).
public static Stream GetResourceFileStream(String nameSpace, String filePath)
{
String pseduoName = filePath.Replace('\\', '.');
Assembly assembly = Assembly.GetExecutingAssembly();
return assembly.GetManifestResourceStream(nameSpace + "." + pseduoName);
}
The following call:
GetResourceFileStream("my.namespace", "resources\\xml\\my.xml")
will return the stream of my.xml located in the folder-structure resources\xml in the name space: my.namespace.
Declare a delegate, assign your text field to the delegate and then include these methods.
Assuming you have a login form with email and password text fields, this code will fit perfectly:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.emailTextField resignFirstResponder];
[self.passwordTextField resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (self.emailTextField == textField) {
[self.passwordTextField becomeFirstResponder];
} else {
[self.emailTextField resignFirstResponder];
[self.passwordTextField resignFirstResponder];
}
return NO;
}
- (void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - keyboard movements
- (void)keyboardWillShow:(NSNotification *)notification
{
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
[UIView animateWithDuration:0.3 animations:^{
CGRect f = self.view.frame;
f.origin.y = -0.5f * keyboardSize.height;
self.view.frame = f;
}];
}
-(void)keyboardWillHide:(NSNotification *)notification
{
[UIView animateWithDuration:0.3 animations:^{
CGRect f = self.view.frame;
f.origin.y = 0.0f;
self.view.frame = f;
}];
}
-
WHERE SUBSTR('Hello world', -4)