You can use the function outer()
to generate it.
Have a look at the demo for the function persp()
, which is a base graphics function to draw perspective plots for surfaces.
Here is their first example:
x <- seq(-10, 10, length.out = 50)
y <- x
rotsinc <- function(x,y) {
sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }
10 * sinc( sqrt(x^2+y^2) )
}
z <- outer(x, y, rotsinc)
persp(x, y, z)
The same applies to surface3d()
:
require(rgl)
surface3d(x, y, z)
Here is a small example that shows the usefulness of the Action delegate
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Action<String> print = new Action<String>(Program.Print);
List<String> names = new List<String> { "andrew", "nicole" };
names.ForEach(print);
Console.Read();
}
static void Print(String s)
{
Console.WriteLine(s);
}
}
Notice that the foreach method iterates the collection of names and executes the print
method against each member of the collection. This a bit of a paradigm shift for us C# developers as we move towards a more functional style of programming. (For more info on the computer science behind it read this: http://en.wikipedia.org/wiki/Map_(higher-order_function).
Now if you are using C# 3 you can slick this up a bit with a lambda expression like so:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String> { "andrew", "nicole" };
names.ForEach(s => Console.WriteLine(s));
Console.Read();
}
}
I'd start by using glob:
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
im=Image.open(filename)
image_list.append(im)
then do what you need to do with your list of images (image_list).
If you don’t need to support IE8 you can use the input
event:
var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));
resizingTextareas.forEach(function(textarea) {
textarea.addEventListener('input', autoresize, false);
});
function autoresize() {
this.style.height = 'auto';
this.style.height = this.scrollHeight+'px';
this.scrollTop = this.scrollHeight;
window.scrollTo(window.scrollLeft,(this.scrollTop+this.scrollHeight));
}
Now you only need to add some CSS and you are done:
textarea[autoresize] {
display: block;
overflow: hidden;
resize: none;
}
Usage:
<textarea autoresize>Type here and I’ll resize.</textarea>
You can read more about how it works on my blog post.
tabs: [...data.map((title) { return Text(title);}).toList(), extra_widget],
tabs: data.map((title) { return Text(title);}).toList(),
It's working fine for me
I think I've accidentally found a solution. The only thing to do is inserting an empty <span class="input-group-addon"></span>
between the <input>
and the <select>
.
Additionally you can make it "invisible" by reducing its width, horizontal padding and borders:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
<span class="input-group-addon" title="* Price" id="priceLabel">Price</span>_x000D_
<input type="number" id="searchbygenerals_priceFrom" name="searchbygenerals[priceFrom]" required="required" class="form-control" value="0">_x000D_
<span class="input-group-addon">-</span>_x000D_
<input type="number" id="searchbygenerals_priceTo" name="searchbygenerals[priceTo]" required="required" class="form-control" value="0">_x000D_
_x000D_
<!-- insert this line -->_x000D_
<span class="input-group-addon" style="width:0px; padding-left:0px; padding-right:0px; border:none;"></span>_x000D_
_x000D_
<select id="searchbygenerals_currency" name="searchbygenerals[currency]" class="form-control">_x000D_
<option value="1">HUF</option>_x000D_
<option value="2">EUR</option>_x000D_
</select>_x000D_
</div>
_x000D_
Tested on Chrome and FireFox.
no... Once u have executed the statement anotherList.addAll(list) and after that if u change some list data it does not carry to another list
For tomcat you can increase the permGem space by using
-XX:MaxPermSize=128m
For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it
export JAVA_OPTS="-XX:MaxPermSize=128m"
Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat
I would do something like this:
boolean foundQuote = false;
if(charAtIndex(currentStringIndex) == '"')
{
foundQuote = true;
}
if(foundQuote == true)
{
//do nothing
}
else
{
string[] split = currentString.split(',');
}
It might be a bit too heavyweight for you, but GlazedLists has a SortedList that is perfect to use as the model of a table or JList
git tag -l --format='%(contents)'
or
git for-each-ref refs/tags/ --format='%(contents)'
will output full annotation message for every tag (including signature if its signed).
%(contents:subject)
will output only first line%(contents:body)
will output annotation without first line and signature (useful text only)%(contents:signature)
will output only PGP-signatureSee more in man git-for-each-ref
“Field names” section.
For the record, jQuery has an is()
function for this:
a.is(b)
Note that a
is already a jQuery instance.
Figure out what version of python3 you have installed:
yum search pip
and then install the best match. Use reqoquery to find name of resulting pip3.e.g
repoquery -l python36u-pip
tells me to use pip3.6 instead of pip3
The following will give you all the elements which is not equal to your special characters!
review = jQuery.grep( review, function ( value ) {
return ( value !== '\u2022 \u2022 \u2022' );
} );
You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3
(and uses it as default), so switch back to a value of 2
which can be read by Python 2.
Check the protocol
parameter in pickle.dump
. Your resulting code will look like this.
pickle.dump(your_object, your_file, protocol=2)
There is no protocol
parameter in pickle.load
because pickle
can determine the protocol from the file.
Simple one:
var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.
However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub
. What if there are multiple jenkins servers that need to access the same gitolite server?
(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)
So in this case you do need to run the Jenkins daemon as a different user.
There are two steps:
The main thing is to update the JENKINS_USER
environment variable. Here's a patch showing how to change the user to ptran
.
--- etc/default/jenkins.old 2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
PIDFILE=/var/run/jenkins/jenkins.pid
# user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran
# location of the jenkins war file
JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old 2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins 2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@
#DAEMON=$JENKINS_SH
DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG - -pidfile=$PIDFILE"
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE"
SU=/bin/su
END PATCH
Update ownership of jenkins directories:
chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins
Restart jenkins
sudo service jenkins restart
Since there is the [vba] tag, split is also easy:
str1 = "001 baseball"
str2 = Split(str1)
Then use str2(1).
New Excel versions
=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)
Older Excel versions
=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)
That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."
Using
public String replaceAll(String regex, String replacement)
will work.
Usage would be str.replace("X", "");
.
Executing
"Xlakjsdf Xxx".replaceAll("X", "");
returns:
lakjsdf xx
I would have put this in a comment on the accepted answer, since that's where it belongs, but I can't. So, just in case anyone gets unreliable results, this could be why.
Be careful of the accepted answer, it fails if the time_point is before the epoch.
This line of code:
std::size_t fractional_seconds = ms.count() % 1000;
will yield unexpected values if ms.count() is negative (since size_t is not meant to hold negative values).
With RxJS 5.5+, the catch
operator is now deprecated. You should now use the catchError
operator in conjunction with pipe
.
RxJS v5.5.2 is the default dependency version for Angular 5.
For each RxJS Operator you import, including catchError
you should now import from 'rxjs/operators' and use the pipe operator.
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...
export class ExampleClass {
constructor(private http: HttpClient) {
this.http.request(method, url, options).pipe(
catchError((err: HttpErrorResponse) => {
...
}
)
}
...
}
Notice here that catch
is replaced with catchError
and the pipe
operator is used to compose the operators in similar manner to what you're used to with dot-chaining.
See the rxjs documentation on pipable (previously known as lettable) operators for more info.
WPF takes a slightly different approach than WinForms here. Instead of having the automation of a object built into the API, they have a separate class for each object that is responsible for automating it. In this case you need the ButtonAutomationPeer
to accomplish this task.
ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();
Here is a blog post on the subject.
Note: IInvokeProvider
interface is defined in the UIAutomationProvider
assembly.
In JavaScript there are no predefined methods to use namespaces. In JavaScript we have to create our own methods to define NameSpaces. Here is a procedure we follow in Oodles technologies.
Register a NameSpace Following is the function to register a name space
//Register NameSpaces Function
function registerNS(args){
var nameSpaceParts = args.split(".");
var root = window;
for(var i=0; i < nameSpaceParts.length; i++)
{
if(typeof root[nameSpaceParts[i]] == "undefined")
root[nameSpaceParts[i]] = new Object();
root = root[nameSpaceParts[i]];
}
}
To register a Namespace just call the above function with the argument as name space separated by '.'
(dot).
For Example
Let your application name is oodles. You can make a namespace by following method
registerNS("oodles.HomeUtilities");
registerNS("oodles.GlobalUtilities");
var $OHU = oodles.HomeUtilities;
var $OGU = oodles.GlobalUtilities;
Basically it will create your NameSpaces structure like below in backend:
var oodles = {
"HomeUtilities": {},
"GlobalUtilities": {}
};
In the above function you have register a namespace called "oodles.HomeUtilities"
and "oodles.GlobalUtilities"
. To call these namespaces we make an variable i.e. var $OHU
and var $OGU
.
These variables are nothing but an alias to Intializing the namespace.
Now, Whenever you declare a function that belong to HomeUtilities
you will declare it like following:
$OHU.initialization = function(){
//Your Code Here
};
Above is the function name initialization and it is put into an namespace $OHU
. and to call this function anywhere in the script files. Just use following code.
$OHU.initialization();
Similarly, with the another NameSpaces.
Hope it helps.
This answer is totally unrelated to the OP's situation, and is a very unlikely scenario for anyone else too, but just in case it may help someone ...
In my case I was getting "Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0 ..." because I had disassembled and reassembled the program using ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 2. Switching to ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 4 fixed the problem.
(Strangely, even though doing what I did may seem like an obvious error, the resulting EXE file that didn't work did indicate that it targeted .Net 4 when examined with JetBrains dotPeek.)
based on Jon's Idea and dear Trufa
def modifyTuple(tup, oldval, newval):
lst=list(tup)
for i in range(tup.count(oldval)):
index = lst.index(oldval)
lst[index]=newval
return tuple(lst)
print modTupByIndex((1, 1, 3), 1, "a")
it changes all of your old values occurrences
The main differences between github and gists are in terms of number of features and user interface:
One is designed with a great number of features and flexibility in mind, which is a good fit for both small and very big projects, while gists are only a good fit for very small projects.
For example, gists do support multi-files, but the interface is very simple, and they're limited in features, so they don't even have a file browser, nor issues, pull requests or wiki. If you dont need to have that, gists are very nice and more discrete. Like the comments, instead of answers, in SO.
Note: Thanks to @Qwerty for the suggestion of making my comment a real answer.
I have redirected from http:// to https:// and this problem was resolved!
You can do smth like this for 1D arrays. Here we use int*& because we want our pointer to be changeable.
#include<algorithm> // for copy
void resize(int*& a, size_t& n)
{
size_t new_n = 2 * n;
int* new_a = new int[new_n];
copy(a, a + n, new_a);
delete[] a;
a = new_a;
n = new_n;
}
For 2D arrays:
#include<algorithm> // for copy
void resize(int**& a, size_t& n)
{
size_t new_n = 2 * n, i = 0;
int** new_a = new int* [new_n];
for (i = 0; i != new_n; ++i)
new_a[i] = new int[100];
for (i = 0; i != n; ++i)
{
copy(a[i], a[i] + 100, new_a[i]);
delete[] a[i];
}
delete[] a;
a = new_a;
n = new_n;
}
Invoking of 1D array:
void myfn(int*& a, size_t& n)
{
// do smth
resize(a, n);
}
Invoking of 2D array:
void myfn(int**& a, size_t& n)
{
// do smth
resize(a, n);
}
This is rather a method than just a single script but gives you much more flexibility.
First of all There are 3 objects:
ColumnActionList
] -> holds data as
parameter proc_PivotPrepare
] -> prepares our dataproc_PivotExecute
] -> execute the scriptCREATE TYPE [dbo].[ColumnActionList] AS TABLE ( [ID] [smallint] NOT NULL, [ColumnName] nvarchar NOT NULL, [Action] nchar NOT NULL ); GO
CREATE PROCEDURE [dbo].[proc_PivotPrepare]
(
@DB_Name nvarchar(128),
@TableName nvarchar(128)
)
AS
SELECT @DB_Name = ISNULL(@DB_Name,db_name())
DECLARE @SQL_Code nvarchar(max)
DECLARE @MyTab TABLE (ID smallint identity(1,1), [Column_Name] nvarchar(128), [Type] nchar(1), [Set Action SQL] nvarchar(max));
SELECT @SQL_Code = 'SELECT [<| SQL_Code |>] = '' '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Declare user defined type [ID] / [ColumnName] / [PivotAction] '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''DECLARE @ColumnListWithActions ColumnActionList;'''
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Set [PivotAction] (''''S'''' as default) to select dimentions and values '' '
+ 'UNION ALL '
+ 'SELECT ''-----|'''
+ 'UNION ALL '
+ 'SELECT ''-----| ''''S'''' = Stable column || ''''D'''' = Dimention column || ''''V'''' = Value column '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''INSERT INTO @ColumnListWithActions VALUES ('' + CAST( ROW_NUMBER() OVER (ORDER BY [NAME]) as nvarchar(10)) + '', '' + '''''''' + [NAME] + ''''''''+ '', ''''S'''');'''
+ 'FROM [' + @DB_Name + '].sys.columns '
+ 'WHERE object_id = object_id(''[' + @DB_Name + ']..[' + @TableName + ']'') '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Execute sp_PivotExecute with parameters: columns and dimentions and main table name'' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''EXEC [dbo].[sp_PivotExecute] @ColumnListWithActions, ' + '''''' + @TableName + '''''' + ';'''
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
EXECUTE SP_EXECUTESQL @SQL_Code;
GO
CREATE PROCEDURE [dbo].[sp_PivotExecute]
(
@ColumnListWithActions ColumnActionList ReadOnly
,@TableName nvarchar(128)
)
AS
--#######################################################################################################################
--###| Step 1 - Select our user-defined-table-variable into temp table
--#######################################################################################################################
IF OBJECT_ID('tempdb.dbo.#ColumnListWithActions', 'U') IS NOT NULL DROP TABLE #ColumnListWithActions;
SELECT * INTO #ColumnListWithActions FROM @ColumnListWithActions;
--#######################################################################################################################
--###| Step 2 - Preparing lists of column groups as strings:
--#######################################################################################################################
DECLARE @ColumnName nvarchar(128)
DECLARE @Destiny nchar(1)
DECLARE @ListOfColumns_Stable nvarchar(max)
DECLARE @ListOfColumns_Dimension nvarchar(max)
DECLARE @ListOfColumns_Variable nvarchar(max)
--############################
--###| Cursor for List of Stable Columns
--############################
DECLARE ColumnListStringCreator_S CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'S'
OPEN ColumnListStringCreator_S;
FETCH NEXT FROM ColumnListStringCreator_S
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Stable = ISNULL(@ListOfColumns_Stable, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_S INTO @ColumnName
END
CLOSE ColumnListStringCreator_S;
DEALLOCATE ColumnListStringCreator_S;
--############################
--###| Cursor for List of Dimension Columns
--############################
DECLARE ColumnListStringCreator_D CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'D'
OPEN ColumnListStringCreator_D;
FETCH NEXT FROM ColumnListStringCreator_D
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Dimension = ISNULL(@ListOfColumns_Dimension, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_D INTO @ColumnName
END
CLOSE ColumnListStringCreator_D;
DEALLOCATE ColumnListStringCreator_D;
--############################
--###| Cursor for List of Variable Columns
--############################
DECLARE ColumnListStringCreator_V CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'V'
OPEN ColumnListStringCreator_V;
FETCH NEXT FROM ColumnListStringCreator_V
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Variable = ISNULL(@ListOfColumns_Variable, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_V INTO @ColumnName
END
CLOSE ColumnListStringCreator_V;
DEALLOCATE ColumnListStringCreator_V;
SELECT @ListOfColumns_Variable = LEFT(@ListOfColumns_Variable, LEN(@ListOfColumns_Variable) - 1);
SELECT @ListOfColumns_Dimension = LEFT(@ListOfColumns_Dimension, LEN(@ListOfColumns_Dimension) - 1);
SELECT @ListOfColumns_Stable = LEFT(@ListOfColumns_Stable, LEN(@ListOfColumns_Stable) - 1);
--#######################################################################################################################
--###| Step 3 - Preparing table with all possible connections between Dimension columns excluding NULLs
--#######################################################################################################################
DECLARE @DIM_TAB TABLE ([DIM_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @DIM_TAB
SELECT [DIM_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'D';
DECLARE @DIM_ID smallint;
SELECT @DIM_ID = 1;
DECLARE @SQL_Dimentions nvarchar(max);
IF OBJECT_ID('tempdb.dbo.##ALL_Dimentions', 'U') IS NOT NULL DROP TABLE ##ALL_Dimentions;
SELECT @SQL_Dimentions = 'SELECT [xxx_ID_xxx] = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Dimension + '), ' + @ListOfColumns_Dimension
+ ' INTO ##ALL_Dimentions '
+ ' FROM (SELECT DISTINCT' + @ListOfColumns_Dimension + ' FROM ' + @TableName
+ ' WHERE ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
SELECT @DIM_ID = @DIM_ID + 1;
WHILE @DIM_ID <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
BEGIN
SELECT @SQL_Dimentions = @SQL_Dimentions + 'AND ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
SELECT @DIM_ID = @DIM_ID + 1;
END
SELECT @SQL_Dimentions = @SQL_Dimentions + ' )x';
EXECUTE SP_EXECUTESQL @SQL_Dimentions;
--#######################################################################################################################
--###| Step 4 - Preparing table with all possible connections between Stable columns excluding NULLs
--#######################################################################################################################
DECLARE @StabPos_TAB TABLE ([StabPos_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @StabPos_TAB
SELECT [StabPos_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'S';
DECLARE @StabPos_ID smallint;
SELECT @StabPos_ID = 1;
DECLARE @SQL_MainStableColumnTable nvarchar(max);
IF OBJECT_ID('tempdb.dbo.##ALL_StableColumns', 'U') IS NOT NULL DROP TABLE ##ALL_StableColumns;
SELECT @SQL_MainStableColumnTable = 'SELECT xxx_ID_xxx = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Stable + '), ' + @ListOfColumns_Stable
+ ' INTO ##ALL_StableColumns '
+ ' FROM (SELECT DISTINCT' + @ListOfColumns_Stable + ' FROM ' + @TableName
+ ' WHERE ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
SELECT @StabPos_ID = @StabPos_ID + 1;
WHILE @StabPos_ID <= (SELECT MAX([StabPos_ID]) FROM @StabPos_TAB)
BEGIN
SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + 'AND ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
SELECT @StabPos_ID = @StabPos_ID + 1;
END
SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + ' )x';
EXECUTE SP_EXECUTESQL @SQL_MainStableColumnTable;
--#######################################################################################################################
--###| Step 5 - Preparing table with all options ID
--#######################################################################################################################
DECLARE @FULL_SQL_1 NVARCHAR(MAX)
SELECT @FULL_SQL_1 = ''
DECLARE @i smallint
IF OBJECT_ID('tempdb.dbo.##FinalTab', 'U') IS NOT NULL DROP TABLE ##FinalTab;
SELECT @FULL_SQL_1 = 'SELECT t.*, dim.[xxx_ID_xxx] '
+ ' INTO ##FinalTab '
+ 'FROM ' + @TableName + ' t '
+ 'JOIN ##ALL_Dimentions dim '
+ 'ON t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1);
SELECT @i = 2
WHILE @i <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
BEGIN
SELECT @FULL_SQL_1 = @FULL_SQL_1 + ' AND t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i)
SELECT @i = @i +1
END
EXECUTE SP_EXECUTESQL @FULL_SQL_1
--#######################################################################################################################
--###| Step 6 - Selecting final data
--#######################################################################################################################
DECLARE @STAB_TAB TABLE ([STAB_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @STAB_TAB
SELECT [STAB_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'S';
DECLARE @VAR_TAB TABLE ([VAR_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @VAR_TAB
SELECT [VAR_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'V';
DECLARE @y smallint;
DECLARE @x smallint;
DECLARE @z smallint;
DECLARE @FinalCode nvarchar(max)
SELECT @FinalCode = ' SELECT ID1.*'
SELECT @y = 1
WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
BEGIN
SELECT @z = 1
WHILE @z <= (SELECT MAX([VAR_ID]) FROM @VAR_TAB)
BEGIN
SELECT @FinalCode = @FinalCode + ', [ID' + CAST((@y) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z) + '] = ID' + CAST((@y + 1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z)
SELECT @z = @z + 1
END
SELECT @y = @y + 1
END
SELECT @FinalCode = @FinalCode +
' FROM ( SELECT * FROM ##ALL_StableColumns)ID1';
SELECT @y = 1
WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
BEGIN
SELECT @x = 1
SELECT @FinalCode = @FinalCode
+ ' LEFT JOIN (SELECT ' + @ListOfColumns_Stable + ' , ' + @ListOfColumns_Variable
+ ' FROM ##FinalTab WHERE [xxx_ID_xxx] = '
+ CAST(@y as varchar(10)) + ' )ID' + CAST((@y + 1) as varchar(10))
+ ' ON 1 = 1'
WHILE @x <= (SELECT MAX([STAB_ID]) FROM @STAB_TAB)
BEGIN
SELECT @FinalCode = @FinalCode + ' AND ID1.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x) + ' = ID' + CAST((@y+1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x)
SELECT @x = @x +1
END
SELECT @y = @y + 1
END
SELECT * FROM ##ALL_Dimentions;
EXECUTE SP_EXECUTESQL @FinalCode;
From executing the first query (by passing source DB and table name) you will get a pre-created execution query for the second SP, all you have to do is define is the column from your source: + Stable + Value (will be used to concentrate values based on that) + Dim (column you want to use to pivot by)
Names and datatypes will be defined automatically!
I cant recommend it for any production environments but does the job for adhoc BI requests.
I had the same issue and it was to do with my file name. If you set the file location using CD in CMD, and then type DIR it will list the files in that directory. Check that the file name appears and check that the spelling and filename ending is correct.
It should be .java but mine was .java.txt. The instructions on the Java tutorials website state that you should select "Save as Type Text Documents" but for me that always adds .txt onto the end of the file name. If I change it to "Save as Type All Documents" it correctly saved the file name.
Also, you could try to use ndarray.item()
, for example, arr.item((0, 0))
(rowid+colid to index) or arr.item(0)
(flatten index), its doc https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html
Here how to do this on mongodb 3.0. I used this nice blog
$ mkdir RANDOM_PATH/node1 $ mkdir RANDOM_PATH/node2> $ mkdir RANDOM_PATH/node3
$ mongod --replSet test --port 27021 --dbpath node1 $ mongod --replSet test --port 27022 --dbpath node2 $ mongod --replSet test --port 27023 --dbpath node3
$ mongo config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]}; rs.initiate(config);
a. Download and unzip the [latest Elasticsearch][2] distribution b. Run bin/elasticsearch to start the es server. c. Run curl -XGET http://localhost:9200/ to confirm it is working.
$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb
$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments
curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'
Test on browser:
There's no good reason for 1
to be true and 0
to be false; that's just the way things have always been notated. So from a logical perspective, the function in your API isn't "wrong", per se.
That said, it's normally not advisable to work against the idioms of whatever language or framework you're using without a damn good reason to do so, so whoever wrote this function was probably pretty bone-headed, assuming it's not simply a bug.
string input = "User name (sales)";
string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.
Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render()
method of a widget.
Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected
is a valid concept in OOP in general (though not, of course, in Python).
pip has mirror support
pip --use-mirrors install yolk
As of version 1.5, this option will be removed:
1.5 (unreleased)
BACKWARD INCOMPATIBLE pip no longer supports the --use-mirrors, -M, and --mirrors flags. The mirroring support has been removed. In order to use a mirror specify it as the primary index with -i or --index-url, or as an additional index with --extra-index-url. (Pull #1098, CVE-2013-5123)
BACKWARD INCOMPATIBLE pip no longer will scrape insecure external urls by default nor will it install externally hosted files by default. Users may opt into installing externally hosted or insecure files or urls using --allow-external PROJECT and --allow-insecure PROJECT. (Pull #1055)
Added colors to the logging output in order to draw attention to important warnings and errors. (Pull #1109)
Added warnings when using an insecure index, find-link, or dependency link. (Pull #1121)
Here's how
String details = "Hello \"world\"!";
details = details.replace("\"","\\\"");
System.out.println(details); // Hello \"world\"!
Note that strings are immutable, thus it is not sufficient to simply do details.replace("\"","\\\"")
. You must reassign the variable details
to the resulting string.
Using
details = details.replaceAll("\"",""e;");
instead, results in
Hello "e;world"e;!
Normally one uses the backslash character as the path separator in Windows. So:
ifstream file;
file.open("C:\\Demo.txt", ios::in);
Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt
.
It happened to me before.
When the table has been created and I added in .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
later, the code migration somehow could not assign default value for the Guid column.
The fix:
All we need is to go to the database, select the Id column and add newsequentialid()
manually into Default Value or Binding
.
No need to update dbo.__MigrationHistory table.
Hope it helps.
The solution of adding New Guid()
is generally not preferred, because in theory there is possibility that you might get a duplicate accidentally.
And you shouldn't worry about directly editing in the database. All Entity Framework do is automate part of our database work.
Translating
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
into
[Id] [uniqueidentifier] NOT NULL DEFAULT newsequentialid(),
If somehow our EF missed one thing and did not add in the default value for us, just go ahead and add it manually.
MinGW
forked from version 1.3.3 ofCygwin
. Although bothCygwin
andMinGW
can be used to portUNIX
software toWindows
, they have different approaches:Cygwin
aims to provide a completePOSIX layer
that provides emulations of several system calls and libraries that exist onLinux
,UNIX
, and theBSD
variants. ThePOSIX layer
runs on top ofWindows
, sacrificing performance where necessary for compatibility. Accordingly, this approach requiresWindows
programs written withCygwin
to run on top of a copylefted compatibility library that must be distributed with the program, along with the program'ssource code
.MinGW
aims to provide native functionality and performance via directWindows API calls
. UnlikeCygwin
,MinGW
does not require a compatibility layerDLL
and thus programs do not need to be distributed withsource code
.Because
MinGW
is dependent uponWindows API calls
, it cannot provide a fullPOSIX API
; it is unable to compile someUNIX applications
that can be compiled withCygwin
. Specifically, this applies to applications that requirePOSIX
functionality likefork()
,mmap()
orioctl()
and those that expect to be run in aPOSIX environment
. Applications written using across-platform library
that has itself been ported toMinGW
, such asSDL
,wxWidgets
,Qt
, orGTK+
, will usually compile as easily inMinGW
as they would inCygwin
.The combination of
MinGW
andMSYS
provides a small, self-contained environment that can be loaded onto removable media without leaving entries in the registry or files on the computer.Cygwin
Portable provides a similar feature. By providing more functionality,Cygwin
becomes more complicated to install and maintain.It is also possible to
cross-compile Windows applications
withMinGW-GCC under POSIX systems
. This means that developers do not need a Windows installation withMSYS
to compile software that will run onWindows
withoutCygwin
.
I think with np.array()
you can only create C like though you mention the order, when you check using np.isfortran()
it says false. but with np.ndarrray()
when you specify the order it creates based on the order provided.
[Ljava.lang.Object;
is the name for Object[].class
, the java.lang.Class
representing the class of array of Object
.
The naming scheme is documented in Class.getName()
:
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).
If this class object represents a primitive type or
void
, then the name returned is the Java language keyword corresponding to the primitive type orvoid
.If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more
'['
characters representing the depth of the array nesting. The encoding of element type names is as follows:Element Type Encoding boolean Z byte B char C double D float F int I long J short S class or interface Lclassname;
Yours is the last on that list. Here are some examples:
// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx
The reason why the toString()
method on arrays returns String
in this format is because arrays do not @Override
the method inherited from Object
, which is specified as follows:
The
toString
method for classObject
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())
Note: you can not rely on the toString()
of any arbitrary object to follow the above specification, since they can (and usually do) @Override
it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass()
on it (a final
method inherited from Object
) and then reflecting on the returned Class
object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).
toString
for arraysjava.util.Arrays
provides toString
overloads for primitive arrays and Object[]
. There is also deepToString
that you may want to use for nested arrays.
Here are some examples:
int[] nums = { 1, 2, 3 };
System.out.println(nums);
// [I@xxxxx
System.out.println(Arrays.toString(nums));
// [1, 2, 3]
int[][] table = {
{ 1, },
{ 2, 3, },
{ 4, 5, 6, },
};
System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]
System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]
There are also Arrays.equals
and Arrays.deepEquals
that perform array equality comparison by their elements, among many other array-related utility methods.
Web.config file
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS; Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>
.cs file
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
function getEffectiveVotes($id)
According to the function header, there is only one parameter variable ($id
).
Thus, on line 27, the votes[]
array is undefined and out of scope. You need to add another
parameter value to the function header so that function getEffectiveVotes()
knows to expect two parameters. I'm rusty, but something like this would work.
function getEffectiveVotes($id, $votes)
I'm not saying this is how it should be done, but you might want to research how PHP passes its arrays and decide if you need to explicitly state to pass it by reference
function getEffectiveVotes($id &$votes) <---I forget, no time to look it up right now.
Lastly, call function getEffectiveVotes()
with both arguments wherever it is supposed to be called.
Cheers.
Use dictionary comprehension way,
x = {k:v for k,v in enumerate(states) if v == True}
Input:
states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
Output:
{4: True, 5: True, 7: True}
Check the following one-liner:
print('\n'.join("%s\n%s" % (key1,('\n'.join("%s : %r" % (key2,val2) for (key2,val2) in val1.items()))) for (key1,val1) in cars.items()))
Output:
A
speed : 70
color : 2
B
speed : 60
color : 3
Method overloading can come in handy here Like:
<code>
public class myClass
{
int add(int a, int b)
{
return (a + b);
}
String add(String a, String b)
{
return (c + d);
}
public static void main(String args[])
{
myClass ob1 = new myClass);
ob1.add(2, 3);
//will return 5
ob1.add("Hello, ", "World!");
//will return Hello, World!
}
}
I came across the same problem. To be precise, I have two branches A
and B
with the same files but a different programming interface in some files. Now the methods of file f
, which is independent of the interface differences in the two branches, were changed in branch B
, but the change is important for both branches. Thus, I need to merge just file f
of branch B
into file f
of branch A
.
A simple command already solved the problem for me if I assume that all changes are committed in both branches A
and B
:
git checkout A
git checkout --patch B f
The first command switches into branch A
, into where I want to merge B
's version of the file f
. The second command patches the file f
with f
of HEAD
of B
. You may even accept/discard single parts of the patch. Instead of B
you can specify any commit here, it does not have to be HEAD
.
Community edit: If the file f
on B
does not exist on A
yet, then omit the --patch
option. Otherwise, you'll get a "No Change." message.
Use the latest supportLibrary
, version 27.1.1
to solve the problem. worked for me. (many bug fixes included - see changelog)
I have smaller code todo this:
$path = "Pending2Post/";
$files = scandir($path);
foreach ($files as &$value) {
echo "<a href='http://localhost/".$value."' target='_blank' >".$value."</a><br/><br/>";
}
This might be late as I think most of us are using BS4. This article explained all the questions you asked in a detailed and simple manner also includes what to do when. The detailed guide to use bs4 or bootstrap
https://uxplanet.org/how-the-bootstrap-4-grid-works-a1b04703a3b7
I got the same error recently. I think McX is right it was caused by insufficient memory on RDP server. Here is the solution that works for us.
use sc cmd to get running services on the remote server. Make sure you can use windows explorer to access the remote server \\remote_server.
sc \\<remote_server> query
find out the service you can stop.
sc \\<remote_server> stop <service_name>
After stopping one service, the remote desktop works again.
This looks like a decent overview of dynamic script loading: http://unixpapa.com/js/dyna.html
Try this:
SELECT h.year, h.id, h.rate
FROM (SELECT h.year, h.id, h.rate, IF(@lastid = (@lastid:=h.id), @index:=@index+1, @index:=0) indx
FROM (SELECT h.year, h.id, h.rate
FROM h
WHERE h.year BETWEEN 2000 AND 2009 AND id IN (SELECT rid FROM table2)
GROUP BY id, h.year
ORDER BY id, rate DESC
) h, (SELECT @lastid:='', @index:=0) AS a
) h
WHERE h.indx <= 5;
=IIf((CountRows("ScannerStatisticsData")=0),False,True)
Should be replaced with
=IIf((CountRows("ScannerStatisticsData")=0),True,False)
because the Visibility expression set up the Hidden value.
You can also use lambda
. Lambda syntax is not supported under Java 1.7 or earlier JVMs.
listView.setOnItemClickListener((parent, view, position, id) -> {
...
});
I've managed to find a CSS workaround to preventing bouncing of the viewport. The key was to wrap the content in 3 divs with -webkit-touch-overflow:scroll applied to them. The final div should have a min-height of 101%. In addition, you should explicitly set fixed widths/heights on the body tag representing the size of your device. I've added a red background on the body to demonstrate that it is the content that is now bouncing and not the mobile safari viewport.
Source code below and here is a plunker (this has been tested on iOS7 GM too). http://embed.plnkr.co/NCOFoY/preview
If you intend to run this as a full-screen app on iPhone 5, modify the height to 1136px (when apple-mobile-web-app-status-bar-style is set to 'black-translucent' or 1096px when set to 'black'). 920x is the height of the viewport once the chrome of mobile safari has been taken into account).
<!doctype html>
<html>
<head>
<meta name="viewport" content="initial-scale=0.5,maximum-scale=0.5,minimum-scale=0.5,user-scalable=no" />
<style>
body { width: 640px; height: 920px; overflow: hidden; margin: 0; padding: 0; background: red; }
.no-bounce { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
.no-bounce > div { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
.no-bounce > div > div { width: 100%; min-height: 101%; font-size: 30px; }
p { display: block; height: 50px; }
</style>
</head>
<body>
<div class="no-bounce">
<div>
<div>
<h1>Some title</h1>
<p>item 1</p>
<p>item 2</p>
<p>item 3</p>
<p>item 4</p>
<p>item 5</p>
<p>item 6</p>
<p>item 7</p>
<p>item 8</p>
<p>item 9</p>
<p>item 10</p>
<p>item 11</p>
<p>item 12</p>
<p>item 13</p>
<p>item 14</p>
<p>item 15</p>
<p>item 16</p>
<p>item 17</p>
<p>item 18</p>
<p>item 19</p>
<p>item 20</p>
</div>
</div>
</div>
</body>
</html>
This should work:
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)
curl_exec($ch);
In the receiving script, you would have:
print_r($_FILES);
/* which would output something like
Array (
[uploaded_file] => Array (
[tmp_name] => /tmp/f87453hf
[name] => myimage.jpg
[error] => 0
[size] => 12345
[type] => image/jpeg
)
)
*/
Then, if you want to properly handle the file upload, you would do something like this:
if (move_uploaded_file($_FILES['uploaded_file'], '/path/to/destination/file.zip')) {
// do stuff
}
I dont know if this useful for you when you resize your page:
$(window).resize(function() {
if(screen.width == window.innerWidth){
alert("you are on normal page with 100% zoom");
} else if(screen.width > window.innerWidth){
alert("you have zoomed in the page i.e more than 100%");
} else {
alert("you have zoomed out i.e less than 100%");
}
});
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
/* array literal */
var aData = [];
/* object constructur */
function Person(firstname, lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = function() {
return (this.firstname + " " + this.lastname);
};
}
/* store object into array */
aData[aData.length] = new Person("Java", "Script"); // aData[0]
aData.push(new Person("Jhon", "Doe"));
aData.push(new Person("Anna", "Smith"));
aData.push(new Person("Black", "Pearl"));
aData[aData.length] = new Person("stack", "overflow"); // aData[4]
/* loop array */
for (var i in aData) {
alert(aData[i].fullname());
}
/* convert array of object into string json */
var jsonString = JSON.stringify(aData);
document.write(jsonString);
_x000D_
It depends on where your postgresql server is installed. You use the pg_ctl to manually start the server like below.
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
Use git rebase
. Specifically:
git stash
to store the changes you want to add.git rebase -i HEAD~10
(or however many commits back you want to see).a0865...
) for edit by changing the word pick
at the start of the line into edit
. Don't delete the other lines as that would delete the commits.[^vimnote]git stash pop
git add <file>
.git commit --amend --no-edit
.git rebase --continue
which will rewrite the rest of your commits against the new one.[^vimnote]: If you are using vim
then you will have to hit the Insert key to edit, then Esc and type in :wq
to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano"
.
The term cohesion is indeed a little counter intuitive for what it means in software design.
Cohesion common meaning is that something that sticks together well, is united, which are characterized by strong bond like molecular attraction. However in software design, it means striving for a class that ideally does only one thing, so multiple sub-modules are not even involved.
Perhaps we can think of it this way. A part has the most cohesion when it is the only part (does only one thing and can't be broken down further). This is what is desired in software design. Cohesion simply is another name for "single responsibility" or "separation of concerns".
The term coupling on the hand is quite intuitive which means when a module doesn't depend on too many other modules and those that it connects with can be easily replaced for example obeying liskov substitution principle .
You can also simply set your pandas column as list of id values with length same as of dataframe.
df['New_ID'] = range(880, 880+len(df))
Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html
BEGIN
FOR r IN (select sid,serial# from v$session where username='user')
LOOP
EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid || ','
|| r.serial# || ''' immediate';
END LOOP;
END;
This should work - I just changed your script to add the immediate
keyword. As the previous answers pointed out, the kill session
only marks the sessions for killing; it does not do so immediately but later when convenient.
From your question, it seemed you are expecting to see the result immediately. So immediate
keyword is used to force this.
You can filter all 'invalid' chars with a custom FilterReader class:
public class InvalidXmlCharacterFilter extends FilterReader {
protected InvalidXmlCharacterFilter(Reader in) {
super(in);
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int read = super.read(cbuf, off, len);
if (read == -1) return read;
for (int i = off; i < off + read; i++) {
if (!XMLChar.isValid(cbuf[i])) cbuf[i] = '?';
}
return read;
}
}
And run it like this:
InputStream fileStream = new FileInputStream(xmlFile);
Reader reader = new BufferedReader(new InputStreamReader(fileStream, charset));
InvalidXmlCharacterFilter filter = new InvalidXmlCharacterFilter(reader);
InputSource is = new InputSource(filter);
xmlReader.parse(is);
List All:
SHOW FULL PROCESSLIST
if you want to kill a hang transaction copy transaction id and kill transaction by using this command:
KILL <id> // e.g KILL 16543
This should help, uses simple hash table.
$a1=@(1,2,3,4,5) $b1=@(1,2,3,4,5,6)
$hash= @{}
#storing elements of $a1 in hash
foreach ($i in $a1)
{$hash.Add($i, "present")}
#define blank array $c
$c = @()
#adding uncommon ones in second array to $c and removing common ones from hash
foreach($j in $b1)
{
if(!$hash.ContainsKey($j)){$c = $c+$j}
else {hash.Remove($j)}
}
#now hash is left with uncommon ones in first array, so add them to $c
foreach($k in $hash.keys)
{
$c = $c + $k
}
Swift 5
Swift 5: Check using canOpneURL
if valid then it's open.
guard let url = URL(string: "https://iosdevcenters.blogspot.com/") else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
I just discovered that MySQL will take null provided the default for the field is null and I write specific if statements and leave off the quotes. This works for update as well.
if(empty($odate) AND empty($ddate))
{
$query2="UPDATE items SET odate=null, ddate=null, istatus='$istatus' WHERE id='$id' ";
};
As of today November 2017
Bootstrap v4 - beta
Responsive utilities
All @screen- variables have been removed in v4.0.0. Use the media-breakpoint-up(), media-breakpoint-down(), or media-breakpoint-only() Sass mixins or the $grid-breakpoints Sass map instead.
Removed from v3: .hidden-xs .hidden-sm .hidden-md .hidden-lg .visible-xs-block .visible-xs-inline .visible-xs-inline-block .visible-sm-block .visible-sm-inline .visible-sm-inline-block .visible-md-block .visible-md-inline .visible-md-inline-block .visible-lg-block .visible-lg-inline .visible-lg-inline-block
Removed from v4 alphas: .hidden-xs-up .hidden-xs-down .hidden-sm-up .hidden-sm-down .hidden-md-up .hidden-md-down .hidden-lg-up .hidden-lg-down
https://getbootstrap.com/docs/4.0/migration/#responsive-utilities
public void ChargingArraySelect()
{
int loop = 0;
int registros = 0;
OdbcConnection conn = WebApiConfig.conn();
OdbcCommand query = conn.CreateCommand();
query.CommandText = "select dataA, DataB, dataC, DataD FROM table where dataA = 'xpto'";
try
{
conn.Open();
OdbcDataReader dr = query.ExecuteReader();
//take the number the registers, to use into next step
registros = dr.RecordsAffected;
//calls an array to be populated
Global.arrayTest = new string[registros, 4];
while (dr.Read())
{
if (loop < registros)
{
Global.arrayTest[i, 0] = Convert.ToString(dr["dataA"]);
Global.arrayTest[i, 1] = Convert.ToString(dr["dataB"]);
Global.arrayTest[i, 2] = Convert.ToString(dr["dataC"]);
Global.arrayTest[i, 3] = Convert.ToString(dr["dataD"]);
}
loop++;
}
}
}
//Declaration the Globais Array in Global Classs
private static string[] uso_internoArray1;
public static string[] arrayTest
{
get { return uso_internoArray1; }
set { uso_internoArray1 = value; }
}
You can use below command to check if it returns 0 or 1 :
In below example, I am checking for the string in the one particular file which will give you 1 if that particular word "Error" is not present in the file and if present then 0
find /i "| ERROR1 |" C:\myfile.txt
echo %errorlevel%
if %errorlevel% equ 1 goto notfound
goto found
:notfound
exit 1
:found
echo we found the text.
For auto reload and clear cache after 3 second you can do it easily using javascript setInterval function. Here is simple code
$(document).ready(function() {_x000D_
setInterval(function() {_x000D_
cache_clear()_x000D_
}, 3000);_x000D_
});_x000D_
_x000D_
function cache_clear() {_x000D_
window.location.reload(true);_x000D_
// window.location.reload(); use this if you do not remove cache_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<p>Auto reload page and clear cache</p>
_x000D_
and you can also use meta for this
<meta http-equiv="Refresh" content="5">
Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in
<![CDATA[ ...raw html... ]]>
Example:
<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>
Then, in your code:
TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));
IMHO, this is several orders of magnitude nicer to work with :-)
I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
iBeacon uses Bluetooth Low Energy(LE) to keep aware of locations, and the distance/range of Bluetooth LE is 160ft (http://en.wikipedia.org/wiki/Bluetooth_low_energy).
The benefit of write-through to main memory is that it simplifies the design of the computer system. With write-through, the main memory always has an up-to-date copy of the line. So when a read is done, main memory can always reply with the requested data.
If write-back is used, sometimes the up-to-date data is in a processor cache, and sometimes it is in main memory. If the data is in a processor cache, then that processor must stop main memory from replying to the read request, because the main memory might have a stale copy of the data. This is more complicated than write-through.
Also, write-through can simplify the cache coherency protocol because it doesn't need the Modify state. The Modify state records that the cache must write back the cache line before it invalidates or evicts the line. In write-through a cache line can always be invalidated without writing back since memory already has an up-to-date copy of the line.
One more thing - on a write-back architecture software that writes to memory-mapped I/O registers must take extra steps to make sure that writes are immediately sent out of the cache. Otherwise writes are not visible outside the core until the line is read by another processor or the line is evicted.
Press ESC to first go into command mode
. Then Press Shift+D.
I have recently made a program that computes a few different stats, including mode. While the coding may be rudimentary, it works for any array of ints, and could be modified to be doubles, floats, etc. The modification to the array is based on deleting indexes in the array that are not the final mode value(s). This allows you to show all modes (if there are multiple) as well as have the amount of occurrences (last item in modes array). The code below is the getMode method as well as the deleteValueIndex method needed to run this code
import java.io.File;
import java.util.Scanner;
import java.io.PrintStream;
public static int[] getMode(final int[] array) {
int[] numOfVals = new int[array.length];
int[] valsList = new int[array.length];
//initialize the numOfVals and valsList
for(int ix = 0; ix < array.length; ix++) {
valsList[ix] = array[ix];
}
for(int ix = 0; ix < numOfVals.length; ix++) {
numOfVals[ix] = 1;
}
//freq table of items in valsList
for(int ix = 0; ix < valsList.length - 1; ix++) {
for(int ix2 = ix + 1; ix2 < valsList.length; ix2++) {
if(valsList[ix2] == valsList[ix]) {
numOfVals[ix] += 1;
}
}
}
//deletes index from valsList and numOfVals if a duplicate is found in valsList
for(int ix = 0; ix < valsList.length - 1; ix++) {
for(int ix2 = ix + 1; ix2 < valsList.length; ix2++) {
if(valsList[ix2] == valsList[ix]) {
valsList = deleteValIndex(valsList, ix2);
numOfVals = deleteValIndex(numOfVals, ix2);
}
}
}
//finds the highest occurence in numOfVals and sets it to most
int most = 0;
for(int ix = 0; ix < valsList.length; ix++) {
if(numOfVals[ix] > most) {
most = numOfVals[ix];
}
}
//deletes index from valsList and numOfVals if corresponding index in numOfVals is less than most
for(int ix = 0; ix < numOfVals.length; ix++) {
if(numOfVals[ix] < most) {
valsList = deleteValIndex(valsList, ix);
numOfVals = deleteValIndex(numOfVals, ix);
ix--;
}
}
//sets modes equal to valsList, with the last index being most(the highest occurence)
int[] modes = new int[valsList.length + 1];
for(int ix = 0; ix < valsList.length; ix++) {
modes[ix] = valsList[ix];
}
modes[modes.length - 1] = most;
return modes;
}
public static int[] deleteValIndex(int[] array, final int index) {
int[] temp = new int[array.length - 1];
int tempix = 0;
//checks if index is in array
if(index >= array.length) {
System.out.println("I'm sorry, there are not that many items in this list.");
return array;
}
//deletes index if in array
for(int ix = 0; ix < array.length; ix++) {
if(ix != index) {
temp[tempix] = array[ix];
tempix++;
}
}
return temp;
}
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
Suppose you have a hidden input, named XXX, if you want to assign a value to the following
<script type="text/javascript">
$(document).ready(function(){
$('#XXX').val('any value');
})
</script>
You should be able to use the @()
expression syntax:
<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>
element.onclick = function() { /* do stuff */ }
element.addEventListener('click', function(){ /* do stuff */ },false);
They apparently do the same thing: listen for the click event and execute a callback function. Nevertheless, they’re not equivalent. If you ever need to choose between the two, this could help you to figure out which one is the best for you.
The main difference is that onclick is just a property, and like all object properties, if you write on more than once, it will be overwritten. With addEventListener() instead, we can simply bind an event handler to the element, and we can call it each time we need it without being worried of any overwritten properties. Example is shown here,
Try it: https://jsfiddle.net/fjets5z4/5/
In first place I was tempted to keep using onclick, because it’s shorter and looks simpler… and in fact it is. But I don’t recommend using it anymore. It’s just like using inline JavaScript. Using something like – that’s inline JavaScript – is highly discouraged nowadays (inline CSS is discouraged too, but that’s another topic).
However, the addEventListener() function, despite it’s the standard, just doesn’t work in old browsers (Internet Explorer below version 9), and this is another big difference. If you need to support these ancient browsers, you should follow the onclick way. But you could also use jQuery (or one of its alternatives): it basically simplifies your work and reduces the differences between browsers, therefore can save you a lot of time.
var clickEvent = document.getElementByID("onclick-eg");
var EventListener = document.getElementByID("addEventListener-eg");
clickEvent.onclick = function(){
window.alert("1 is not called")
}
clickEvent.onclick = function(){
window.alert("1 is not called, 2 is called")
}
EventListener.addEventListener("click",function(){
window.alert("1 is called")
})
EventListener.addEventListener("click",function(){
window.alert("2 is also called")
})
String[] result = "hi i'm paul".split("\\s+");
to split across one or more cases.
Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str)
method that splits string using white space as delimiter. It also has other useful utility methods
Absolute positioning positions an element relative to its nearest positioned ancestor. So put position: relative
on the container, then for child elements, top
and left
will be relative to the top-left of the container so long as the child elements have position: absolute
. More information is available in the CSS 2.1 specification.
The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.
Create it at the following location <your home folder>/.m2/settings.xml
e.g. C:\Users\YourUserName\.m2\settings.xml
on Windows or /home/YourUserName/.m2/settings.xml
on Linux
Here's an empty skeleton you can use:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies/>
<profiles/>
<activeProfiles/>
</settings>
If you use Eclipse to edit it, it will give you auto-completion when editing it.
And here's the Maven settings.xml Reference page
Your should really use the INFORMATION_SCHEMA
views in your database:
USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
You can then filter that by table schema and/or table type, e.g.
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
In my case I tried to run npm i [email protected]
and got the error because the dev server was running in another terminal on vsc. Hit ctrl+c, y to stop it in that terminal, and then installation works.
Right click > Open.
Or, you can go into System Preferences, Security & Privacy, and set the restrictions on opening apps there.
Here is what happened in my case. I was asked to attach files for a database. I was given the file names as follows
I proceeded to attach the files and kept getting the files are in use by another process.
I ran a query against the system view select name, physical_name from sys.master_files; and saw that the exact file names were already in use by another database, thus each time I tried to attach the files, I kept getting the error the files are in use by another process(sql server)
Thus if you are getting such a message, then also query against the system view sys.master_files and see which database may already be using the same name files. Hereafter you will figure out what to do.
thanks.
None of these suggestions above worked for me as-is. I had to use the following to center a checkbox with the label text displayed to the right of the box:
<style>
.checkboxes {
display: flex;
justify-content: center;
align-items: center;
vertical-align: middle;
word-wrap: break-word;
}
</style>
<label for="checkbox1" class="checkboxes"><input type="checkbox" id="checkbox1" name="checked" value="yes" class="checkboxes"/>
Check the box.</label>
Use FilenameUtils.removeExtension
from Apache Commons IO
Example:
You can provide full path name or only the file name.
String myString1 = FilenameUtils.removeExtension("helloworld.exe"); // returns "helloworld"
String myString2 = FilenameUtils.removeExtension("/home/abc/yey.xls"); // returns "yey"
Hope this helps ..
I had this other solution (I'm posting it in case someone else as me is using the following method from the model):
class onlyUserIsActiveField(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
self.fields['is_active'].initial = False
class Meta:
model = User
fields = ['is_active']
labels = {'is_active': 'Is Active'}
widgets = {
'is_active': forms.CheckboxInput( attrs={
'class': 'form-control bootstrap-switch',
'data-size': 'mini',
'data-on-color': 'success',
'data-on-text': 'Active',
'data-off-color': 'danger',
'data-off-text': 'Inactive',
'name': 'is_active',
})
}
The initial is definded on the __init__
function as self.fields['is_active'].initial = False
In Bootstrap, the default width of modal-dialog
is 600px
. But you can explicitly change its width. For instance, if you would like to maximize its width to the value of your choice, 800px
for instance, you do as following:
.modal-dialog {
width: 800px;
margin: 30px auto;
}
Note: This change sets to all modal dialog you use in your application. Also, my suggestion is it is best to have your own CSS rules defined and not to touch the core of the framework.
If you only want it to be set for specific modal dialog, use your own catchy class name as modal-800
whose width is set to 800px
, as following:
HTML
<div class="modal">
<div class="modal-dialog modal-800">
<div class="modal-content">
</div>
</div>
</div>
CSS
.modal-dialog.modal-800 {
width: 800px;
margin: 30px auto;
}
Likewise, you can have class name as based on the width size like modal-700
whose width is 700px
.
Hope it's helpful!
in 1.x there used to be things DataTables couldn't do which DataSets could (don't remember exactly what). All that was changed in 2.x. My guess is that's why a lot of examples still use DataSets. DataTables should be quicker as they are more lightweight. If you're only pulling a single resultset, its your best choice between the two.
Prior to version 1.14, wget timeout arguments were not adhered to if downloading over https due to a bug.
Your calculation is correct for DATE
types, but if your values are timestamps, you should probably use EXTRACT
(or DATE_PART) to be sure to get only the difference in full days;
EXTRACT(DAY FROM MAX(joindate)-MIN(joindate)) AS DateDifference
An SQLfiddle to test with. Note the timestamp difference being 1 second less than 2 full days.
Everyone explained pretty well on it. Let me answer when should this class be used.
When Should You Use NoSuchElementException?
Java includes a few different ways to iterate through elements in a collection. The first of these classes, Enumeration, was introduced in JDK1.0
and is generally considered deprecated in favor of newer iteration classes, like Iterator and ListIterator.
As with most programming languages, the Iterator class includes a hasNext()
method that returns a boolean indicating if the iteration has anymore elements. If hasNext()
returns true
, then the next()
method will return the next element in the iteration. Unlike Enumeration, Iterator also has a remove()
method, which removes the last element that was obtained via next()
.
While Iterator is generalized for use with all collections in the Java Collections Framework
, ListIterator
is more specialized and only works with List-based collections, like ArrayList
, LinkedList
, and so forth. However, ListIterator
adds even more functionality by allowing iteration to traverse in both directions via hasPrevious()
and previous()
methods.
I understand the problem of performing the segue at one place and maintaining the state to send parameters in prepare for segue.
I figured out a way to do this. I've added a property called userInfoDict to ViewControllers using a category. and I've override perform segue with identifier too, in such a way that If the sender is self(means the controller itself). It will pass this userInfoDict to the next ViewController.
Here instead of passing the whole UserInfoDict you can also pass the specific params, as sender and override accordingly.
1 thing you need to keep in mind. don't forget to call super method in ur performSegue method.
If you can, use background images and set background-size: cover
. This will make the background cover the whole element.
CSS
div {
background-image: url(path/to/your/image.png);
background-repeat: no-repeat;
background-position: 50% 50%;
background-size: cover;
}
If you're stuck with using inline images there are a few options. First, there is
object-fit
This property acts on images, videos and other objects similar to background-size: cover
.
CSS
img {
object-fit: cover;
}
Sadly, browser support is not that great with IE up to version 11 not supporting it at all. The next option uses jQuery
CSS + jQuery
HTML
<div>
<img src="image.png" class="cover-image">
</div>
CSS
div {
height: 8em;
width: 15em;
}
Custom jQuery plugin
(function ($) {
$.fn.coverImage = function(contain) {
this.each(function() {
var $this = $(this),
src = $this.get(0).src,
$wrapper = $this.parent();
if (contain) {
$wrapper.css({
'background': 'url(' + src + ') 50% 50%/contain no-repeat'
});
} else {
$wrapper.css({
'background': 'url(' + src + ') 50% 50%/cover no-repeat'
});
}
$this.remove();
});
return this;
};
})(jQuery);
Use the plugin like this
jQuery('.cover-image').coverImage();
It will take an image, set it as a background image on the image's wrapper element and remove the img
tag from the document. Lastly you could use
Pure CSS
You might use this as a fallback. The image will scale up to cover it's container but it won't scale down.
CSS
div {
height: 8em;
width: 15em;
overflow: hidden;
}
div img {
min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
max-width: none;
max-height: none;
display: block;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Hope this might help somebody, happy coding!
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;
var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
return dateTime;
}
This may work for you:
select t1.*
from table t1
join (select t2.Chromosome, t2.Locus
from table2
group by t2.Chromosome, t2.Locus
having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus
My solution:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
myobj.myconnection();// connection created
string mystr = "Delete table_name where water_id= '" + GridView1.DataKeys[e.RowIndex].Value + "'";// query
sqlcmd = new SqlCommand(mystr, myobj.mycon);
sqlcmd.ExecuteNonQuery();
fillgrid();
}
android:textAppearance="?android:attr/textAppearanceLarge"
seemed no effect.
android:minHeight="?android:attr/listPreferredItemHeight"
changed the height for me
In order to create a cronjob, follow these steps:
run this command : SET GLOBAL event_scheduler = ON;
If ERROR 1229 (HY000): Variable 'event_scheduler' is a GLOBAL variable and should be set with SET GLOBAL: mportant
It is possible to set the Event Scheduler to DISABLED only at server startup. If event_scheduler is ON or OFF, you cannot set it to DISABLED at runtime. Also, if the Event Scheduler is set to DISABLED at startup, you cannot change the value of event_scheduler at runtime.
To disable the event scheduler, use one of the following two methods:
As a command-line option when starting the server:
--event-scheduler=DISABLED
In the server configuration file (my.cnf, or my.ini on Windows systems): include the line where it will be read by the server (for example, in a [mysqld] section):
event_scheduler=DISABLED
Read MySQL documentation for more information.
DROP EVENT IF EXISTS EVENT_NAME;
CREATE EVENT EVENT_NAME
ON SCHEDULE EVERY 10 SECOND/minute/hour
DO
CALL PROCEDURE_NAME();
Guava has a method similar to the one from Commons IOUtils that Willi aus Rohr mentioned:
import com.google.common.base.Charsets;
import com.google.common.io.Files;
// ...
String text = Files.toString(new File(path), Charsets.UTF_8);
EDIT by PiggyPiglet
Files#toString
is deprecated, and due for removal Octobor 2019. Instead use
Files.asCharSource(new File(path), StandardCharsets.UTF_8).read();
EDIT by Oscar Reyes
This is the (simplified) underlying code on the cited library:
InputStream in = new FileInputStream(file);
byte[] b = new byte[file.length()];
int len = b.length;
int total = 0;
while (total < len) {
int result = in.read(b, total, len - total);
if (result == -1) {
break;
}
total += result;
}
return new String( b , Charsets.UTF_8 );
Edit (by Jonik): The above doesn't match the source code of recent Guava versions. For the current source, see the classes Files, CharStreams, ByteSource and CharSource in com.google.common.io package.
Make sure:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
is the first <meta>
tag on your page, otherwise IE may not respect it.
Alternatively, the problem may be that IE is using Enterprise Mode for this website:
HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.
You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).
The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.
According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:
git tag <tagname>
, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).git tag -a <tagname>
, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.git tag -a -m <msg> <tagname>
, Git will tag the commit and annotate it with the provided message.git tag -m <msg> <tagname>
, Git will behave as if you passed the -a flag for annotation and use the provided message.Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.
I don't think you need/want the timeout.
onhover (hover) would be defined as the time period while "over" something. IMHO
onmouseover = start...
onmouseout = ...end
For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.
If you have to do a curl in php, you should use urlencode()
from PHP but individually!
strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")
If you do urlencode(strPOST)
, you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!
Example 1
$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B
Example 2
$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B
Example 1 is the good way to prepare string for POST in curl
Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!
You should look at the with
binding, as well as controlsDescendantBindings
http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
Several easy-to-use form serializers with good documentation.
In order of Github stars,
Use for
, something along the lines of:
set content=
for /f "delims=" %%i in ('filename') do set content=%content% %%i
Maybe you’ll have to do setlocal enabledelayedexpansion
and/or use !content!
rather than %content%
. I can’t test, as I don’t have any MS Windows nearby (and I wish you the same :-).
The best batch-file-black-magic-reference I know of is at http://www.rsdn.ru/article/winshell/batanyca.xml. If you don’t know Russian, you still could make some use of the code snippets provided.
FormHelper::select(string $fieldName, array $options,
array $attributes)
$attributes['value']
to set which value should be selected default
<?php echo $this->Form->select('status', $list, array(
'empty' => false,
'value' => 1)
); ?>
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}
I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...
Edit: I actually re-implemented the above code:
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
Check an example here.
createdb
is a command line utility which you can run from bash and not from psql. To create a database from psql, use the create database statement like so:
create database [databasename];
Note: be sure to always end your SQL statements with ;
I just used a model variable to show/hide the dialog and removed the data-dismiss="alert"
Example:
<div data-ng-show="vm.result == 'error'" class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-ng-click="vm.result = null" aria-hidden="true">×</button>
<strong>Error ! </strong>{{vm.exception}}
</div>
works for me and stops the need to go out to jquery
Rails drop down using has_many association for article and category:
has_many :articles
belongs_to :category
<%= form.select :category_id,Category.all.pluck(:name,:id),{prompt:'select'},{class: "form-control"}%>
just change the path:
"c:\program files\android\sdk" to "c:\progra~1\android\sdk"
or
"c:\program files (x86)\android\sdk" to "c:\progra~2\android\sdk"
note that the paths should not contain spaces.
For anyone else who gets caught, ensure setCustomAnimations is called before the call to replace/add when building the transaction.
Not answering the question directly, but it might help someone else.
I have a column called Volume
, having both -
(invalid/NaN) and numbers formatted with ,
df['Volume'] = df['Volume'].astype('str')
df['Volume'] = df['Volume'].str.replace(',', '')
df['Volume'] = pd.to_numeric(df['Volume'], errors='coerce')
Casting to string is required for it to apply to str.replace
Take selected value:
worksheet name = ordls
form control list box name = DEPDB1
selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)
No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a finite automaton.
You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input).
There are many parser generators avialable, for instance ANTLR for Java. Finding an existing grammar for Java (or C) is also not difficult.
For more background: Automata Theory at Wikipedia
Here is a working example for kramdown following @Yarin's answer.
A simple paragraph with a class attribute.
{:.yourClass}
Reference: https://kramdown.gettalong.org/syntax.html#inline-attribute-lists
you may need to try
pip install --upgrade setuptools
you may also need to install Visual Studio 2015, and remember to choose to install Visual C++ 14.0 https://visualstudio.microsoft.com/visual-cpp-build-tools/
Use jQuery's
$(this).addClass('showhideExtra_up_hover');
and
$(this).addClass('showhideExtra_down_hover');
I had the same problem and solved by using Newtonsoft.Json;
var list = JsonConvert.SerializeObject(model,
Formatting.None,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
python3: Google "list comphrension" if the square bracket syntax is new to you.
with open('data.txt') as f:
lines = [ line.strip( ) for line in list(f) ]
Here's making the indexes unusable without the file:
DECLARE
CURSOR usr_idxs IS select * from user_indexes;
cur_idx usr_idxs% ROWTYPE;
v_sql VARCHAR2(1024);
BEGIN
OPEN usr_idxs;
LOOP
FETCH usr_idxs INTO cur_idx;
EXIT WHEN NOT usr_idxs%FOUND;
v_sql:= 'ALTER INDEX ' || cur_idx.index_name || ' UNUSABLE';
EXECUTE IMMEDIATE v_sql;
END LOOP;
CLOSE usr_idxs;
END;
The rebuild would be similiar.
For Console Applications, you can try this:
System.IO.Directory.GetCurrentDirectory();
Output (on my local machine):
c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug
Or you can try (there's an additional backslash in the end):
AppDomain.CurrentDomain.BaseDirectory
Output:
c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\
In my specific case, I was trying to build my node package with the node docker image so that I wouldn't have to install npm on the deployment server. It worked well until, outside out the container and on the host machine, I tried to move a file into the node_modules directory that the node docker image had created, to which I was denied permissions because it was owned by root. I realized that I could work around this by copying the directory out of the container onto the host machine. Via docker docs...
Files copied to the local machine are created with the UID:GID of the user which invoked the docker cp command.
This is the bash code I used to change ownership of the directory created by and within the docker container.
NODE_IMAGE=node_builder
docker run -v $(pwd)/build:/build -w="/build" --name $NODE_IMAGE node:6-slim npm i --production
# node_modules is owned by root, so we need to copy it out
docker cp $NODE_IMAGE:/build/node_modules build/lambda
# you might have issues trying to remove the directory "node_modules" within the shared volume "build", because it is owned by root, so remove the image and its volumes
docker rm -vf $NODE_IMAGE || true
If needed, you can remove the directory with a second docker container.
docker run -v $(pwd)/build:/build -w="/build" --name $RMR_IMAGE node:6-slim rm -r node_modules
Just define the variable as a variant, and make them equal:
Dim DirArray As Variant
DirArray = Range("a1:a5").Value
No need for the Array command.
No need for jQuery unless you target old browsers and don't want to use shims.
var yahooOnly = JSON.parse(jsondata).filter(function (entry) {
return entry.website === 'yahoo';
});
In ES2015:
const yahooOnly = JSON.parse(jsondata).filter(({website}) => website === 'yahoo');
To achieve that, I suggest you to use AngularJS Environment Plugin: https://www.npmjs.com/package/angular-environment
Here's an example:
angular.module('yourApp', ['environment']).
config(function(envServiceProvider) {
// set the domains and variables for each environment
envServiceProvider.config({
domains: {
development: ['localhost', 'dev.local'],
production: ['acme.com', 'acme.net', 'acme.org']
// anotherStage: ['domain1', 'domain2'],
// anotherStage: ['domain1', 'domain2']
},
vars: {
development: {
apiUrl: '//localhost/api',
staticUrl: '//localhost/static'
// antoherCustomVar: 'lorem',
// antoherCustomVar: 'ipsum'
},
production: {
apiUrl: '//api.acme.com/v2',
staticUrl: '//static.acme.com'
// antoherCustomVar: 'lorem',
// antoherCustomVar: 'ipsum'
}
// anotherStage: {
// customVar: 'lorem',
// customVar: 'ipsum'
// }
}
});
// run the environment check, so the comprobation is made
// before controllers and services are built
envServiceProvider.check();
});
And then, you can call the variables from your controllers such as this:
envService.read('apiUrl');
Hope it helps.
You can use array_merge($array1, $array2) to merge the associative array. Example:
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
Output:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
if it doesnt exist load default image or handle error
$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
if (status == "error")
$(this).attr('src', 'images/DEFAULT.JPG');
else
$(this).attr('src', imgurl);
});
msiexec.exe /x "{588A9A11-1E20-4B91-8817-2D36ACBBBF9F}" /q
Gosh, NO!!! You're asking for a world of hurt if you store formatted dates in SQL Server. Always store your dates and times and one of the SQL Server "date/time" datatypes (DATETIME, DATE, TIME, DATETIME2, whatever). Let the front end code resolve the method of display and only store formatted dates when you're building a staging table to build a file from. If you absolutely must display ISO date/time formats from SQL Server, only do it at display time. I can't emphasize enough... do NOT store formatted dates/times in SQL Server.
{Edit}. The reasons for this are many but the most obvious are that, even with a nice ISO format (which is sortable), all future date calculations and searches (search for all rows in a given month, for example) will require at least an implicit conversion (which takes extra time) and if the stored formatted date isn't the format that you currently need, you'll need to first convert it to a date and then to the format you want.
The same holds true for front end code. If you store a formatted date (which is text), it requires the same gyrations to display the local date format defined either by windows or the app.
My recommendation is to always store the date/time as a DATETIME or other temporal datatype and only format the date at display time.
Your JSON is perfectly valid. Try using these JSON classes to parse it. http://json.org/java/
Although the other answers solve the OP's problem, they are all overkill and do not explain why he or she is experiencing this issue.
The key is this line, "I close putty, then I cannot reach the address"
When you are logged into your remote host on Putty you have started an SSH linux process and all commands typed from that SSH session will be executed as children of said process.
Your problem is that when you close Putty you are exiting the SSH session which kills that process and any active child processes. When you close putty you inadvertently kill your server because you ran it in the foreground. To avoid this behavior run the server in the background by appending & to your command:
node /srv/www/MyUserAccount/server/server.js &
The problem here is a lack of linux knowledge and not a question about node. For some more info check out: http://linuxconfig.org/understanding-foreground-and-background-linux-processes
UPDATE:
As others have mentioned, the node server may still die when exiting the terminal. A common gotcha I have come across is that even though the node process is running in bg, it's stdout and stderr is still pointed at the terminal. This means that if the node server writes to console.log or console.error it will receive a broken pipe error and crash. This can be avoided by piping the output of your process:
node /srv/www/MyUserAccount/server/server.js > stdout.txt 2> stderr.txt &
If the problem persists then you should look into things like tmux or nohup, which are still more robust than node specific solutions, because they can be used to run all types of processes (databases, logging services, other languages).
A common mistake that could cause the server to exit is that after running the nohup node your_path/server.js &
you simply close the Putty terminal by a simple click. You should use exit
command instead, then your node server will be up and running.
If you want to write connection string in Web.config then write under given sting
<connectionStrings>
<add name="Conn" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"
providerName="System.Data.SqlClient" />
</connectionStrings>
OR
you right in aspx.cs file like
SqlConnection conn = new SqlConnection("Data Source=12.16.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com");
Hi I have same issue tried almost everything. So, finally i resolved after 6 hour long struggle by debugging everything line by line.
classpath 'com.google.gms:google-services:3.0.0'
Google-services 3.0 Doesn't support firebase with Studio 3.0 with playServiceVersion: 11.6.0 or less.
implementation "com.google.firebase:firebase-messaging:$rootProject.ext.playServiceVersion"
implementation "com.google.firebase:firebase-core:$rootProject.ext.playServiceVersion"
implementation "com.firebase:firebase-jobdispatcher-with-gcm-dep:$rootProject.ext.jobdispatcherVersion"
Solution :
I have change google services to
classpath 'com.google.gms:google-services:3.1.1'
And it support firebase services.
Hopefully somebody save his/her time.
I have created main.css file and included all css files in it.
We can include only one main.css file
@import url('style.css');
@import url('platforms.css');
Quote from Android Docs:
If you need to format your strings using
String.format(String, Object...)
, then you can do so by putting your format arguments in the string resource. For example, with the following resource:<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments:
%1$s
is a string and%2$d
is a decimal number. You can format the string with arguments from your application like this:Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
So much answers and all them good, but I will suggest my own, maybe it will be usefull for somebody.
We have HTML in the template:
<div class="listing-item-excerpt" id="listing-item-excerpt-<?= $task['id'] ?>">
<?= mb_substr($txt, 0, 150) ?><span class="complete_txt"><?= mb_substr($txt, 150) ?></span>
<a href="javascript: show_more_less(<?= $task['id'] ?>);void(0);" class="more_less_btn" data-more-txt="<?= __('... show more') ?>" data-less-txt=" <?= __('show less') ?>" data-state="0"><?= __('... show more') ?></a>
</div>
JS function for toggling which:
function show_more_less(task_id) {
var btn = jQuery('#listing-item-excerpt-' + task_id).find('.more_less_btn');
var txt_container = jQuery('#listing-item-excerpt-' + task_id).find('.complete_txt');
var state = parseInt(jQuery(btn).data('state'), 10);
if (state === 0) {
jQuery(txt_container).show();
jQuery(btn).text(jQuery(btn).data('less-txt'));
jQuery(btn).data('state', 1);
} else {
jQuery(txt_container).hide();
jQuery(btn).text(jQuery(btn).data('more-txt'));
jQuery(btn).data('state', 0);
}
}
> Required JS for jquery form validation
> ## jquery-1.7.1.min.js ##
> ## jquery.validate.min.js ##
> ## jquery.form.js ##
$("form#data").validate({
rules: {
first: {
required: true,
},
middle: {
required: true,
},
image: {
required: true,
},
},
messages: {
first: {
required: "Please enter first",
},
middle: {
required: "Please enter middle",
},
image: {
required: "Please Select logo",
},
},
submitHandler: function(form) {
var formData = new FormData($("#image")[0]);
$(form).ajaxSubmit({
url:"action.php",
type:"post",
success: function(data,status){
alert(data);
}
});
}
});
Check this thread out: read and write image file.
Also, have a look at this other question at Stackoverflow.
Can you try this,
var ajaxSubmit = function(formE1) {
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
async: "false",
url: "checkpass.php",
data: "password="+password,
success: function(html) {
var arr=$.parseJSON(html);
if(arr == "Successful")
{
**$("form[name='form']").submit();**
return true;
}
else
{ return false;
}
}
});
**return false;**
}
Either increase the ram size allocated while doing HAX installation , so as to fit exactly or a bit more higher space than the ram size of the emulator which you want to launch in "Intel x86 Emulator Accelerator (HAXM) " mode,
Once you succeed with that, you can now able to view this in the console /log
Let's say you had commits:
C
B
A
git revert B
, will create a commit that undoes changes in B
.
git revert A
, will create a commit that undoes changes in A
, but will not touch changes in B
Note that if changes in B
are dependent on changes in A
, the revert of A
is not possible.
git reset --soft A
, will change the commit history and repository; staging and working directory will still be at state of C
.
git reset --mixed A
, will change the commit history, repository, and staging; working directory will still be at state of C
.
git reset --hard A
, will change the commit history, repository, staging and working directory; you will go back to the state of A
completely.
The simplest solution would be:
let str = '\t\n\r this \n \t \r is \r a \n test \t \r \n';
str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"
.replace()
with /\s+/g
regexp is changing all groups of white-spaces characters to a single space in the whole string then we .trim()
the result to remove all exceeding white-spaces before and after the text.
Are considered as white-spaces characters:
[ \f\n\r\t\v?\u00a0\u1680?\u2000?-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
You can do the following
Reload
It will add a reload button on your right hand at the bottom of the vs code.
Flexbox works.
.box{_x000D_
display: flex;_x000D_
flex-flow: row nowrap;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items:center;_x000D_
border:1px solid #e3f2fd;_x000D_
}_x000D_
.item{_x000D_
flex: 1 1 auto;_x000D_
border:1px solid #ffebee;_x000D_
}
_x000D_
<div class="box">_x000D_
<p class="item">A</p>_x000D_
<p class="item">B</p>_x000D_
<p class="item">C</p>_x000D_
</div>
_x000D_
There is actually a media query for that:
@media (hover: none) { … }
Apart from Firefox, it's fairly well supported. Safari and Chrome being the most common browsers on mobile devices, it might suffice untill greater adoption.
You need to import the module datetime
first:
>>> import datetime
After that it works:
>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
Try this: Character.toString(aChar)
or just this: aChar + ""
Removing the restrictions (to None) worked for me.
You can either make your variable non static
public final String TTT = (String) getText(R.string.TTT);
or make the "getText" method static (if at all possible)
If you have stopped the mongod.exe service from the task manager, you need to restart the service. In my case I stopped the service from task manager and on restart it doesn't automatically started.
I got the same error with a different problem,
I used namespaces in my headers and forgot the closing bracket and got this cryptic error instead.
The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html
The method DocumentBuilder.parse(String)
takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream
or Reader
, for example a StringReader
. ... Welcome to the Java standard levels of indirections !
Basically :
DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
Note that if you read your XML from a file, you can directly give the File
object to DocumentBuilder.parse()
.
As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !
If you want the overflowing text in the div to automatically newline instead of being hidden or making a scrollbar, use the
word-wrap: break-word
property.
Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...
from operator import lt, gt
def ultimate (l,op,c=1,u=0):
try:
if op(l[c],l[u]):
u = c
c += 1
return ultimate(l,op,c,u)
except IndexError:
return l[u]
def minimum (l):
return ultimate(l,lt)
def maximum (l):
return ultimate(l,gt)
The solution is simple. Use this to set yourself apart from obvious choices.
This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow";_x000D_
var components = URI.parse(uri);_x000D_
var query = URI.parseQuery(components['query']);_x000D_
document.getElementById("result").innerHTML = "URI = " + uri;_x000D_
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];_x000D_
_x000D_
// If you look in your console, you will see that this library generates a JS array for multi-valued queries!_x000D_
console.log(query['technology']);_x000D_
console.log(query['blog']);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>_x000D_
_x000D_
<span id="result"></span>
_x000D_
Here is a Solution for Jupyter and Python3:
I droped my images in a folder named ImageTest
.
My directory is:
C:\Users\MyPcName\ImageTest\image.png
To show the image I used this expression:
![title](/notebooks/ImageTest/image.png "ShowMyImage")
Also watch out for /
and \
It means the file containing main
doesn't have access to the player
structure definition (i.e. doesn't know what it looks like).
Try including it in header.h
or make a constructor-like function that allocates it if it's to be an opaque object.
If your goal is to hide the implementation of the structure, do this in a C file that has access to the struct:
struct player *
init_player(...)
{
struct player *p = calloc(1, sizeof *p);
/* ... */
return p;
}
However if the implementation shouldn't be hidden - i.e. main
should legally say p->canPlay = 1
it would be better to put the definition of the structure in header.h
.
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
I had the same scenario in my job and here are our findings
The first thing you have to do is get the certificate and install it on your computer, you can either buy one from a Certificate Authority or generate one using makecert.
Here are the pros and cons of the 2 options
Buy a certificate
There is a cost involved on getting a certificate from a CA
For prices, see https://cheapsslsecurity.com/sslproducts/codesigningcertificate.html and https://www.digicert.com/code-signing/
Generate a certificate using Makecert
Sign the executable file
There are two ways of signing the file you want:
Using a certificate installed on the computer
signtool.exe sign /a /s MY /sha1 sha1_thumbprint_value /t http://timestamp.verisign.com/scripts/timstamp.dll /v "C:\filename.dll"
C:\filename.dll
Using a certificate file
signtool sign /tr http://timestamp.digicert.com /td sha256 /fd sha256 /f "c:\path\to\mycert.pfx" /p pfxpassword "c:\path\to\file.exe"
c:\path\to\mycert.pfx
with the password pfxpassword
to sign the file c:\path\to\file.exe
Test Your Signature
Method 1: Using signtool
Go to: Start > Run
Type CMD
> click OK
At the command prompt, enter the directory where signtool
exists
Run the following:
signtool.exe verify /pa /v "C:\filename.dll"
Method 2: Using Windows
Right-click the signed file
Select Properties
Select the Digital Signatures tab. The signature will be displayed in the Signature list section.
I hope this could help you
Sources:
Just to provide additional example of paragraph 2 in the answer. I'm not sure how critical it is for you to get three groups in one match rather than three matches using one group. E.g., in groovy:
def subject = "HELLO,THERE,WORLD"
def pat = "([A-Z]+)"
def m = (subject =~ pat)
m.eachWithIndex{ g,i ->
println "Match #$i: ${g[1]}"
}
Match #0: HELLO
Match #1: THERE
Match #2: WORLD
Its easy to switch between prefork or worker mpm in Apache 2.4 on RHEL7
Check MPM type by executing
sudo httpd -V
Server version: Apache/2.4.6 (Red Hat Enterprise Linux)
Server built: Jul 26 2017 04:45:44
Server's Module Magic Number: 20120211:24
Server loaded: APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture: 64-bit
Server MPM: prefork
threaded: no
forked: yes (variable process count)
Server compiled with....
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_SYSVSEM_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=256
-D HTTPD_ROOT="/etc/httpd"
-D SUEXEC_BIN="/usr/sbin/suexec"
-D DEFAULT_PIDLOG="/run/httpd/httpd.pid"
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
-D DEFAULT_ERRORLOG="logs/error_log"
-D AP_TYPES_CONFIG_FILE="conf/mime.types"
-D SERVER_CONFIG_FILE="conf/httpd.conf"
Now to change MPM edit following file and uncomment required MPM
/etc/httpd/conf.modules.d/00-mpm.conf
# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:
# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
#LoadModule mpm_event_module modules/mod_mpm_event.so
Spring Boot seems had changed the way of reading the VM options as it evolves. Here's some way to try when you launch an application in Intellij and want to active some profile:
Open "Edit configuration" in "Run", and in "VM options", add: -Dspring.profiles.active=local
It actually works with one project of mine with Spring Boot v2.0.3.RELEASE
and Spring v5.0.7.RELEASE
, but not with another project with Spring Boot v2.1.1.RELEASE
and Spring v5.1.3.RELEASE
.
Also, when running with Maven or JAR, people mentioned this:
mvn spring-boot:run -Drun.profiles=dev
or
java -jar -Dspring.profiles.active=dev XXX.jar
(See here: how to use Spring Boot profiles)
It is mentioned somewhere, that Spring changes the way of launching the process of applications if you specify some JVM options; it forks another process and will not pass the arg it received so this does not work. The only way to pass args to it, is:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="..."
Again, this is for Maven. https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html
What works for me for the second project, was setting the environment variable, as mentioned in some answer above: "Edit configuration" - "Environment variable", and:
SPRING_PROFILES_ACTIVE=local
Code used basic nav bootstrap
<!--MENU CENTER`enter code here` RESPONSIVE -->_x000D_
_x000D_
<div class="container-fluid">_x000D_
<div class="container logo"><h1>LOGO</h1></div>_x000D_
<nav class="navbar navbar-default menu">_x000D_
<div class="container-fluid">_x000D_
<!-- Brand and toggle get grouped for better mobile display -->_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar2"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>_x000D_
</div>_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="defaultNavbar2">_x000D_
<ul class="nav nav-justified" >_x000D_
<li><a href="#">Home</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
<li><a href="#">Link</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
<!-- /.navbar-collapse -->_x000D_
</div>_x000D_
<!-- /.container-fluid -->_x000D_
</nav>_x000D_
</div>_x000D_
<!-- END MENU-->
_x000D_
If you have output that can have errors, you may want to use an ampersand and a greater than, as follows:
my_task &> 'Users/Name/Desktop/task_output.log'
this will redirect both stderr and stdout to the log file (instead of stdout only).
<?php if(!class_exists('PDO2')) {
class PDO2 {
private static $_instance;
public static function getInstance() {
if (!isset(self::$_instance)) {
try {
self::$_instance = new PDO(
'mysql:host=***;dbname=***',
'***',
'***',
array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_general_ci",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int) $e->getCode());
}
}
return self::$_instance;
}
public static function closeInstance() {
return self::$_instance = null;
}
}
}
$req = PDO2::getInstance()->prepare('SELECT * FROM table');
$req->execute();
$count = $req->rowCount();
$results = $req->fetchAll(PDO::FETCH_ASSOC);
$req->closeCursor();
// Do other requests maybe
// And close connection
PDO2::closeInstance();
// print output
Full example, with custom class PDO2.
Update 2013-01-07: If you want to see a good mix of component-based game engine with the (in my opinion) superior approach of reactive programming take a look at the V-Play engine. It very well integrates QTs QML property binding functionality.
We did some research on CBSE in games at our university and I collected some material over the years:
CBSE in games literature:
A very good and clean example of a component-based game-engine in C# is the Elephant game framework.
If you really want to know what components are read: Component-based Software Engineering! They define a component as:
A software component is a software element that conforms to a component model and can be independently deployed and composed without modification according to a composition standard.
A component model defines specific interaction and composition standards. A component model implementation is the dedicated set of executable software elements required to support the execution of components that conform to the model.
A software component infrastructure is a set of interacting software components designed to ensure that a software system or subsystem constructed using those components and interfaces will satisfy clearly defined performance specifications.
My opinions after 2 years of experience with CBSE in games thought are that object-oriented programming is simply a dead-end. Remember my warning as you watch your components become smaller and smaller, and more like functions packed in components with a lot of useless overhead. Use functional-reactive programming instead. Also take a look at my fresh blog post (which lead me to this question while writing it :)) about Why I switched from component-based game engine architecture to FRP.
CBSE in games papers:
CBSE in games web-links (sorted by relevancy):
public static String readFileToString(String filePath) {
InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
try {
return IOUtils.toString(in, StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("Failed to read the xml : ", e);
}
return null;
}
We can do this in this way too.
var myMap = new Map();
myMap.set(0, 'my value1');
myMap.set(1, 'my value2');
for (var [key, value] of myMap) {
console.log(key + ' = ' + value);
}
I have put my working gmail java class up on pastebin for your review, pay special attention to the "startSessionWithTLS" method and you may be able adjust JavaMail to provide the same functionality. http://pastebin.com/VE8Mqkqp
From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.
Usage looks like this:
using System.Linq;
// ...
public void My()
{
var myArray = new[] { "abc", "123", "zyx" };
List<string> myList = myArray.ToList();
}
PS. There's also ToArray()
method that works in other way.
The other Answers are correct, especially this one by Stephen C.
Generating a UUID value within Java is limited to Version 4 (random) because of security concerns.
If you want other versions of UUIDs, one avenue is to have your Java app reach outside the JVM to generate UUIDs by calling on:
uuidgen
found in Mac OS X, BSD, and Linux.uuid-ossp
extension often bundled with Postgres. That extension can generates Versions 1, 3, and 4 values and additionally a couple variations:
uuid_generate_v1mc()
– generates a version 1 UUID but uses a random multicast MAC address instead of the real MAC address of the computer.uuid_generate_v5(namespace uuid, name text)
– generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method.A test subject performs actions in response to certain prompts (function calls) or other stimuli. Here are concrete examples of test situations.
A student has studied to be an Emergency Medical Technician. Go watch Ian Gallagher in Shameless Season 6, Episode 10 if you are unfamiliar with this test situation.
It is too expensive to find patients with various illnesses for test purposes. Instead we use actors. We ask the test subject (Ian) "you arrive on the scene and the patient is immobilized and unconscious what do you do first?" Ian responds "I check if the scene is safe". And the test instructor says "the scene is safe".
The instructor (and actor) are able to inject arbitrary answers to the test subject's queries.
Here, the instructor (and actor) are a mock. Medical training uses this terminology (e.g. mock code simulation) the same as computer scientists.
You are testing Yahoo, a new email service you heard about. In order to sign up, you must provide your birthday and answers to other intrusive questions.
The website requires that you are 21 years or older. So you enter in the value January 1, 1970. It meets the requirements and it saves you from the laborious process of implementing a remember-my-birthday-and-type-it-in workflow.
This date is a stub. This word usage is specific to computer science.
New Operator for lambda expression added in java 8
Lambda expression is the short way of method writing.
It is indirectly used to implement functional interface
Primary Syntax : (parameters) -> { statements; }
There are some basic rules for effective lambda expressions writting which you should konw.
You should use Measure-Object
to count things. In this case it would look like:
Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;
or if that's too long
Write-Host ( dir c:\MyFolder | mo).Count;
and in PowerShell 4.0 use the measure
alias instead of mo
Write-Host (dir c:\MyFolder | measure).Count;
String.format("%1$,.2f", myDouble);
String.format
automatically uses the default locale.
I've written a library that is up-to-date, since all the other answers are outdated:
using System;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StartServer();
Task.Delay(1000).Wait();
//Client
var client = new NamedPipeClientStream("PipesOfPiece");
client.Connect();
StreamReader reader = new StreamReader(client);
StreamWriter writer = new StreamWriter(client);
while (true)
{
string input = Console.ReadLine();
if (String.IsNullOrEmpty(input)) break;
writer.WriteLine(input);
writer.Flush();
Console.WriteLine(reader.ReadLine());
}
}
static void StartServer()
{
Task.Factory.StartNew(() =>
{
var server = new NamedPipeServerStream("PipesOfPiece");
server.WaitForConnection();
StreamReader reader = new StreamReader(server);
StreamWriter writer = new StreamWriter(server);
while (true)
{
var line = reader.ReadLine();
writer.WriteLine(String.Join("", line.Reverse()));
writer.Flush();
}
});
}
}
}
If your current min. API level is 23, you can simply use getColor()
like we are using to get string resources by getString()
:
//example
textView.setTextColor(getColor(R.color.green));
// if `Context` is not available, use with context.getColor()
You can constraint for API Levels below 23:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(getColor(R.color.green));
} else {
textView.setTextColor(getResources().getColor(R.color.green));
}
but to keep it simple, you can do like below as accepted answer:
textView.setTextColor(ContextCompat.getColor(context, R.color.green))
From Resources.
From ContextCompat AndroidX.
Additional to Vasil's answer: If you have the values given as a Scala collection, you can write
val list = List(1,2,3,4,5)
val arr = Array[Int](list:_*)
println(arr.mkString)
But usually the toArray method is more handy:
val list = List(1,2,3,4,5)
val arr = list.toArray
println(arr.mkString)
This may help someone loading select2 data from AJAX while loading data for editing (applicable for single or multi-select):
During my form/model load :
$.ajax({
type: "POST",
...
success: function (data) {
selectCountries(fixedEncodeURI(data.countries));
}
Call to select data for Select2:
var countrySelect = $('.select_country');
function selectCountries(countries)
{
if (countries) {
$.ajax({
type: 'GET',
url: "/regions/getCountries/",
data: $.param({ 'idsSelected': countries }, true),
}).then(function (data) {
// create the option and append to Select2
$.each(data, function (index, value) {
var option = new Option(value.text, value.id, true, true);
countrySelect.append(option).trigger('change');
console.log(option);
});
// manually trigger the `select2:select` event
countrySelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
}
}
and if you may be having issues with encoding you may change as your requirement:
function fixedEncodeURI(str) {
return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%22/g,"");
}
Here is a pure Java
solution actually:
public static long getFreePhysicalMemory()
{
com.sun.management.OperatingSystemMXBean bean =
(com.sun.management.OperatingSystemMXBean)
java.lang.management.ManagementFactory.getOperatingSystemMXBean();
return bean.getFreePhysicalMemorySize();
}