I had this same problem after I dropped the special PhpMyAdmin controluser account from MySQL.
I had to update the config.inc.php file and replace the entries for 'controluser' and controlpass' with 'user' and 'password'.
So my file ended like this:
$cfg['Servers'][$i]['user'] = 'root'; $cfg['Servers'][$i]['password']='123456';
you can use rindex()
function to get the last occurrence of a character in string
s="hellloooloo"
b='l'
print(s.rindex(b))
You 'can' have a static class in C++, as mentioned before, a static class is one that does not have any objects of it instantiated it. In C++, this can be obtained by declaring the constructor/destructor as private. End result is the same.
textBlock.Foreground = new SolidColorBrush(Colors.White);
getUserRootFolder() {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
For XAMPP, do the following steps:
G:\xampp\apache\conf\extra\httpd-ssl.conf"
Search 'DocumentRoot' text.
Change DocumentRoot DocumentRoot "G:/xampp/htdocs" to DocumentRoot "G:/xampp/htdocs/project name".
In my case, I was mistaken the function parameters, which are:
context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);
If you expect them to be
context.drawImage(image, width, height);
you will place the image just outside the canvas with the same effects as described in the question.
All of these three solutions give the same results if the input is a string:
1.
def reverse(text):
result = ""
for i in range(len(text),0,-1):
result += text[i-1]
return (result)
2.
text[::-1]
3.
"".join(reversed(text))
sqlcmd works, System.Data.SqlClient not working - Server not found in Kerberos database. You should add RestrictedKrbHost SPN
5.1.2 SPNs with Serviceclass Equal to "RestrictedKrbHost"
Supporting the "RestrictedKrbHost" service class allows client applications to use Kerberos authentication when they do not have the identity of the service but have the server name. This does not provide client-to-service mutual authentication, but rather client-to-server computer authentication. Services of different privilege levels have the same session key and could decrypt each other's data if the underlying service does not ensure that data cannot be accessed by higher services.
Create a separate ul.nav
for just that list item and float that ul
right.
Add a connection string in the root web.config file of 'container' MVC project that references the class library as following:
<connectionStrings>
<add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />
</connectionStrings>
If you do not want to use "MyEntities" as connection name then change it as you wish but make the following change in your MyEntities DbContext class:
MyEntities: DbContext
{
public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
}
Reason for this error is, If we will not specify the name of connection string Or connect string in derived class of DbConext(In your case it is MyEntities) then DbContext will automatically search for a connection string in root web.config file whoes name is same as derived class name (In your case it is My Entities).
You can run Rake tasks from your shell by running:
rake task_name
To run from from Ruby (e.g., in the Rails console or another Rake task):
Rake::Task['task_name'].invoke
To run multiple tasks in the same namespace with a single task, create the following new task in your namespace:
task :runall => [:iqmedier, :euroads, :mikkelsen, :orville] do
# This will run after all those tasks have run
end
Here are the steps I went through in getting ffmpeg to work on Android:
make
away. You'll need to extract bionic(libc) and zlib(libz) from the Android build as well, as ffmpeg libraries depend on them.Create a dynamic library wrapping ffmpeg functionality using the Android NDK. There's a lot of documentation out there on how to work with the NDK. Basically you'll need to write some C/C++ code to export the functionality you need out of ffmpeg into a library java can interact with through JNI. The NDK allows you to easily link against the static libraries you've generated in step 1, just add a line similar to this to Android.mk: LOCAL_STATIC_LIBRARIES := libavcodec libavformat libavutil libc libz
Use the ffmpeg-wrapping dynamic library from your java sources. There's enough documentation on JNI out there, you should be fine.
Regarding using ffmpeg for playback, there are many examples (the ffmpeg binary itself is a good example), here's a basic tutorial. The best documentation can be found in the headers.
Good luck :)
Specific actions you can do from SQL client and you don't need to restart anything:
SET GLOBAL log = 'ON';
FLUSH LOGS;
I got this error while trying to use the &&
operator inside single brackets like [ ... && ... ]
. I had to switch to [[ ... && ... ]]
.
Visual Basic has built-in constants for newlines:
vbCr
= Chr$(13) = CR (carriage-return character) - used by Mac OS and Apple II family
vbLf
= Chr$(10) = LF (line-feed character) - used by Linux and Mac OS X
vbCrLf
= Chr$(13) & Chr$(10) = CRLF (carriage-return followed by line-feed) - used by Windows
vbNewLine
= the same as vbCrLf
Use the oncontextmenu
event.
Here's an example:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners (credit to rampion from a comment in 2011):
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
Alternatively you can use Jetty which is (now) part of the Eclipe Platform (the Help system is running Jetty). Besides Jetty is used by Android, Windows Mobile..
To get started check the Eclipse Wiki or if you prefer a Video And check out this related Post!
I had many issues involving C# and SqlServer. I ended up doing the following:
Also make sure that all your machines run on the same timezone.
Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...
Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).
EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.
I've added
public void ExportToFile(string path, DataTable tabela)
{
DataColumnCollection colunas = tabela.Columns;
foreach (DataRow linha in tabela.Rows)
{
this.AddRow();
foreach (DataColumn coluna in colunas)
{
this[coluna.ColumnName] = linha[coluna];
}
}
this.ExportToFile(path);
}
Previous code does not work with old .NET versions. For 3.5 version of framework use this other version:
public void ExportToFile(string path)
{
bool abort = false;
bool exists = false;
do
{
exists = File.Exists(path);
if (!exists)
{
if( !Convert.ToBoolean( File.CreateText(path) ) )
abort = true;
}
} while (!exists || abort);
if (!abort)
{
//File.OpenWrite(path);
using (StreamWriter w = File.AppendText(path))
{
w.WriteLine("hello");
}
}
//File.WriteAllText(path, Export());
}
The group_concat supports its own order by clause
http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/
So you should be able to write:
SELECT li.clientid, group_concat(li.views order by views) AS views,
group_concat(li.percentage order by percentage)
FROM table_views GROUP BY client_id
I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).
<input type="text" value="<script>alert('test');</script>" />
Produces:
You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value
attribute.
var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";
Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.
The problem is, that if you have that problem, the database-schema is denormalized.
You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.
So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.
So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.
And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...
Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO
CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
@in_RM_ApertureID uniqueidentifier
,@in_DatumVon AS datetime
,@in_DatumBis AS datetime
,@in_Status AS integer
)
RETURNS bit
AS
BEGIN
DECLARE @bNoCheckForThisCustomer AS bit
DECLARE @bIsInvalidValue AS bit
SET @bNoCheckForThisCustomer = 'false'
SET @bIsInvalidValue = 'false'
IF @in_Status = 99
RETURN 'false'
IF @in_DatumVon > @in_DatumBis
BEGIN
RETURN 'true'
END
IF @bNoCheckForThisCustomer = 'true'
RETURN @bIsInvalidValue
IF NOT EXISTS
(
SELECT
T_Raum.RM_UID
,T_Raum.RM_Status
,T_Raum.RM_DatumVon
,T_Raum.RM_DatumBis
,T_Raum.RM_ApertureID
FROM T_Raum
WHERE (1=1)
AND T_Raum.RM_ApertureID = @in_RM_ApertureID
AND @in_DatumVon >= T_Raum.RM_DatumVon
AND @in_DatumBis <= T_Raum.RM_DatumBis
AND T_Raum.RM_Status <> 99
)
SET @bIsInvalidValue = 'true' -- IF !
RETURN @bIsInvalidValue
END
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
CHECK
(
NOT
(
dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1
)
)
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO
In response to the above post I think it needs this line instead of your line:-
var strMethodUrl = '@Url.Action("SubMenu_Click", "Logging")?param1='+value1+' ¶m2='+value2
Or else you send the actual strings value1 and value2 to the controller.
However, for me, it only calls the controller once. It seems to hit 'receieveResponse' each time, but a break point on the controller method shows it is only hit 1st time until a page refresh.
Here is a working solution. For the cshtml page:-
<button type="button" onclick="ButtonClick();"> Call »</button>
<script>
function ButtonClick()
{
callControllerMethod2("1", "2");
}
function callControllerMethod2(value1, value2)
{
var response = null;
$.ajax({
async: true,
url: "Logging/SubMenu_Click?param1=" + value1 + " ¶m2=" + value2,
cache: false,
dataType: "json",
success: function (data) { receiveResponse(data); }
});
}
function receiveResponse(response)
{
if (response != null)
{
for (var i = 0; i < response.length; i++)
{
alert(response[i].Data);
}
}
}
</script>
And for the controller:-
public class A
{
public string Id { get; set; }
public string Data { get; set; }
}
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = new A[] {new A(){ Id = "1", Data = DateTime.Now.Millisecond.ToString() } };
return Json(arr , JsonRequestBehavior.AllowGet);
}
You can see the time changing each time it is called, so there is no caching of the values...
As an addition to @C??? answer, make sure the title of the tooltip has not already been set manually in the HTML element. In my case, the span class for the tooltip already had a fixed tittle text, because of this my JQuery function $('[data-toggle="tooltip"]').prop('title', 'your new title');
did not work.
When I removed the title attribute in the HTML span class, the jQuery was working.
So:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top" title="this is my pre-set title text"></span>
</span>
Should becode:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top"></span>
</span>
Interestingly I checked this on an app of mine and I got the same error.
I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES
and found nothing.
So I moved the
#define _USE_MATH_DEFINES
#include <cmath>
to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h"
) and suddenly it compile perfectly.
Try moving it higher up the page. Totally unsure as to why this would cause issues though.
Edit: Figured it out. The #include <math.h>
occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath
without the #define
specified. math.h
is specifically designed so that you can include it again with that define now changed to add M_PI
etc. This is NOT the case with cmath
. So you need to make sure you #define _USE_MATH_DEFINES
before you include anything else. Hope that clears it up for you :)
Failing that just include math.h
you are using non-standard C/C++ as already pointed out :)
Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)
When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda
It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)
var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);
There's nothing wrong with saving the whole history in the database, they are prepared for that kind of tasks.
Actually you can find here in Stack Overflow a link to an example schema for a chat: example
If you are still worried for the size, you could apply some optimizations to group messages, like adding a buffer to your application that you only push after some time (like 1 minute or so); that way you would avoid having only 1 line messages
Fell into the same trouble with inlining functions into so libraries. It seems that inlined functions are not compiled into the library. as a result the linker puts out a "undefined reference" error, if a executable wants to use the inlined function of the library. (happened to me compiling Qt source with gcc 4.5.
I found that adding "-i" to the commit command fixes this problem for me. The -i basically tells it to stage additional files before committing. That is:
git commit -i myfile.php
Did you put void while calling your function?
For example:
void something(int x){
logic..
}
int main() {
**void** something();
return 0;
}
If so, you should delete the last void.
No, you're not allocating memory for y->x
twice.
Instead, you're allocating memory for the structure (which includes a pointer) plus something for that pointer to point to.
Think of it this way:
1 2
+-----+ +------+
y------>| x------>| *x |
| n | +------+
+-----+
So you actually need the two allocations (1
and 2
) to store everything.
Additionally, your type should be struct Vector *y
since it's a pointer, and you should never cast the return value from malloc
in C since it can hide certain problems you don't want hidden - C is perfectly capable of implicitly converting the void*
return value to any other pointer.
And, of course, you probably want to encapsulate the creation of these vectors to make management of them easier, such as with:
struct Vector {
double *data; // no place for x and n in readable code :-)
size_t size;
};
struct Vector *newVector (size_t sz) {
// Try to allocate vector structure.
struct Vector *retVal = malloc (sizeof (struct Vector));
if (retVal == NULL)
return NULL;
// Try to allocate vector data, free structure if fail.
retVal->data = malloc (sz * sizeof (double));
if (retVal->data == NULL) {
free (retVal);
return NULL;
}
// Set size and return.
retVal->size = sz;
return retVal;
}
void delVector (struct Vector *vector) {
// Can safely assume vector is NULL or fully built.
if (vector != NULL) {
free (vector->data);
free (vector);
}
}
By encapsulating the creation like that, you ensure that vectors are either fully built or not built at all - there's no chance of them being half-built. It also allows you to totally change the underlying data structures in future without affecting clients (for example, if you wanted to make them sparse arrays to trade off space for speed).
Django provides it. You can use either:
{{ forloop.counter }}
index starts at 1.{{ forloop.counter0 }}
index starts at 0.In template, you can do:
{% for item in item_list %}
{{ forloop.counter }} # starting index 1
{{ forloop.counter0 }} # starting index 0
# do your stuff
{% endfor %}
More info at: for | Built-in template tags and filters | Django documentation
I used this and works for me.
<div class="col-sm-3">
<img src="xxx.png" style="width: auto; height: 195px;">
</div>
You could use .apply and pd.value_counts to get a count the occurrence of all the names in the name column.
dataframe['name'].apply(pd.value_counts)
How about:
df['new_col'] = range(1, len(df) + 1)
Alternatively if you want the index to be the ranks and store the original index as a column:
df = df.reset_index()
One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.
Using the standard HTML5 file input, you'll receive an extra path
property on selected files, containing the real file path.
Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md
You can configure the ObjectMapper
to convert camel case to names with an underscore:
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
Or annotate a specific model class with this annotation:
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
Before Jackson 2.7, the constant was named:
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
If you want to make sure that the order of execution is retained you can use flatMap as the following example
const first = Rx.Observable.of(1).delay(1000).do(i => console.log(i));
const second = Rx.Observable.of(11).delay(500).do(i => console.log(i));
const third = Rx.Observable.of(111).do(i => console.log(i));
first
.flatMap(() => second)
.flatMap(() => third)
.subscribe(()=> console.log('finished'));
The outcome would be:
"1"
"11"
"111"
"finished"
I was making mistakes like this.
@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i&subset=cyrillic,cyrillic-ext,latin-ext";
@import "https://use.fontawesome.com/releases/v5.3.1/css/all.css";
It works properly this way
@import url(https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i&subset=cyrillic,cyrillic-ext,latin-ext);
@import url(https://use.fontawesome.com/releases/v5.3.1/css/all.css);
This is a good question. There are many reason you would want to actually transpose the matrix in memory rather than just swap coordinates, e.g. in matrix multiplication and Gaussian smearing.
First let me list one of the functions I use for the transpose (EDIT: please see the end of my answer where I found a much faster solution)
void transpose(float *src, float *dst, const int N, const int M) {
#pragma omp parallel for
for(int n = 0; n<N*M; n++) {
int i = n/N;
int j = n%N;
dst[n] = src[M*j + i];
}
}
Now let's see why the transpose is useful. Consider matrix multiplication C = A*B. We could do it this way.
for(int i=0; i<N; i++) {
for(int j=0; j<K; j++) {
float tmp = 0;
for(int l=0; l<M; l++) {
tmp += A[M*i+l]*B[K*l+j];
}
C[K*i + j] = tmp;
}
}
That way, however, is going to have a lot of cache misses. A much faster solution is to take the transpose of B first
transpose(B);
for(int i=0; i<N; i++) {
for(int j=0; j<K; j++) {
float tmp = 0;
for(int l=0; l<M; l++) {
tmp += A[M*i+l]*B[K*j+l];
}
C[K*i + j] = tmp;
}
}
transpose(B);
Matrix multiplication is O(n^3) and the transpose is O(n^2), so taking the transpose should have a negligible effect on the computation time (for large n
). In matrix multiplication loop tiling is even more effective than taking the transpose but that's much more complicated.
I wish I knew a faster way to do the transpose (Edit: I found a faster solution, see the end of my answer). When Haswell/AVX2 comes out in a few weeks it will have a gather function. I don't know if that will be helpful in this case but I could image gathering a column and writing out a row. Maybe it will make the transpose unnecessary.
For Gaussian smearing what you do is smear horizontally and then smear vertically. But smearing vertically has the cache problem so what you do is
Smear image horizontally
transpose output
Smear output horizontally
transpose output
Here is a paper by Intel explaining that http://software.intel.com/en-us/articles/iir-gaussian-blur-filter-implementation-using-intel-advanced-vector-extensions
Lastly, what I actually do in matrix multiplication (and in Gaussian smearing) is not take exactly the transpose but take the transpose in widths of a certain vector size (e.g. 4 or 8 for SSE/AVX). Here is the function I use
void reorder_matrix(const float* A, float* B, const int N, const int M, const int vec_size) {
#pragma omp parallel for
for(int n=0; n<M*N; n++) {
int k = vec_size*(n/N/vec_size);
int i = (n/vec_size)%N;
int j = n%vec_size;
B[n] = A[M*i + k + j];
}
}
EDIT:
I tried several function to find the fastest transpose for large matrices. In the end the fastest result is to use loop blocking with block_size=16
(Edit: I found a faster solution using SSE and loop blocking - see below). This code works for any NxM matrix (i.e. the matrix does not have to be square).
inline void transpose_scalar_block(float *A, float *B, const int lda, const int ldb, const int block_size) {
#pragma omp parallel for
for(int i=0; i<block_size; i++) {
for(int j=0; j<block_size; j++) {
B[j*ldb + i] = A[i*lda +j];
}
}
}
inline void transpose_block(float *A, float *B, const int n, const int m, const int lda, const int ldb, const int block_size) {
#pragma omp parallel for
for(int i=0; i<n; i+=block_size) {
for(int j=0; j<m; j+=block_size) {
transpose_scalar_block(&A[i*lda +j], &B[j*ldb + i], lda, ldb, block_size);
}
}
}
The values lda
and ldb
are the width of the matrix. These need to be multiples of the block size. To find the values and allocate the memory for e.g. a 3000x1001 matrix I do something like this
#define ROUND_UP(x, s) (((x)+((s)-1)) & -(s))
const int n = 3000;
const int m = 1001;
int lda = ROUND_UP(m, 16);
int ldb = ROUND_UP(n, 16);
float *A = (float*)_mm_malloc(sizeof(float)*lda*ldb, 64);
float *B = (float*)_mm_malloc(sizeof(float)*lda*ldb, 64);
For 3000x1001 this returns ldb = 3008
and lda = 1008
Edit:
I found an even faster solution using SSE intrinsics:
inline void transpose4x4_SSE(float *A, float *B, const int lda, const int ldb) {
__m128 row1 = _mm_load_ps(&A[0*lda]);
__m128 row2 = _mm_load_ps(&A[1*lda]);
__m128 row3 = _mm_load_ps(&A[2*lda]);
__m128 row4 = _mm_load_ps(&A[3*lda]);
_MM_TRANSPOSE4_PS(row1, row2, row3, row4);
_mm_store_ps(&B[0*ldb], row1);
_mm_store_ps(&B[1*ldb], row2);
_mm_store_ps(&B[2*ldb], row3);
_mm_store_ps(&B[3*ldb], row4);
}
inline void transpose_block_SSE4x4(float *A, float *B, const int n, const int m, const int lda, const int ldb ,const int block_size) {
#pragma omp parallel for
for(int i=0; i<n; i+=block_size) {
for(int j=0; j<m; j+=block_size) {
int max_i2 = i+block_size < n ? i + block_size : n;
int max_j2 = j+block_size < m ? j + block_size : m;
for(int i2=i; i2<max_i2; i2+=4) {
for(int j2=j; j2<max_j2; j2+=4) {
transpose4x4_SSE(&A[i2*lda +j2], &B[j2*ldb + i2], lda, ldb);
}
}
}
}
}
<div id="canvasdiv" style="margin: 5px; height: 100%; width: 100%;">
<canvas id="mycanvas" style="border: 1px solid red;"></canvas>
</div>
<script>
$(function(){
InitContext();
});
function InitContext()
{
var $canvasDiv = $('#canvasdiv');
var canvas = document.getElementById("mycanvas");
canvas.height = $canvasDiv.innerHeight();
canvas.width = $canvasDiv.innerWidth();
}
</script>
In the spirit of a DVCS (as in "Distributed"), you don't cancel something you have published:
Pull requests are essentially patches you have send (normally by email, here by GitHub webapp), and you wouldn't cancel an email either ;)
But since the GitHub Pull Request system also includes a discussion section, that would be there that you could voice your concern to the recipient of those changes, asking him/her to disregards 29 of your 30 commits.
Finally, remember:
That being said, since January 2011 ("Refreshed Pull Request Discussions"), and mentioned in the answer above, you can close a pull request in the comments.
Look for that "Comment and Close" button at the bottom of the discussion page:
Remove the function and check the output of:
var_dump(function_exists('parseDate'));
In which case, change the name of the function.
If you get false, you're including the file with that function twice, replace :
include
by
include_once
And replace :
require
by
require_once
EDIT : I'm just a little too late, post before beat me to it !
Check any extra space before php tag.
NOTE: this answer is obsolete. See the community wiki answer below for an up-to-date solution.
I found this Gist today and it works perfectly: https://gist.github.com/2571173
(Many thanks to https://gist.github.com/smeranda)
/*
Make the Facebook Like box responsive (fluid width)
https://developers.facebook.com/docs/reference/plugins/like-box/
*/
/*
This element holds injected scripts inside iframes that in
some cases may stretch layouts. So, we're just hiding it.
*/
#fb-root {
display: none;
}
/* To fill the container and nothing else */
.fb_iframe_widget, .fb_iframe_widget span, .fb_iframe_widget span iframe[style] {
width: 100% !important;
}
If you are using Windows and Android Studio 4 and above, the location to the directory is C:\Users(your name)\AppData\Roaming\Google\
Simple delete the Google folder to reset all settings. Open Android Studio and do not import settings when asked
I wrapped my line that was crashing in a try-catch block, printed out the exception, and breaked immediately after it was printed. The exception information shown had a stack trace which pointed me to the file and line of code causing the fault to occur.
System.TypeInitializationException: The type initializer for 'Blah.blah.blah' threw an exception.
---> System.NullReferenceException: Object reference not set to an instance of an object.
at Some.Faulty.Software..cctor() in C:\Projects\My.Faulty.File.cs:line 56
--- End of inner exception stack trace ---
at Blah.blah.blah(Blah.blah.blah)
at TestApplication.Program.Main(String[] args)
in C:\Projects\Blah.blah.blah\Program.cs:line 29 Exception caught.
git reset --hard 1258f0d0aae
But be careful, if the descendant commits between 1258f0d0aae
and HEAD
are not referenced in other branches it'll be tedious (but not impossible) to recover them, so you'd better to create a "backup" branch at current HEAD
, checkout master
, and reset to the commit you want.
Also, be sure that you don't have uncommitted changes before a reset --hard
, they will be truly lost (no way to recover).
SELECT * FROM INFORMATION_SCHEMA.TABLES
OR
SELECT * FROM Sys.Tables
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
Maybe you need "sys." before:
select * from sys.registry$history;
One case you check that nginx hold on 80 number port in system by default , check if you have any server like as apache or anything exist on system that block 80 number port thats the problem occurred.
1 .You change port number on nginx by this way,
sudo vim /etc/nginx/sites-available/default
Change 80 to 81 or anything,
sudo nginx -t
sudo service nginx start
sudo service nginx status
Hope that will work
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
SQL query to change the id column into first:
ALTER TABLE `student` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT FIRST;
or by using:
ALTER TABLE `student` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT AFTER 'column_name'
In order to avoid having to fully specify the git push command you could alternatively modify your git config file:
[remote "gerrit"]
url = https://your.gerrit.repo:44444/repo
fetch = +refs/heads/master:refs/remotes/origin/master
push = refs/heads/master:refs/for/master
Now you can simply:
git fetch gerrit
git push gerrit
This is according to Gerrit
IF EXISTS (SELECT NAME FROM SYS.OBJECTS WHERE object_id = OBJECT_ID(N'Scores') AND TYPE in (N'U'))
DROP TABLE Scores
GO
I sometimes find a variation of this useful.
Example in JavaScript:
class Scaler {
constructor(inMin, inMax, outMin, outMax) {
this.inMin = inMin;
this.inMax = inMax;
this.outMin = outMin;
this.outMax = outMax;
}
scale(value) {
const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;
if (result < this.outMin) {
return this.outMin;
} else if (result > this.outMax) {
return this.outMax;
}
return result;
}
}
This example along with a function based version comes from the page https://writingjavascript.com/scaling-values-between-two-ranges
Write these codes end of the C:\xampp\apache\conf\extra\httpd-vhosts.conf file,
DocumentRoot "D:/xampp/htdocs/foldername"
ServerName www.siteurl.com
ServerAlias www.siteurl.com
ErrorLog "logs/dummy-host.example.com-error.log"
CustomLog "logs/dummy-host.example.com-access.log" common
between the virtual host tag.
and edit the file System32/Drivers/etc/hosts use notepad as administrator
add bottom of the file
127.0.0.1 www.siteurl.com
Whilst, as has been pointed out, it is possible to see the current default socket buffer sizes in /proc
, it is also possible to check them using sysctl
(Note: Whilst the name includes ipv4 these sizes also apply to ipv6 sockets - the ipv6 tcp_v6_init_sock() code just calls the ipv4 tcp_init_sock() function):
sysctl net.ipv4.tcp_rmem
sysctl net.ipv4.tcp_wmem
However, the default socket buffers are just set when the sock is initialised but the kernel then dynamically sizes them (unless set using setsockopt() with SO_SNDBUF). The actual size of the buffers for currently open sockets may be inspected using the ss
command (part of the iproute
package), which can also provide a bunch more info on sockets like congestion control parameter etc. E.g. To list the currently open TCP (t
option) sockets and associated memory (m
) information:
ss -tm
Here's some example output:
State Recv-Q Send-Q Local Address:Port Peer Address:Port
ESTAB 0 0 192.168.56.102:ssh 192.168.56.1:56328
skmem:(r0,rb369280,t0,tb87040,f0,w0,o0,bl0,d0)
Here's a brief explanation of skmem (socket memory) - for more info you'll need to look at the kernel sources (e.g. sock.h):
r:sk_rmem_alloc rb:sk_rcvbuf # current receive buffer size t:sk_wmem_alloc tb:sk_sndbuf # current transmit buffer size f:sk_forward_alloc w:sk_wmem_queued # persistent transmit queue size o:sk_omem_alloc bl:sk_backlog d:sk_drops
I do this a lot. A lot. :-)
I have got used to using "DoEvents" more often, but still tend to set things running without really double checking a sure stop method.
Then, today, having done it again, I thought, "Well just wait for the end in 3 hours", and started paddling around in the ribbon. Earlier, I had noticed in the "View" section of the Ribbon a "Macros" pull down, and thought I have a look to see if I could see my interminable Macro running....
I now realise you can also get this up using Alt-F8.
Then I thought, well what if I "Step into" a different Macro, would that rescue me? It did :-) It also works if you step into your running Macro (but you still lose where you're upto), unless you are a very lazy programmer like me and declare lots of "Global" variables, in which case the Global data is retained :-)
K
This might help
import binascii
x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')
print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374
x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'
x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test
This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii')
.
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>();
foreach (JToken attribute in attributes)
{
JProperty jProperty = attribute.ToObject<JProperty>();
string propertyName = jProperty.Name;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
titolorecuperato = (TextView) findViewById(R.id.textView);
String stitolo = titolorecuperato.getText().toString();
Button btnHome = (Button) findViewById(R.id.button);
btnHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
same thing as Nic007 said before.
You do need to write code inside "onCreate" method. Sorry me too for the indent... (first comment here)
On your backEnd, you should add:
@RequestMapping(value="/blabla", produces="text/plain" , method = RequestMethod.GET)
On the frontEnd (Service):
methodBlabla()
{
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.get(this.url,{ headers, responseType: 'text'});
}
Change:
android:theme="@style/AppTheme"
to something like:
android:theme="@style/Theme.AppCompat.Light"
For those of you how have implemented the checked answer yet still getting the error
(Object reference not set to an instance of an object)
As was mentioned in the comments, maybe the DataGridView's data source is not of the type DataTable, but if it is, try to assign the data table to the DataGridView's data source again. In my case, I assigned the data table to the DataGridView in FormLoad() and when I write this code
(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
it was giving me the error I mentioned above. So, I reassigned the data table to the dgv again. So the code was something like
dataGridViewFields.DataSource = Dt;
(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
And it worked.
java.io.File
class contains four static separator variables. For better understanding, Let's understand with the help of some code
Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables. FileSeparator.java
import java.io.File;
public class FileSeparator {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :
Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
In Oracle:
SELECT DISTINCT city
FROM station
WHERE SUBSTR(lower(CITY),1,1) IN ('a','e','i','o','u') AND SUBSTR(lower(CITY),-1) IN ('a','e','i','o','u');
Laravel 5.6 method: https://laravel.com/docs/5.6/views#passing-data-to-views
Example, with sharing a model collection to all views (AppServiceProvider.php):
use Illuminate\Support\Facades\View;
use App\Product;
public function boot()
{
$products = Product::all();
View::share('products', $products);
}
Set npm registry globally
use the below command to modify the .npmrc config file for the logged in user
npm config set registry <registry url>
Example: npm config set registry https://registry.npmjs.org/
Set npm registry Scope
Scopes allow grouping of related packages together. Scoped packages will be installed in a sub-folder under node_modules folder.
Example: node_modules/@my-org/packagaename
To set the scope registry use: npm config set @my-org:registry http://example.reg-org.com
To install packages using scope use: npm install @my-org/mypackage
whenever you install any packages from scope @my-org npm will search in the registry setting linked to scope @my-org for the registry url.
Set npm registry locally for a project
To modify the npm registry only for the current project. create a file inside the root folder of the project as .npmrc
Add the below contents in the file
registry = 'https://registry.npmjs.org/'
SETUSER could work, having a user, even an orphaned user in the DB with the default schema needed. But SETUSER is on the legacy not supported for ever list. So a similar alternative would be to setup an application role with the needed default schema, as long as no cross DB access is needed, this should work like a treat.
In matplotlib you have two main options:
Create your plots and draw them at the end:
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.plot(z, t)
plt.show()
Create your plots and draw them as soon as they are created:
import matplotlib.pyplot as plt
from matplotlib import interactive
interactive(True)
plt.plot(x, y)
raw_input('press return to continue')
plt.plot(z, t)
raw_input('press return to end')
Also make sure the page is valid. You can check this in the browsers developer tools (F12)
In the Console tab select the correct Target/Frame and check for the [Page_IsValid] property
If the page is not valid the form will not submit and therefore not fire the event.
Truncate drops the decimal point.
Take a look at the very recently released SSHD, which is based on the Apache MINA project.
So I see many possibilities to achieve this.
string text = "Foobar-test";
Regex Match everything till the first "-"
Match result = Regex.Match(text, @"^.*?(?=-)");
^
match from the start of the string.*?
match any character (.
), zero or more times (*
) but as less as possible (?
)(?=-)
till the next character is a "-" (this is a positive look ahead)Regex Match anything that is not a "-" from the start of the string
Match result2 = Regex.Match(text, @"^[^-]*");
[^-]*
matches any character that is not a "-" zero or more timesRegex Match anything that is not a "-" from the start of the string till a "-"
Match result21 = Regex.Match(text, @"^([^-]*)-");
Will only match if there is a dash in the string, but the result is then found in capture group 1.
Split on "-"
string[] result3 = text.Split('-');
Result is an Array the part before the first "-" is the first item in the Array
Substring till the first "-"
string result4 = text.Substring(0, text.IndexOf("-"));
Get the substring from text from the start till the first occurrence of "-" (text.IndexOf("-")
)
You get then all the results (all the same) with this
Console.WriteLine(result);
Console.WriteLine(result2);
Console.WriteLine(result21.Groups[1]);
Console.WriteLine(result3[0]);
Console.WriteLine(result4);
I would prefer the first method.
You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-")
will be -1
. Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string.
Drop the 's' off of the package name.
You want sudo apt-get install build-essential
You may also need to run sudo apt-get update
to make sure that your package index is up to date.
For anyone wondering why this package may be needed as part of another install, it contains the essential tools for building most other packages from source (C/C++ compiler, libc, and make).
Try gmdate
like this:
<?php
$timestamp=1333699439;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
First we should know that regular expression can separately be used. Here is an example:
import scala.util.matching.Regex
val pattern = "Scala".r // <=> val pattern = new Regex("Scala")
val str = "Scala is very cool"
val result = pattern findFirstIn str
result match {
case Some(v) => println(v)
case _ =>
} // output: Scala
Second we should notice that combining regular expression with pattern matching would be very powerful. Here is a simple example.
val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
"2014-11-20" match {
case date(year, month, day) => "hello"
} // output: hello
In fact, regular expression itself is already very powerful; the only thing we need to do is to make it more powerful by Scala. Here are more examples in Scala Document: http://www.scala-lang.org/files/archive/api/current/index.html#scala.util.matching.Regex
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
In minimalistic programs where a size_t
definition was not loaded "by chance" in some include but I still need it in some context (for example to access std::vector<double>
), then I use that context to extract the correct type. For example typedef std::vector<double>::size_type size_t
.
(Surround with namespace {...}
if necessary to make the scope limited.)
Here is another solution which uses any/2
map(select(any(.Names[]; contains("data"))|not)|.Id)[]
with the sample data and the -r
option it produces
cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19
If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:
// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')
// now 'e_str' is a unique query for this element that can be stringify
var e_str = e.tagName
+ ( e.id != "" ? "#" + e.id : "")
+ ( e.className != "" ? "." + e.className.replace(' ','.') : "");
//now you can stringify your element to JSON string
var e_json = JSON.stringify({
'element': e_str
})
than
//parse it back to an object
var obj = JSON.parse( e_json )
//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )
//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();
In my testing with Tomcat and Java 8, the JVM was opening an ephemeral port in addition to the one specified for JMX. The following code fixed me up; give it a try if you are having issues where your JMX client (e.g. VisualVM is not connecting.
-Dcom.sun.management.jmxremote.port=8989
-Dcom.sun.management.jmxremote.rmi.port=8989
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
Fixed my issue by changing these
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+'
to
compile 'com.android.support:cardview-v7:23.0.+'
compile 'com.android.support:recyclerview-v7:23.0.+'
that means your target SDK version should be same as version of cardView and recyclerView and other google libraries.
targetSdkVersion 23
Until the day #pragma once
becomes standard (that's not currently a priority for the future standards), I suggest you use it AND use guards, this way:
#ifndef BLAH_H
#define BLAH_H
#pragma once
// ...
#endif
The reasons are :
#pragma once
is not standard, so it is possible that some compiler don't provide the functionality. That said, all major compiler supports it. If a compiler don't know it, at least it will be ignored.#pragma once
, you shouldn't assume that the behavior will be the same on all compiler. The guards will ensure at least that the basic assumption is the same for all compilers that at least implement the needed preprocessor instructions for guards.#pragma once
will speed up compilation (of one cpp) because the compiler will not reopen the file containing this instruction. So having it in a file might help, or not, depending on the compiler. I heard g++ can do the same optimization when guards are detected but it have to be confirmed.Using the two together you get the best of each compiler for this.
Now, if you don't have some automatic script to generate the guards, it might be more convenient to just use #pragma once
. Just know what that means for portable code. (I'm using VAssistX to generate the guards and pragma once quickly)
You should almost always think your code in a portable way (because you don't know what the future is made of) but if you really think that it's not meant to be compiled with another compiler (code for very specific embedded hardware for example) then you should just check your compiler documentation about #pragma once
to know what you're really doing.
This can be accomplished using the brand new CSS display: grid
(browser support)
HTML:
<div class='container'>
<label for="dummy1">title for dummy1:</label>
<input id="dummy1" name="dummy1" value="dummy1">
<label for="dummy2">longer title for dummy2:</label>
<input id="dummy2" name="dummy2" value="dummy2">
<label for="dummy3">even longer title for dummy3:</label>
<input id="dummy3" name="dummy3" value="dummy3">
</div>
CSS:
.container {
display: grid;
grid-template-columns: 1fr 3fr;
}
When using css grid, by default elements are laid out column by column then row by row. The grid-template-columns
rule creates two grid columns, one which takes up 1/4 of the total horizontal space and the other which takes up 3/4 of the horizontal space. This creates the desired effect.
for mysql>=5.5 only for slow queries (1 second and more) my.cfg
[mysqld]
slow-query-log = 1
slow-query-log-file = /var/log/mysql/mysql-slow.log
long_query_time = 1
log-queries-not-using-indexes
Order Collection Limit :
$orderCollection = Mage::getResourceModel('sales/order_collection');
$orderCollection->getSelect()->limit(10);
foreach ($orderCollection->getItems() as $order) :
$orderModel = Mage::getModel('sales/order');
$order = $orderModel->load($order['entity_id']);
echo $order->getId().'<br>';
endforeach;
After testing it with RSpec like this:
describe Hash do
describe :map_values do
it 'should map the values' do
expect({:a => 2, :b => 3}.map_values { |x| x ** 2 }).to eq({:a => 4, :b => 9})
end
end
end
You could implement Hash#map_values as follows:
class Hash
def map_values
Hash[map { |k, v| [k, yield(v)] }]
end
end
The function then can be used like this:
{:a=>'a' , :b=>'b'}.map_values { |v| "%#{v}%" }
# {:a=>"%a%", :b=>"%b%"}
I think double quotes works too:
SELECT "Business Name","Other Name" FROM your_Table
But I only tested on SQL Server NOT mySQL in case someone work with MS SQL Server.
ServicePointManager.ServerCertificateValidationCallback +=
(mender, certificate, chain, sslPolicyErrors) => true;
will bypass invaild ssl . Write it to your web service constructor.
Well i am trying to open a .vbs within a batch file without having to click open but the answer to this question is ...
SET APPDATA=%CD%
start (your file here without the brackets with a .vbs if it is a vbd file)
https://golang.org/ref/mem#tmp_4
Program initialization runs in a single goroutine, but that goroutine may create other goroutines, which run concurrently.
If a package p imports package q, the completion of q's init functions happens before the start of any of p's.
The start of the function main.main happens after all init functions have finished.
I'm pretty sure you can do explicit casting here.
foo f = (foo)value;
So long as you say the enum inherits(?) from int, which you have.
enum foo : int
EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.
You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.
enum (C# Reference)
Enumeration Types (C# Programming Guide)
NSMutableDictionary *dictParam = [NSMutableDictionary dictionary];
[dictParam setValue:@"VALUE_NAME" forKey:@"KEY_NAME"]; //set parameters like id, name, date, product_name etc
if ([[AppDelegate instance] checkInternetConnection]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParam options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"Api Url"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0f];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];
[request setValue:ACCESS_TOKEN forHTTPHeaderField:@"TOKEN"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json", nil];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
arrayList = [responseObject valueForKey:@"data"];
[_tblView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//show failure alert
}];
[op start];
}
} else {
[UIAlertView infoAlertWithMessage:NO_INTERNET_AVAIL andTitle:APP_NAME];
}
The browser's native JSON API may not give you back your idOld function after you call JSON.stringify, however, if can stringify your JSON yourself (maybe use Crockford's json2.js instead of browser's API), then if you have a string of JSON e.g.
var person_json = "{ \"age:\" : 20, \"isOld:\": false, isOld: function() { return this.age > 60; } }";
then you can call
eval("(" + person + ")")
, and you will get back your function in the json object.
It works, when you use both lines:
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"
document.querySelector('#edit-submitted-first-name').required = false;
$('#edit-submitted-first-name').removeAttr('required');
Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:
import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;
verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
The key to this is examining any information you recieve and then display and/or use in code on the server. Get/Post form variables if they contain javascript that you store and later redisplay is a security risk. As are any thing that gets concatenated unexamined into a sql statement you run.
One potential gotcha to watch for are attacks that mess with the character encoding. For instance if I submit a form with utf-8 character set but you store and later display in iso-8859-1 latin with no translation then I might be able to sneak something past your validator. The easiest way to handle this is to always display and store in the same character set. utf-8 is usually a good choice. Never depend on the browser to do the right thing for you in this case. Set explicit character sets and examine the character sets you recieve and do a translation to the expected storage set before you validate it.
It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
This is not, as you've titled it, a "JavaScript" question; it is a question regarding the design of jQuery.
jQuery and the previously linked citation from John Resig (in karim79's message) seem to be the source misunderstanding of how event handlers in general work.
Fact: An event handler that returns false prevents the default action for that event. It does not stop the event propagation. Event handlers have always worked this way, since the old days of Netscape Navigator.
The documentation from MDN explains how return false
in an event handler works
What happens in jQuery is not the same as what happens with event handlers. DOM event listeners and MSIE "attached" events are a different matter altogether.
For further reading, see attachEvent on MSDN and the W3C DOM 2 Events documentation.
For IntelliJ in Mac
View -> Quick Switch theme (^`)-> color schema
my friend by this u are not getting height of image stored in db.but you are getting view height.for getting height of image u have to create bitmap from db,s image.and than u can fetch height and width of imageview
I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:
d = {'x': 1, 'y': 2, 'z': 3}
for i, (key, value) in enumerate(d.items()):
print(i, key, value)
Note that the parentheses around the key, value are important, without them, you'd get an ValueError
"not enough values to unpack".
Don't do it, if you can avoid it. As Devon Sans points out in the comments: This feature will most likely be deprecated.
#Update - Newer Way
From Angular 4.3.0, all piercing css combinators were deprecated. Angular team introduced a new combinator ::ng-deep
(still it is experimental and not the full and final way) as shown below,
DEMO : https://plnkr.co/edit/RBJIszu14o4svHLQt563?p=preview
styles: [
`
:host { color: red; }
:host ::ng-deep parent {
color:blue;
}
:host ::ng-deep child{
color:orange;
}
:host ::ng-deep child.class1 {
color:yellow;
}
:host ::ng-deep child.class2{
color:pink;
}
`
],
template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`
You can use encapsulation mode
and/or piercing CSS combinators >>>, /deep/ and ::shadow
working example : http://plnkr.co/edit/1RBDGQ?p=preview
styles: [
`
:host { color: red; }
:host >>> parent {
color:blue;
}
:host >>> child{
color:orange;
}
:host >>> child.class1 {
color:yellow;
}
:host >>> child.class2{
color:pink;
}
`
],
template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`
Heap overflow should be blame (but not always) for corrupted double-linked list
, malloc(): memory corruption
, double free or corruption (!prev)
-like glibc warnings.
It should be reproduced by the following code:
#include <vector>
using std::vector;
int main(int argc, const char *argv[])
{
int *p = new int[3];
vector<int> vec;
vec.resize(100);
p[6] = 1024;
delete[] p;
return 0;
}
if compiled using g++ (4.5.4):
$ ./heapoverflow
*** glibc detected *** ./heapoverflow: double free or corruption (!prev): 0x0000000001263030 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7af26)[0x7f853f5d3f26]
./heapoverflow[0x40138e]
./heapoverflow[0x400d9c]
./heapoverflow[0x400bd9]
./heapoverflow[0x400aa6]
./heapoverflow[0x400a26]
/lib64/libc.so.6(__libc_start_main+0xfd)[0x7f853f57b4bd]
./heapoverflow[0x4008f9]
======= Memory map: ========
00400000-00403000 r-xp 00000000 08:02 2150398851 /data1/home/mckelvin/heapoverflow
00602000-00603000 r--p 00002000 08:02 2150398851 /data1/home/mckelvin/heapoverflow
00603000-00604000 rw-p 00003000 08:02 2150398851 /data1/home/mckelvin/heapoverflow
01263000-01284000 rw-p 00000000 00:00 0 [heap]
7f853f559000-7f853f6fa000 r-xp 00000000 09:01 201329536 /lib64/libc-2.15.so
7f853f6fa000-7f853f8fa000 ---p 001a1000 09:01 201329536 /lib64/libc-2.15.so
7f853f8fa000-7f853f8fe000 r--p 001a1000 09:01 201329536 /lib64/libc-2.15.so
7f853f8fe000-7f853f900000 rw-p 001a5000 09:01 201329536 /lib64/libc-2.15.so
7f853f900000-7f853f904000 rw-p 00000000 00:00 0
7f853f904000-7f853f919000 r-xp 00000000 09:01 74726670 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853f919000-7f853fb19000 ---p 00015000 09:01 74726670 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb19000-7f853fb1a000 r--p 00015000 09:01 74726670 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb1a000-7f853fb1b000 rw-p 00016000 09:01 74726670 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libgcc_s.so.1
7f853fb1b000-7f853fc11000 r-xp 00000000 09:01 201329538 /lib64/libm-2.15.so
7f853fc11000-7f853fe10000 ---p 000f6000 09:01 201329538 /lib64/libm-2.15.so
7f853fe10000-7f853fe11000 r--p 000f5000 09:01 201329538 /lib64/libm-2.15.so
7f853fe11000-7f853fe12000 rw-p 000f6000 09:01 201329538 /lib64/libm-2.15.so
7f853fe12000-7f853fefc000 r-xp 00000000 09:01 74726678 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f853fefc000-7f85400fb000 ---p 000ea000 09:01 74726678 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f85400fb000-7f8540103000 r--p 000e9000 09:01 74726678 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f8540103000-7f8540105000 rw-p 000f1000 09:01 74726678 /usr/lib64/gcc/x86_64-pc-linux-gnu/4.8.1/libstdc++.so.6.0.18
7f8540105000-7f854011a000 rw-p 00000000 00:00 0
7f854011a000-7f854013c000 r-xp 00000000 09:01 201328977 /lib64/ld-2.15.so
7f854031c000-7f8540321000 rw-p 00000000 00:00 0
7f8540339000-7f854033b000 rw-p 00000000 00:00 0
7f854033b000-7f854033c000 r--p 00021000 09:01 201328977 /lib64/ld-2.15.so
7f854033c000-7f854033d000 rw-p 00022000 09:01 201328977 /lib64/ld-2.15.so
7f854033d000-7f854033e000 rw-p 00000000 00:00 0
7fff92922000-7fff92943000 rw-p 00000000 00:00 0 [stack]
7fff929ff000-7fff92a00000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
[1] 18379 abort ./heapoverflow
and if compiled using clang++(6.0 (clang-600.0.56)):
$ ./heapoverflow
[1] 96277 segmentation fault ./heapoverflow
If you thought you might have written a bug like that, here is some hints to trace it out.
First, compile the code with debug flag(-g
):
g++ -g foo.cpp
And then, run it using valgrind:
$ valgrind ./a.out
==12693== Memcheck, a memory error detector
==12693== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12693== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==12693== Command: ./a.out
==12693==
==12693== Invalid write of size 4
==12693== at 0x400A25: main (foo.cpp:11)
==12693== Address 0x5a1c058 is 12 bytes after a block of size 12 alloc'd
==12693== at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12693== by 0x4009F6: main (foo.cpp:8)
==12693==
==12693==
==12693== HEAP SUMMARY:
==12693== in use at exit: 0 bytes in 0 blocks
==12693== total heap usage: 2 allocs, 2 frees, 412 bytes allocated
==12693==
==12693== All heap blocks were freed -- no leaks are possible
==12693==
==12693== For counts of detected and suppressed errors, rerun with: -v
==12693== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
The bug is located in ==12693== at 0x400A25: main (foo.cpp:11)
So it was a simple fix. Just had to move the ng-click
to a scope click handler:
<input id="upload"
type="file"
ng-file-select="onFileSelect($files)"
style="display: none;">
<button type="button"
ng-click="clickUpload()">Upload</button>
$scope.clickUpload = function(){
angular.element('#upload').trigger('click');
};
You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).
To add the PPA run:
sudo add-apt-repository ppa:eugenesan/ppa
sudo apt-get update
To install smartgit
(after adding the PPA) run:
sudo apt-get install smartgit
To install smartgithg
(after adding the PPA) run:
sudo apt-get install smartgithg
This should add a menu option for you
For more information, see Eugene San PPA.
This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release
To find out the limits on your system:
#include <iostream>
#include <limits>
int main(int, char **) {
std::cout
<< static_cast< int >(std::numeric_limits< char >::max()) << "\n"
<< static_cast< int >(std::numeric_limits< unsigned char >::max()) << "\n"
<< std::numeric_limits< short >::max() << "\n"
<< std::numeric_limits< unsigned short >::max() << "\n"
<< std::numeric_limits< int >::max() << "\n"
<< std::numeric_limits< unsigned int >::max() << "\n"
<< std::numeric_limits< long >::max() << "\n"
<< std::numeric_limits< unsigned long >::max() << "\n"
<< std::numeric_limits< long long >::max() << "\n"
<< std::numeric_limits< unsigned long long >::max() << "\n";
}
Note that long long
is only legal in C99 and in C++11.
Just in case this helps anybody else out there, I stumbled on an obscure case for this error triggering last night. Specifically, I was using the require_once method and specifying only a filename and no path, since the file being required was present in the same directory.
I started to get the 'Failed opening required file' error at one point. After tearing my hair out for a while, I finally noticed a PHP Warning message immediately above the fatal error output, indicating 'failed to open stream: Permission denied', but more importantly, informing me of the path to the file it was trying to open. I then twigged to the fact I had created a copy of the file (with ownership not accessible to Apache) elsewhere that happened to also be in the PHP 'include' search path, and ahead of the folder where I wanted it to be picked up. D'oh!
This doesn't quite yet look like what I want, but I accomplished something like
this by stacking nav pills in the leftmost two spans. This is what my app's
app/views/layouts/application.html.erb
file looks like:
<!DOCTYPE html>
...
<body>
<!-- top navigation bar -->
<div class="navbar navbar-fixed-top">
...
</div>
<div class="container-fluid">
<!-- the navigation buttons bar on the left -->
<div class="sidebar-nav span2"> <!-- we reserve 2 spans out of 12 for this -->
<ul class="nav nav-pills nav-stacked">
<li class="<%= current_page?(root_path) ? 'active' : 'inactive' %>">
<%= link_to "Home", root_path %>
</li>
<li class="<%= current_page?(section_a_path) ? 'active' : 'inactive' %>">
<%= link_to "Section A", section_a_path %>
</li>
<li class="<%= current_page?(section_b_path) ? 'active' : 'inactive' %>">
<%= link_to "Section B", section_b_path %>
</li>
</ul>
</div>
<div class="container-fluid span10"> <!-- use the remaining 10 spans -->
<%= flash_messages %>
<%= yield :layout %> <!-- the content page sees a full 12 spans -->
</div>
</div> <!-- class="container-fluid" -->
...
</body>
</html>
Now the stacked pills appear on the top left, below the navbar. When the user clicks on
one of them, the corresponding page loads. From the point of view of
application.html.erb
, that page has the 10 rightmost spans available for it,
but from the page's view, it has the full 12 spans available.
The button corresponding to the page currently being displayed is rendered as
active, and the others as inactive. Specify the colours for active and inactive
buttons in file app/assets/stylesheets/custom.css.scss
(in this case, the
colour for a disabled state is also defined):
@import "bootstrap";
...
$spray: #81c9e2;
$grey_light: #dddddd;
...
.nav-pills {
.inactive > a, .inactive > a:hover {
background-color: $spray;
}
.disabled > a, .disabled > a:hover {
background-color: $grey_light;
}
}
The active pill's colour is not defined, so it appears as the default blue.
File custom.css.scss
is included because of the line *= require_tree .
in
file app/assets/stylesheets/application.css
.
To update other branches like (backup) with your master branch copy. You can do follow either way (rebase or merge)...
Merge branches (there will be an extra commit automatically to the backup branch).
Note : Rebase is nothing but establishing a new base (a new copy)
git checkout backup git merge master git push
(Repeat for other branches if any like backup2 & etc..,)
git checkout backup git rebase master git push
(Repeat for other branches if any like backup2 & etc..,)
If you're using Spring Boot, the simplest way to disable the Spring Security default headers is to use security.headers.*
properties. In particular, if you want to disable the X-Frame-Options
default header, just add the following to your application.properties
:
security.headers.frame=false
There is also security.headers.cache
, security.headers.content-type
, security.headers.hsts
and security.headers.xss
properties that you can use. For more information, take a look at SecurityProperties
.
This is what i did, it works fine.
User.find({name:'Thava'}, null, {sort: { name : 1 }})
An important point is to consider if you perform tasks based on difference between 2 timestamps because you will get odd behavior if you generate it with gettimeofday()
, and even clock_gettime(CLOCK_REALTIME,..)
at the moment where you will set the time of your system.
To prevent such problem, use clock_gettime(CLOCK_MONOTONIC_RAW, &tms)
instead.
Your web server isn't running! You need to find the XAMPP control panel and start the web server up.
Of course, you might find other problems after that, but this is the first step.
Does:
Set Sheets("Output").Range("$A$1:$A$500") = Sheets(sheet_).Range("$A$1:$A$500")
...work? (I don't have Excel in front of me, so can't test.)
I see this questions is realla old, but for that problem I wrote a recursive function to unset all values in an array. Recursive because its possible that values from the given array are also an array. So that works for me:
function empty_array(& $complete_array) {
foreach($complete_array as $ckey => $cvalue)
{
if (!is_array($cvalue)) {
$complete_array[$ckey] = "";
} else {
empty_array( $complete_array[$ckey]);
}
}
return $complete_array;
}
So with that i get the array with all keys and sub-arrays, but empty values.
To solve the error "...cannot be resolved to a type.." do the followings:
It works for me.
A small patch to @Adam Sills's answer which solves FormatException
on cases where the input string like "c:\u00ab\otherdirectory\" plus RegexOptions.Compiled
makes the Regex
compilation much faster:
private static Regex DECODING_REGEX = new Regex(@"\\u(?<Value>[a-fA-F0-9]{4})", RegexOptions.Compiled);
private const string PLACEHOLDER = @"#!#";
public static string DecodeEncodedNonAsciiCharacters(this string value)
{
return DECODING_REGEX.Replace(
value.Replace(@"\\", PLACEHOLDER),
m => {
return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString(); })
.Replace(PLACEHOLDER, @"\\");
}
Most of the times these terms Web Server and Application server are used interchangeably.
Following are some of the key differences in features of Web Server and Application Server:
Example of such configuration is Apache Tomcat HTTP Server and Oracle (formerly BEA) WebLogic Server. Apache Tomcat HTTP Server is Web Server and Oracle WebLogic is Application Server.
In some cases the servers are tightly integrated such as IIS and .NET Runtime. IIS is web server. When equipped with .NET runtime environment, IIS is capable of providing application services.
The man pages is the best source of information you can find... and is at your fingertips: man mkdir
yields this about -p
switch:
-p, --parents
no error if existing, make parent directories as needed
Use case example: Assume I want to create directories hello/goodbye
but none exist:
$mkdir hello/goodbye
mkdir:cannot create directory 'hello/goodbye': No such file or directory
$mkdir -p hello/goodbye
$
-p
created both, hello
and goodbye
This means that the command will create all the directories necessaries to fulfill your request, not returning any error in case that directory exists.
About rlidwka
, Google has a very good memory for acronyms :). My search returned this for example: http://www.cs.cmu.edu/~help/afs/afs_acls.html
Directory permissions
l (lookup)
Allows one to list the contents of a directory. It does not allow the reading of files.
i (insert)
Allows one to create new files in a directory or copy new files to a directory.
d (delete)
Allows one to remove files and sub-directories from a directory.
a (administer)
Allows one to change a directory's ACL. The owner of a directory can always change the ACL of a directory that s/he owns, along with the ACLs of any subdirectories in that directory.
File permissions
r (read)
Allows one to read the contents of file in the directory.
w (write)
Allows one to modify the contents of files in a directory and use chmod on them.
k (lock)
Allows programs to lock files in a directory.
Hence rlidwka
means: All permissions on.
It's worth mentioning, as @KeithThompson pointed out in the comments, that not all Unix systems support ACL. So probably the rlidwka
concept doesn't apply here.
Best way to store date
in SQlite DB is to store the current DateTimeMilliseconds
. Below is the code snippet to do so_
- Get the
DateTimeMilliseconds
public static long getTimeMillis(String dateString, String dateFormat) throws ParseException {
/*Use date format as according to your need! Ex. - yyyy/MM/dd HH:mm:ss */
String myDate = dateString;//"2017/12/20 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
Date date = sdf.parse(myDate);
long millis = date.getTime();
return millis;
}
- Insert the data in your DB
public void insert(Context mContext, long dateTimeMillis, String msg) {
//Your DB Helper
MyDatabaseHelper dbHelper = new MyDatabaseHelper(mContext);
database = dbHelper.getWritableDatabase();
ContentValues contentValue = new ContentValues();
contentValue.put(MyDatabaseHelper.DATE_MILLIS, dateTimeMillis);
contentValue.put(MyDatabaseHelper.MESSAGE, msg);
//insert data in DB
database.insert("your_table_name", null, contentValue);
//Close the DB connection.
dbHelper.close();
}
Now, your data (date is in currentTimeMilliseconds) is get inserted in DB .
Next step is, when you want to retrieve data from DB you need to convert the respective date time milliseconds in to corresponding date. Below is the sample code snippet to do the same_
- Convert date milliseconds in to date string.
public static String getDate(long milliSeconds, String dateFormat)
{
// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
- Now, Finally fetch the data and see its working...
public ArrayList<String> fetchData() {
ArrayList<String> listOfAllDates = new ArrayList<String>();
String cDate = null;
MyDatabaseHelper dbHelper = new MyDatabaseHelper("your_app_context");
database = dbHelper.getWritableDatabase();
String[] columns = new String[] {MyDatabaseHelper.DATE_MILLIS, MyDatabaseHelper.MESSAGE};
Cursor cursor = database.query("your_table_name", columns, null, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()){
do{
//iterate the cursor to get data.
cDate = getDate(cursor.getLong(cursor.getColumnIndex(MyDatabaseHelper.DATE_MILLIS)), "yyyy/MM/dd HH:mm:ss");
listOfAllDates.add(cDate);
}while(cursor.moveToNext());
}
cursor.close();
//Close the DB connection.
dbHelper.close();
return listOfAllDates;
}
Hope this will help all! :)
You get the index number of the row in the datagridview using northwind database employees tables as an example:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'nORTHWNDDataSet.Employees' table. You can move, or remove it, as needed.
this.employeesTableAdapter.Fill(this.nORTHWNDDataSet.Employees);
}
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var dataIndexNo = dataGridView1.Rows[e.RowIndex].Index.ToString();
string cellValue = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
MessageBox.Show("The row index = " + dataIndexNo.ToString() + " and the row data in second column is: "
+ cellValue.ToString());
}
}
}
the result will show you index number of record and the contents of the second table column in datagridview:
A good example of where this matters in practice is the ConcurrentSkipListSet
implementation in the JDK, which states:
Beware that, unlike in most collections, the size method is not a constant-time operation.
This is a clear case where isEmpty()
is much more efficient than checking whether size()==0
.
You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.
Just to make this simpler, to create a Date
in UTC
you can use Calendar
:
Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Which will construct a new instance for Calendar
using the "UTC" TimeZone
.
If you need a Date
object from that calendar you could just use getTime()
.
Please add this option:
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
(Reference: Chart.js)
N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion
Here is an example for passing parameters to a fxml document through namespace.
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns="http://javafx.com/javafx/null" xmlns:fx="http://javafx.com/fxml/1">
<BorderPane>
<center>
<Label text="$labelText"/>
</center>
</BorderPane>
</VBox>
Define value External Text
for namespace variable labelText
:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class NamespaceParameterExampleApplication extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException {
final FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("namespace-parameter-example.fxml"));
fxmlLoader.getNamespace()
.put("labelText", "External Text");
final Parent root = fxmlLoader.load();
primaryStage.setTitle("Namespace Parameter Example");
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
}
Just adding my experience, studying computer engineering I see that the two or three professors that I have seen writing in C always cast malloc, however the one I asked (with an immense CV and understanding of C) told me that it is absolutely unnecessary but only used to be absolutely specific, and to get the students into the mentality of being absolutely specific. Essentially casting will not change anything in how it works, it does exactly what it says, allocates memory, and casting does not effect it, you get the same memory, and even if you cast it to something else by mistake (and somehow evade compiler errors) C will access it the same way.
Edit: Casting has a certain point. When you use array notation, the code generated has to know how many memory places it has to advance to reach the beginning of the next element, this is achieved through casting. This way you know that for a double you go 8 bytes ahead while for an int you go 4, and so on. Thus it has no effect if you use pointer notation, in array notation it becomes necessary.
Need to make sure once switched into a frame, need to switch back to default content for accessing webelements in another frames. As Webdriver tend to find the new frame inside the current frame.
driver.switchTo().defaultContent()
char *charPtr = "test string";
cout << charPtr << endl;
string str = charPtr;
cout << str << endl;
I can't be satisfied by the answers calling for a English-only solution based on manual formats. I've been looking for a proper solution for a while now and I finally found it.
You should be using RuleBasedNumberFormat. It works perfectly and it's respectful of the Locale.
The best way to remove illegal character from user input is to replace illegal character using Regex class, create method in code behind or also it validate at client side using RegularExpression control.
public string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_]+", "_", RegexOptions.Compiled);
}
OR
<asp:RegularExpressionValidator ID="regxFolderName"
runat="server"
ErrorMessage="Enter folder name with a-z A-Z0-9_"
ControlToValidate="txtFolderName"
Display="Dynamic"
ValidationExpression="^[a-zA-Z0-9_]*$"
ForeColor="Red">
I sometimes get this problem when changing from Debug to Release or vice-versa. Closing and reopening QtCreator and building again solves the problem for me.
Qt Creator 2.8.1; Qt 5.1.1 (MSVC2010, 32bit)
Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:
//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
if (e.which == 13) e.preventDefault();
});
Thanks to this answer: https://stackoverflow.com/a/1977126/560114.
Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:
Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.
content_script.js
(function () {
var visited = window.location.href;
var time = +new Date();
chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
console.log("Just visited",visited)
});
})();
popup.js
(function () {
chrome.storage.onChanged.addListener(function (changes,areaName) {
console.log("New item in storage",changes.visitedPages.newValue);
})
})();
"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.
Remember to declare storage permission in manifest.json.
manifest.json
...
"permissions": [
"storage"
],
...
The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.
Another possibility would be to set the Working Directory
under the debugging options to be the directory that has that DLL.
Edit: I was going to mention using a batch file to start Visual Studio (and set the PATH variable in the batch file). So then did a bit of searching and see that this exact same question was asked not long ago in this post. The answer suggests the batch file option as well as project settings that apparently may do the job (I did not test it).
Try restarting the application (creating an app_offline.htm than deleting it will do) and if you still get the same error message, make sure you've only declared customErrors once in the web.config, or anything like that. Errors in the web.config can have some weird impact on the application.
git show-branch
There's a lot you can do with core git functionality. It might be good to specify what you'd like to include in your visual diff. Most answers focus on line-by-line diffs of commits, where your example focuses on names of files affected in a given commit.
One visual that seems not to be addressed is how to see the commits that branches contain (whether in common or uniquely).
For this visual, I'm a big fan of git show-branch
; it breaks out a well organized table of commits per branch back to the common ancestor.
- to try it on a repo with multiple branches with divergences, just type git show-branch
and check the output
- for a writeup with examples, see Compare Commits Between Git Branches
@Andrea Tulimiero 's answer works for local, but when you ssh to a remote server, the beep turns on again. My suggestion is to disable from the Windows 10 taskbar. There is volume mixer in the right bottom corner, which works for me.
A generic solution using Khoth's answer as a starting point.
/**
* @param set a Set in which to look for a random element
* @param <T> generic type of the Set elements
* @return a random element in the Set or null if the set is empty
*/
public <T> T randomElement(Set<T> set) {
int size = set.size();
int item = random.nextInt(size);
int i = 0;
for (T obj : set) {
if (i == item) {
return obj;
}
i++;
}
return null;
}
I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.
You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.
The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.
This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.
I was playing around with the following code for another question on StackOverflow and thought that it might be appropriate for here. The function printList2 allows the use of a regex and lists all the occurrences in order. (printList was an attempt at an earlier solution, but it failed in a number of cases.)
<html>_x000D_
<head>_x000D_
<title>Checking regex</title>_x000D_
<script>_x000D_
var string1 = "123xxx5yyy1234ABCxxxabc";_x000D_
var search1 = /\d+/;_x000D_
var search2 = /\d/;_x000D_
var search3 = /abc/;_x000D_
function printList(search) {_x000D_
document.writeln("<p>Searching using regex: " + search + " (printList)</p>");_x000D_
var list = string1.match(search);_x000D_
if (list == null) {_x000D_
document.writeln("<p>No matches</p>");_x000D_
return;_x000D_
}_x000D_
// document.writeln("<p>" + list.toString() + "</p>");_x000D_
// document.writeln("<p>" + typeof(list1) + "</p>");_x000D_
// document.writeln("<p>" + Array.isArray(list1) + "</p>");_x000D_
// document.writeln("<p>" + list1 + "</p>");_x000D_
var count = list.length;_x000D_
document.writeln("<ul>");_x000D_
for (i = 0; i < count; i++) {_x000D_
document.writeln("<li>" + " " + list[i] + " length=" + list[i].length + _x000D_
" first position=" + string1.indexOf(list[i]) + "</li>");_x000D_
}_x000D_
document.writeln("</ul>");_x000D_
}_x000D_
function printList2(search) {_x000D_
document.writeln("<p>Searching using regex: " + search + " (printList2)</p>");_x000D_
var index = 0;_x000D_
var partial = string1;_x000D_
document.writeln("<ol>");_x000D_
for (j = 0; j < 100; j++) {_x000D_
var found = partial.match(search);_x000D_
if (found == null) {_x000D_
// document.writeln("<p>not found</p>");_x000D_
break;_x000D_
}_x000D_
var size = found[0].length;_x000D_
var loc = partial.search(search);_x000D_
var actloc = loc + index;_x000D_
document.writeln("<li>" + found[0] + " length=" + size + " first position=" + actloc);_x000D_
// document.writeln(" " + partial + " " + loc);_x000D_
partial = partial.substring(loc + size);_x000D_
index = index + loc + size;_x000D_
document.writeln("</li>");_x000D_
}_x000D_
document.writeln("</ol>");_x000D_
_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<p>Original string is <script>document.writeln(string1);</script></p>_x000D_
<script>_x000D_
printList(/\d+/g);_x000D_
printList2(/\d+/);_x000D_
printList(/\d/g);_x000D_
printList2(/\d/);_x000D_
printList(/abc/g);_x000D_
printList2(/abc/);_x000D_
printList(/ABC/gi);_x000D_
printList2(/ABC/i);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
yauzl is a robust library for unzipping. Design principles:
Currently has 97% test coverage.
alter table User
add constraint userProperties
foreign key (properties)
references Properties(ID)
You have no way to see who has checked out your repository using standard git commands such as git clone
, but you can see who has forked your repository on GitHub using the Network Graph Visualizer. At the time of this answer, you can access this feature in at least two ways:
For example, here is a partial screenshot of the rbenv network graph:
The "Members" tab at the top of the Network Graph will also show you a different view, listing the names of the people who currently have forks on GitHub. It obviously will not show people who cloned outside of GitHub, or folks who have subsequently deleted their forks.
For everyone who felt they want to run away with all the steps and screen shots on the (great!) above answers, this worked for me with android studio 2.2.1
:
Create a new project, name it as you want and take the default (minSdkVersion 15 is fine).
Download the zip file from here: https://sourceforge.net/projects/opencvlibrary/files/opencv-android/ (I downloaded 3.2.0 version, but there may be a newer versions).
Unzip the zip file, the best place is in your workspace folder, but it not really matter.
Inside Android Studio
, click File->New-> Import Module
and navigate to \path_to_your_unzipped_file\OpenCV-android-sdk\sdk\java
and hit Ok, then accept all default dialogs.
In the gradle
file of your app
module, add this to the dependencies block:
dependencies {
compile project(':openCVLibraryXYZ')
//rest of code
}
Where XYZ is the exact version you downloaded, for example in my case:
dependencies {
compile project(':openCVLibrary320')
//rest of code
}
Instance methods need to be called from an instance. Your setLoanItem
method is an instance method (it doesn't have the modifier static
), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this
)).
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(Btw it would be better to use a boolean instead of a string containing "Yes".)
As other answers pointed out, it is most likely generated by some tool.
But if I were the original author of the file, my answer would be: Consistency.
If I am not allowed to put double quotes in my attributes, why put them in the element's content ? Why do these specs always have these exceptional cases ..
If I had to write the HTML spec, I would say All double quotes need to be encoded
. Done.
Today it is like In attribute values we need to encode double quotes, except when the attribute value itself is defined by single quotes. In the content of elements, double quotes can be, but are not required to be, encoded.
(And I am surely forgetting some cases here).
Double quotes are a keyword of the spec, encode them. Lesser/greater than are a keyword of the spec, encode them. etc..
An adventage of use ExpectedException Rule (version 4.7) is that you can test exception message and not only the expected exception.
And using Matchers, you can test the part of message you are interested:
exception.expectMessage(containsString("income: -1000.0"));
mongoDB Atlas has a indexes tab when under their collections tab that allows you to view and delete any index you do not want.
<input type="radio" name="brd" onclick="javascript:brd();" value="IN">
<input type="radio" name="brd" onclick="javascript:brd();" value="EX">`
<script type="text/javascript">
function brd() {alert($('[name="brd"]:checked').val());}
</script>
If the remote branch already exists then you can (probably) get away with..
git checkout branch_name
and git will automatically set up to track the remote branch with the same name on origin.
I realize this post is a few years old, but I just wanted to extend this to anyone still struggling through this issue.
The company I work for still uses VS2015 so in turn I still use VS2015. I recently started working on a RPC application using C++ and found the need to download the Win32 Templates. Like many others I was having this "SDK 8.1 was not found" issue. i took the following corrective actions with no luck.
None of the attempts above corrected the issue for me...
I then found this article on social MSDN https://social.msdn.microsoft.com/Forums/office/en-US/5287c51b-46d0-4a79-baad-ddde36af4885/visual-studio-cant-find-windows-81-sdk-when-trying-to-build-vs2015?forum=visualstudiogeneral
Finally what resolved the issue for me was:
I hope this saves anyone else from almost 3 full days of frustration and loss of productivity.
If you want the latest file in the directory and you are using only the LastWriteTime
to determine the latest file, you can do something like below:
gci path | sort LastWriteTime | select -last 1
On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar
gci path | select -last 1
Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}
The easiest way is to use sshpass. This is available in Ubuntu/Debian repositories and you don't have to deal with integrating expect with Bash.
An example:
sshpass -p<password> ssh <arguments>
sshpass -ptest1324 ssh [email protected] ls -l /tmp
The above command can be easily integrated with a Bash script.
Note: Please read the Security Considerations section in man sshpass
for a full understanding of the security implications.
Maybe this will help someone else, but I've seen this error when the RHS of the mapping contains a colon without enclosing quotes, such as:
someKey: another key: Change to make today: work out more
should be
someKey: another key: "Change to make today: work out more"
R doesn't have a concept of increment operator
(as for example ++ in C). However, it is not difficult to implement one yourself, for example:
inc <- function(x)
{
eval.parent(substitute(x <- x + 1))
}
In that case you would call
x <- 10
inc(x)
However, it introduces function call overhead, so it's slower than typing x <- x + 1
yourself. If I'm not mistaken increment operator
was introduced to make job for compiler easier, as it could convert the code to those machine language instructions directly.
In my opinion the bare minimum implementation has two requirements. A state that keeps track of whether the modal is open or not, and a portal to render the modal outside of the standard react tree.
The ModalContainer component below implements those requirements along with corresponding render functions for the modal and the trigger, which is responsible for executing the callback to open the modal.
import React from 'react';
import PropTypes from 'prop-types';
import Portal from 'react-portal';
class ModalContainer extends React.Component {
state = {
isOpen: false,
};
openModal = () => {
this.setState(() => ({ isOpen: true }));
}
closeModal = () => {
this.setState(() => ({ isOpen: false }));
}
renderModal() {
return (
this.props.renderModal({
isOpen: this.state.isOpen,
closeModal: this.closeModal,
})
);
}
renderTrigger() {
return (
this.props.renderTrigger({
openModal: this.openModal
})
)
}
render() {
return (
<React.Fragment>
<Portal>
{this.renderModal()}
</Portal>
{this.renderTrigger()}
</React.Fragment>
);
}
}
ModalContainer.propTypes = {
renderModal: PropTypes.func.isRequired,
renderTrigger: PropTypes.func.isRequired,
};
export default ModalContainer;
And here's a simple use case...
import React from 'react';
import Modal from 'react-modal';
import Fade from 'components/Animations/Fade';
import ModalContainer from 'components/ModalContainer';
const SimpleModal = ({ isOpen, closeModal }) => (
<Fade visible={isOpen}> // example use case with animation components
<Modal>
<Button onClick={closeModal}>
close modal
</Button>
</Modal>
</Fade>
);
const SimpleModalButton = ({ openModal }) => (
<button onClick={openModal}>
open modal
</button>
);
const SimpleButtonWithModal = () => (
<ModalContainer
renderModal={props => <SimpleModal {...props} />}
renderTrigger={props => <SimpleModalButton {...props} />}
/>
);
export default SimpleButtonWithModal;
I use render functions, because I want to isolate state management and boilerplate logic from the implementation of the rendered modal and trigger component. This allows the rendered components to be whatever you want them to be. In your case, I suppose the modal component could be a connected component that receives a callback function that dispatches an asynchronous action.
If you need to send dynamic props to the modal component from the trigger component, which hopefully doesn't happen too often, I recommend wrapping the ModalContainer with a container component that manages the dynamic props in its own state and enhance the original render methods like so.
import React from 'react'
import partialRight from 'lodash/partialRight';
import ModalContainer from 'components/ModalContainer';
class ErrorModalContainer extends React.Component {
state = { message: '' }
onError = (message, callback) => {
this.setState(
() => ({ message }),
() => callback && callback()
);
}
renderModal = (props) => (
this.props.renderModal({
...props,
message: this.state.message,
})
)
renderTrigger = (props) => (
this.props.renderTrigger({
openModal: partialRight(this.onError, props.openModal)
})
)
render() {
return (
<ModalContainer
renderModal={this.renderModal}
renderTrigger={this.renderTrigger}
/>
)
}
}
ErrorModalContainer.propTypes = (
ModalContainer.propTypes
);
export default ErrorModalContainer;
private boolean containsIgnoreCase(List<String> list, String soughtFor) {
for (String current : list) {
if (current.equalsIgnoreCase(soughtFor)) {
return true;
}
}
return false;
}
This is OK too; For example:
==> In "NumberController" file:
public ActionResult Create([Bind(Include = "NumberId,Number1,Number2,OperatorId")] Number number)
{
if (ModelState.IsValid)
{
...
...
return RedirectToAction("Index");
}
ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId",
"OperatorSign", number.OperatorId);
return View();
}
==> In View file (Create.cshtml):
<div class="form-group">
@Html.LabelFor(model => model.Number1, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Number1, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Number1, "", new { @class =
"text-danger" })
</div>
</div>
Now if we remove this statement:
ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", "OperatorSign", number.OperatorId);
from back of the following statement (in our controller) :
return View();
we will see this error:
There is no ViewData item of type 'IEnumerable' that has the key 'OperatorId'.
* So be sure of the existing of these statements. *
I've read through these answers multiple times, but didn't REALLY get it until I learned about the technical definition of "Call by sharing" as termed by Barbara Liskov
The semantics of call by sharing differ from call by reference in that assignments to function arguments within the function aren't visible to the caller (unlike by reference semantics)[citation needed], so e.g. if a variable was passed, it is not possible to simulate an assignment on that variable in the caller's scope. However, since the function has access to the same object as the caller (no copy is made), mutations to those objects, if the objects are mutable, within the function are visible to the caller, which may appear to differ from call by value semantics. Mutations of a mutable object within the function are visible to the caller because the object is not copied or cloned — it is shared.
That is, parameter references are alterable if you go and access the parameter value itself. On the other hand, assignment to a parameter will disappear after evaluation, and is non-accessible to the function caller.
This helped me to get uri from Gallery and convert to a file for Multipart upload
File file = FileUtils.getFile(this, fileUri);
First: Even the unique IDs generated by java UUID.randomUUID or .net GUID are not 100% unique. Especialy UUID.randomUUID is "only" a 128 bit (secure) random value. So if you reduce it to 64 bit, 32 bit, 16 bit (or even 1 bit) then it becomes simply less unique.
So it is at least a risk based decisions, how long your uuid must be.
Second: I assume that when you talk about "only 8 characters" you mean a String of 8 normal printable characters.
If you want a unique string with length 8 printable characters you could use a base64 encoding. This means 6bit per char, so you get 48bit in total (possible not very unique - but maybe it is ok for you application)
So the way is simple: create a 6 byte random array
SecureRandom rand;
// ...
byte[] randomBytes = new byte[16];
rand.nextBytes(randomBytes);
And then transform it to a Base64 String, for example by org.apache.commons.codec.binary.Base64
BTW: it depends on your application if there is a better way to create "uuid" then by random. (If you create a the UUIDs only once per second, then it is a good idea to add a time stamp) (By the way: if you combine (xor) two random values, the result is always at least as random as the most random of the both).
This may work for you, Please try this.
<form>
<div class="form-inline">
<div class="controls-row">
<label class="control-label">Some label</label>
<label class="radio inline">
<input type="radio" value="1" />First
</label>
<label class="radio inline">
<input type="radio" value="2" />Second
</label>
</div>
</div>
</form>
Foreign keys are almost always "Allow Duplicates," which would make them unsuitable as Primary Keys.
Instead, find a field that uniquely identifies each record in the table, or add a new field (either an auto-incrementing integer or a GUID) to act as the primary key.
The only exception to this are tables with a one-to-one relationship, where the foreign key and primary key of the linked table are one and the same.
To get body lines use escape()
body_line = escape("\n");
so
href = "mailto:[email protected]?body=hello,"+body_line+"I like this.";
Working example is given below,
MyService.class
public class MyService extends Service implements SpeechDelegate, Speech.stopDueToDelay {
public static SpeechDelegate delegate;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
Speech.init(this);
delegate = this;
Speech.getInstance().setListener(this);
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
System.setProperty("rx.unsafe-disable", "True");
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
@Override
public void onStartOfSpeech() {
}
@Override
public void onSpeechRmsChanged(float value) {
}
@Override
public void onSpeechPartialResults(List<String> results) {
for (String partial : results) {
Log.d("Result", partial+"");
}
}
@Override
public void onSpeechResult(String result) {
Log.d("Result", result+"");
if (!TextUtils.isEmpty(result)) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSpecifiedCommandPronounced(String event) {
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
//Restarting the service if it is removed.
PendingIntent service =
PendingIntent.getService(getApplicationContext(), new Random().nextInt(),
new Intent(getApplicationContext(), MyService.class), PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
super.onTaskRemoved(rootIntent);
}
}
For more details,
Hope this will help someone in future.
use the "unlink" command and make sure not to have the / at the end
$ unlink mySymLink
unlink() deletes a name from the file system. If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse. If the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.
I think this may be problematic if I'm reading it correctly.
If the name referred to a symbolic link the link is removed.
If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.
For me, I am working on .net 4.5.2 with web api 2.0, I have the same error, i set it just by adding requestPathInvalidCharacters="" in the requestPathInvalidCharacters you have to set not allowed characters else you have to remove characters that cause this problem.
<system.web>
<httpRuntime targetFramework="4.5.2" requestPathInvalidCharacters="" />
<pages >
<namespaces>
....
</namespaces>
</pages>
</system.web>
**Note that it is not a good practice, may be a post with this parameter as attribute of an object is better or try to encode the special character. -- After searching on best practice for designing rest api, i found that in search, sort and paginnation, we have to handle the query parameter like this
/companies?search=Digital%26Mckinsey
and this solve the problem when we encode & and remplace it on the url by %26 any way, on the server we receive the correct parameter Digital&Mckinsey
this link may help on best practice of designing rest web api https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9
If you only want to have a list of large files, then I'd like to provide you with the following one-liner:
join -o "1.1 1.2 2.3" <(git rev-list --objects --all | sort) <(git verify-pack -v objects/pack/*.idx | sort -k3 -n | tail -5 | sort) | sort -k3 -n
Whose output will be:
commit file name size in bytes
72e1e6d20... db/players.sql 818314
ea20b964a... app/assets/images/background_final2.png 6739212
f8344b9b5... data_test/pg_xlog/000000010000000000000001 1625545
1ecc2395c... data_development/pg_xlog/000000010000000000000001 16777216
bc83d216d... app/assets/images/background_1forfinal.psd 95533848
The last entry in the list points to the largest file in your git history.
You can use this output to assure that you're not deleting stuff with BFG you would have needed in your history.
Be aware, that you need to clone your repository with --mirror
for this to work.
What's the error log say? I got this error, and it ended up being an old invalid setting in the my.cnf, which the mysql error log indicated. If not a bad config setting, the error log should at least point you in the right direction.
Well, I assume the OP has fixed it at this point... but hopefully this points the others seeing this error in the right direction.
You can say that it is with PHP, but actually it has just one PHP command, all other files are just *.html.
AddType application/x-httpd-php .html
<?php include("meniu.html"); ?>
.That's all!
Remark: all commands like <? ...>
will be treated as php executables, so if your html have question marks, then you could have some problems.
Just for the purpose of mentioning underscore's find method works in IE with no problem.
The server should respond with the correct MIME Type for JSONP application/javascript
and your request should tell jQuery you are loading JSONP dataType: 'jsonp'
Please see this answer for further details !
You can also have a look a this one as it explains why loading .js
file with text/plain
won't work.
Analogous to @Resh32, but without the need to use the USE
statement:
SELECT TABLE_NAME,
COLUMN_NAME,
CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,
REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "database_name"
AND TABLE_NAME = "table_name"
AND REFERENCED_COLUMN_NAME IS NOT NULL;
Useful, e.g. using the ORM.
If you can't do
UPDATE table SET a=value WHERE x IN
(SELECT x FROM table WHERE condition);
because it is the same table, you can trick and do :
UPDATE table SET a=value WHERE x IN
(SELECT * FROM (SELECT x FROM table WHERE condition) as t)
[update or delete or whatever]
You could do either:
dirname(__DIR__);
Or:
__DIR__ . '/..';
...but in a web server environment you will probably find that you are already working from current file's working directory, so you can probably just use:
'../'
...to reference the directory above. You can replace __DIR__
with dirname(__FILE__)
before PHP 5.3.0.
You should also be aware what __DIR__
and __FILE__
refers to:
The full path and filename of the file. If used inside an include, the name of the included file is returned.
So it may not always point to where you want it to.
Actually more sane sources are provided by http://suckless.org look at their sbase
repository:
git clone git://git.suckless.org/sbase
They are clearer, smarter, simpler and suckless, eg ls.c
has just 369 LOC
After that it will be easier to understand more complicated GNU code.
I use a tool called Prepo to produce all the right image sizes. You simply feed the app you image file and it will spit out each necessary file with an appropriate name.
Once you do this, you can then drag in the appropriate files or simply point to your Prepo exported folder.
edit your .bash_profile
file
vim .bash_profile
commnet
#export TERM=xterm-256color
add this
export TERMINFO=/usr/share/terminfo
export TERM=xterm-basic
to your .bash_profile
finally
run:
source .bash_profile
$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
To my understanding, when you need to train a NN, you need a large dataset involves many data items. when NN is being trained, data items go in to NN one by one, that is called an iteration; When the whole dataset goes through, it is called an epoch.
The default dbpath for mongodb is /data/db
.
There is no default config file, so you will either need to specify this when starting mongod
with:
mongod --config /etc/mongodb.conf
.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.
Note: to check the dbpath and command-line options for a running mongod
, connect via the mongo
shell and run:
db.serverCmdLineOpts()
In particular, if a custom dbpath
is set it will be the value of:
db.serverCmdLineOpts().parsed.dbpath // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath // MongoDB 2.6+
Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:
List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));
inspired by @jason-bunting, same thing for either height or width:
function resizeElementDimension(element, doHeight) {
dim = (doHeight ? 'Height' : 'Width')
ref = (doHeight ? 'Top' : 'Left')
var x = 0;
var body = window.document.body;
if(window['inner' + dim])
x = window['inner' + dim]
else if (body.parentElement['client' + dim])
x = body.parentElement['client' + dim]
else if (body && body['client' + dim])
x = body['client' + dim]
element.style[dim.toLowerCase()] = ((x - element['offset' + ref]) + "px");
}
There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.
This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )
SELECT questionid,
LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM (SELECT questionid,
elementid,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
FROM emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;
String.split uses Regular Expressions, also you don't need to allocate an extra array for your split.
The split-method will give you a list., the problem is that you try to pre-define how many occurrences you have of a tab, but how would you Really know that? Try using the Scanner or StringTokenizer and just learn how splitting strings work.
Let me explain Why \t does not work and why you need \\\\
to escape \\
.
Okay, so when you use Split, it actually takes a regex ( Regular Expression ) and in regular expression you want to define what Character to split by, and if you write \t that actually doesn't mean \t
and what you WANT to split by is \t
, right? So, by just writing \t
you tell your regex-processor that "Hey split by the character that is escaped t" NOT "Hey split by all characters looking like \t
". Notice the difference? Using \ means to escape something. And \
in regex means something Totally different than what you think.
So this is why you need to use this Solution:
\\t
To tell the regex processor to look for \t. Okay, so why would you need two of em? Well, the first \ escapes the second, which means it will look like this: \t when you are processing the text!
Now let's say that you are looking to split \
Well then you would be left with \\ but see, that doesn't Work! because \ will try to escape the previous char! That is why you want the Output to be \\ and therefore you need to have \\\\.
I really hope the examples above helps you understand why your solution doesn't work and how to conquer other ones!
Now, I've given you this answer before, maybe you should start looking at them now.
OTHER METHODS
StringTokenizer
You should look into the StringTokenizer, it's a very handy tool for this type of work.
Example
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
This will output
this
is
a
test
You use the Second Constructor for StringTokenizer to set the delimiter:
StringTokenizer(String str, String delim)
Scanner
You could also use a Scanner as one of the commentators said this could look somewhat like this
Example
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
The output would be
1
2
red
blue
Meaning that it will cut out the word "fish" and give you the rest, using "fish" as the delimiter.
myFunction(
contextParamers : {
param1: any,
param2: string
param3: string
}){
contextParamers.param1 = contextParamers.param1+ 'canChange';
//contextParamers.param4 = "CannotChange";
var contextParamers2 : any = contextParamers;// lost the typescript on the new object of type any
contextParamers2.param4 = 'canChange';
return contextParamers2;
}
%Started Program or Command% | taskkill /F /IM cmd.exe
Example:
notepad.exe | taskkill /F /IM cmd.exe