When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (http://jquery.com/), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.
Example of your code then becomes;
function AddtoCart() {
var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;
$row = $("#Items td:first").clone(true);
$cells = $row.find("td");
$cells.get(0).html( len );
$inp1 = $cells.get(1).find("input:first");
$inp1.attr("id", $inp1.attr("id") + len).val("");
$inp2 = $cells.get(2).find("input:first");
$inp2.attr("id", $inp2.attr("id") + len).val("");
$("#Items").append($row);
}
I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.
I would use the libraries already created specifically for js shopping carts if I were you though.
To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?
Using jQuery you can do this:
var str = '<td>1</td><td>2</td>';
$('#__TABLE__').replaceWith(str);
Or in pure javascript:
var str = '<td>1</td><td>2</td>';
var tdElement = document.getElementById('__TABLE__');
var trElement = tdElement.parentNode;
trElement.removeChild(tdElement);
trElement.innerHTML = str + trElement.innerHTML;
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
Lo-Dash, now a superset of Underscore.js, has a couple of deep clone functions:
_.cloneDeepWith(object, (val) => {if(_.isElement(val)) return val.cloneNode(true)})
the second parameter is a function that is invoked to produce the cloned value.
From an answer of the author himself:
lodash underscore
build is provided to ensure compatibility with the latest stable version of Underscore.
mysqladmin -u [username] -p password
worked for me on OS X El Capitan and MySQL 5.7.12 Community Server. Example:
$ /usr/local/mysql/bin/mysqladmin -u root -p password
Enter password:
New password:
Confirm new password:
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.
This is similar to pavan sachi's answer, but with password prompts.
My error was "#1862 - Your password has expired. To log in you must change it using a client that supports expired passwords." at phpMyAdmin login screen first time.
To send a message through TLS/SSL, you need to set Ssl of the SmtpClient class to true.
string to = "[email protected]";
string from = "[email protected]";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = @"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Send(message);
You can make the pagebreak conditional on knitting to PDF. This worked for me.
```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```
Actually the list of parameters could be accessed with $1 $2 ...
etc.
Which is exactly equivalent to:
${!i}
So, the list of parameters could be changed with set,
and ${!i}
is the correct way to access them:
$ set -- aa bb cc dd 55 ff gg hh ii jjj kkk lll
$ for ((i=0;i<=$#;i++)); do echo "$#" "$i" "${!i}"; done
12 1 aa
12 2 bb
12 3 cc
12 4 dd
12 5 55
12 6 ff
12 7 gg
12 8 hh
12 9 ii
12 10 jjj
12 11 kkk
12 12 lll
For your specific case, this could be used (without the need for arrays), to set the list of arguments when none was given:
if [ "$#" -eq 0 ]; then
set -- defaultarg1 defaultarg2
fi
which translates to this even simpler expression:
[ "$#" == "0" ] && set -- defaultarg1 defaultarg2
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getYear();
var today = (day<10?'0':'')+ day + '/' +(month<10?'0':'')+ month + '/' + year;
alert(today);
Neither clean/reset/hard checkout/rebase worked for me.
So I just removed files that git complained about*
rm /path/to/files/that/git/complained/about
*I checked if this files can be removed by checking out a brand new repo in a separate folder (files were not there)
You can do it if you wrap your text into a span like:
a {_x000D_
color: red;_x000D_
text-decoration: underline;_x000D_
}_x000D_
span {_x000D_
color: blue;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<a href="#">_x000D_
<span>Text</span>_x000D_
</a>
_x000D_
Another possible solution with JS
function onSelect(e) {
if (e.files.length > 5) {
alert("Only 5 files accepted.");
e.preventDefault();
}
}
<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("?"));
window.history.replaceState({}, document.title, clean_uri);
}
</script>
put this code on head section
I prefer to do it in code:
// Run a specific test only
//testing::GTEST_FLAG(filter) = "MyLibrary.TestReading"; // I'm testing a new feature, run something quickly
// Exclude a specific test
testing::GTEST_FLAG(filter) = "-MyLibrary.TestWriting"; // The writing test is broken, so skip it
I can either comment out both lines to run all tests, uncomment out the first line to test a single feature that I'm investigating/working on, or uncomment the second line if a test is broken but I want to test everything else.
You can also test/exclude a suite of features by using wildcards and writing a list, "MyLibrary.TestNetwork*" or "-MyLibrary.TestFileSystem*".
Visual Studio provides lots of options for conditional breakpoints:
To set any of these you
These options are as follows:
foo == 8
or some other expression.Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
It should be quite simple if you are using LogBack or SLF4J. I do it as below
//imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//Initialize logger
Logger logger = LoggerFactory.getLogger(<classname>.class);
try {
//try something
} catch(Exception e){
//Actual logging of error
logger.error("some message", e);
}
Windows: Mostly C and C++, some C#
Maybe this helps someone: You can always place the div outside the other div and then push it upwards using negative margin:
<div id="container" style="background-color: #ccc; padding-bottom: 30px;">
Hello!
</div>
<div id="copyright" style="margin-top: -20px;">
Copyright Foo web designs
</div>
AFAIK, you can't create a File
from an assets file because these are stored in the apk, that means there is no path to an assets folder.
But, you can try to create that File
using a buffer and the AssetManager
(it provides access to an application's raw asset files).
Try to do something like:
AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
Let me know about your progress.
Since version 3.3 of ggplot2, we have access to the convenient after_stat()
function.
We can do something similar to @Andrew's answer, but without using the ..
syntax:
# original example data
mydata <- c("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc")
# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
y = after_stat(count/sum(count)))) +
geom_bar() +
scale_y_continuous(labels = scales::percent)
You can find all the "computed variables" available to use in the documentation of the geom_
and stat_
functions. For example, for geom_bar()
, you can access the count
and prop
variables. (See the documentation for computed variables.)
One comment about your NULL
values: they are ignored when you create the vector (i.e. you end up with a vector of length 9, not 11). If you really want to keep track of missing data, you will have to use NA
instead (ggplot2 will put NAs at the right end of the plot):
# use NA instead of NULL
mydata <- c("aa", "bb", NA, "bb", "cc", "aa", "aa", "aa", "ee", NA, "cc")
length(mydata)
#> [1] 11
# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
y = after_stat(count/sum(count)))) +
geom_bar() +
scale_y_continuous(labels = scales::percent)
Created on 2021-02-09 by the reprex package (v1.0.0)
(Note that using chr
or fct
data will not make a difference for your example.)
just add a variable in CSHTML file
var myVariable = @"@";
and add it to your layout
<span class="my-class"><a href="@myVariale" target="_blank" >link text</a></span>
You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.F)) {
MessageBox.Show("What the Ctrl+F?");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
With dplyr 0.7.2
, you can use the very useful case_when
function :
x=read.table(
text="V1 V2 V3 V4
1 1 2 3 5
2 2 4 4 1
3 1 4 1 1
4 4 5 1 3
5 5 5 5 4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
x$V2==4 & x$V3!=1 ~ 2,
TRUE ~ 0)
Expressed with dplyr::mutate
, it gives:
x = x %>% mutate(
V5 = case_when(
V1==1 & V2!=4 ~ 1,
V2==4 & V3!=1 ~ 2,
TRUE ~ 0
)
)
Please note that NA
are not treated specially, as it can be misleading. The function will return NA
only when no condition is matched. If you put a line with TRUE ~ ...
, like I did in my example, the return value will then never be NA
.
Therefore, you have to expressively tell case_when
to put NA
where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_
. Hint: the dplyr::coalesce()
function can be really useful here sometimes!
Moreover, please note that NA
alone will usually not work, you have to put special NA
values : NA_integer_
, NA_character_
or NA_real_
.
on windows: Go to "Add or remove programs" in control panel (or open the start menu and search for "remove program")
You can also just enter the website and:
The same limitation applies here: the folder must contain at least one file inside it.
If you run into this in Xcode 10 you will have to clean before build. Or, switch to the legacy build system. File -> Workspace Settings... -> Build System: Legacy Build System.
I think you are putting one too many curly brackets. Try this
@if($user->status=='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
@else
<td>{!! $user->status !!}</td>
@endif
This worked for me
yum install mysql
It will install mysql client and then
pip install mysqlclient
In my case, I had a very similar problem. I was updating my view inside a function that was being called by a parent component, and in my parent component I forgot to use @ViewChild(NameOfMyChieldComponent). I lost at least 3 hours just for this stupid mistake. i.e: I didn't need to use any of those methods:
Please remove call to trustSrc
function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}.
Check this link http://plnkr.co/edit/caqS1jE9fpmMn5NofUve?p=preview
src
url. Have a look on the following code.
Before:
Javascript
scope.baseUrl = 'page';
scope.a = 1;
scope.b = 2;
Html
<!-- Are a and b properly escaped here? Is baseUrl controlled by user? -->
<iframe src="{{baseUrl}}?a={{a}&b={{b}}"
But for security reason they are recommending following method
Javascript
var baseUrl = "page";
scope.getIframeSrc = function() {
// One should think about their particular case and sanitize accordingly
var qs = ["a", "b"].map(function(value, name) {
return encodeURIComponent(name) + "=" +
encodeURIComponent(value);
}).join("&");
// `baseUrl` isn't exposed to a user's control, so we don't have to worry about escaping it.
return baseUrl + "?" + qs;
};
Html
<iframe src="{{getIframeSrc()}}">
because of your a and b variable is not have been initialized. You must initialized this variables for excample if you declare this variable like this int a=0; int b=0; than your code run without error.
Make sure you add both Jackson jars to classpath:
Also, you must have the following in your Spring xml file:
<mvc:annotation-driven />
What is the other application you are trying to suppress the visibility of? Have you investigated other ways of achieving your desired effect? Please do so before subjecting your users to such rogue behaviour as you are describing: what you are trying to do sound rather like what certain naughty sites do with browser windows...
At least try to adhere to the rule of Least Surprise. Users expect to be able to determine the z-order of most applications themselves. You don't know what is most important to them, so if you change anything, you should focus on pushing the other application behind everything rather than promoting your own.
This is of course trickier, since Windows doesn't have a particularly sophisticated window manager. Two approaches suggest themselves:
For Wamp 3.1.3 and Apache 2.4 I simply had to change 1 line in my httpd-vhosts.conf file.
I was then able to get to my apache server from other computers.
Give credit to this video: https://www.youtube.com/watch?v=Sy_f6wBGnjI
I've seen a couple cases where this error occurs:
!=
in a where
clause with a list of multiple or
valuessuch as:
where columnName !=('A'||'B')
This can be resolved by using
where columnName not in ('A','B')
if()
function:select if(col1,col1,col2);
in order to select the value in col1
if it exists and otherwise show the value in col2
...this throws the error; it can be resolved by using:
select if(col1!='',col1,col2);
Also a good script, although my laptop ran out of memory, but this was on a very large table
https://basitaalishan.com/2014/02/23/rebuild-all-indexes-on-all-tables-in-the-sql-server-database/
USE [<mydatabasename>]
Go
--/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
--Arguments Data Type Description
-------------- ------------ ------------
--@FillFactor [int] Specifies a percentage that indicates how full the Database Engine should make the leaf level
-- of each index page during index creation or alteration. The valid inputs for this parameter
-- must be an integer value from 1 to 100 The default is 0.
-- For more information, see http://technet.microsoft.com/en-us/library/ms177459.aspx.
--@PadIndex [varchar](3) Specifies index padding. The PAD_INDEX option is useful only when FILLFACTOR is specified,
-- because PAD_INDEX uses the percentage specified by FILLFACTOR. If the percentage specified
-- for FILLFACTOR is not large enough to allow for one row, the Database Engine internally
-- overrides the percentage to allow for the minimum. The number of rows on an intermediate
-- index page is never less than two, regardless of how low the value of fillfactor. The valid
-- inputs for this parameter are ON or OFF. The default is OFF.
-- For more information, see http://technet.microsoft.com/en-us/library/ms188783.aspx.
--@SortInTempDB [varchar](3) Specifies whether to store temporary sort results in tempdb. The valid inputs for this
-- parameter are ON or OFF. The default is OFF.
-- For more information, see http://technet.microsoft.com/en-us/library/ms188281.aspx.
--@OnlineRebuild [varchar](3) Specifies whether underlying tables and associated indexes are available for queries and data
-- modification during the index operation. The valid inputs for this parameter are ON or OFF.
-- The default is OFF.
-- Note: Online index operations are only available in Enterprise edition of Microsoft
-- SQL Server 2005 and above.
-- For more information, see http://technet.microsoft.com/en-us/library/ms191261.aspx.
--@DataCompression [varchar](4) Specifies the data compression option for the specified index, partition number, or range of
-- partitions. The options for this parameter are as follows:
-- > NONE - Index or specified partitions are not compressed.
-- > ROW - Index or specified partitions are compressed by using row compression.
-- > PAGE - Index or specified partitions are compressed by using page compression.
-- The default is NONE.
-- Note: Data compression feature is only available in Enterprise edition of Microsoft
-- SQL Server 2005 and above.
-- For more information about compression, see http://technet.microsoft.com/en-us/library/cc280449.aspx.
--@MaxDOP [int] Overrides the max degree of parallelism configuration option for the duration of the index
-- operation. The valid input for this parameter can be between 0 and 64, but should not exceed
-- number of processors available to SQL Server.
-- For more information, see http://technet.microsoft.com/en-us/library/ms189094.aspx.
--- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
-- Ensure a USE <databasename> statement has been executed first.
SET NOCOUNT ON;
DECLARE @Version [numeric] (18, 10)
,@SQLStatementID [int]
,@CurrentTSQLToExecute [nvarchar](max)
,@FillFactor [int] = 100 -- Change if needed
,@PadIndex [varchar](3) = N'OFF' -- Change if needed
,@SortInTempDB [varchar](3) = N'OFF' -- Change if needed
,@OnlineRebuild [varchar](3) = N'OFF' -- Change if needed
,@LOBCompaction [varchar](3) = N'ON' -- Change if needed
,@DataCompression [varchar](4) = N'NONE' -- Change if needed
,@MaxDOP [int] = NULL -- Change if needed
,@IncludeDataCompressionArgument [char](1);
IF OBJECT_ID(N'TempDb.dbo.#Work_To_Do') IS NOT NULL
DROP TABLE #Work_To_Do
CREATE TABLE #Work_To_Do
(
[sql_id] [int] IDENTITY(1, 1)
PRIMARY KEY ,
[tsql_text] [varchar](1024) ,
[completed] [bit]
)
SET @Version = CAST(LEFT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - 1) + N'.' + REPLACE(RIGHT(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)), LEN(CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128))) - CHARINDEX('.', CAST(SERVERPROPERTY(N'ProductVersion') AS [nvarchar](128)))), N'.', N'') AS [numeric](18, 10))
IF @DataCompression IN (N'PAGE', N'ROW', N'NONE')
AND (
@Version >= 10.0
AND SERVERPROPERTY(N'EngineEdition') = 3
)
BEGIN
SET @IncludeDataCompressionArgument = N'Y'
END
IF @IncludeDataCompressionArgument IS NULL
BEGIN
SET @IncludeDataCompressionArgument = N'N'
END
INSERT INTO #Work_To_Do ([tsql_text], [completed])
SELECT 'ALTER INDEX [' + i.[name] + '] ON' + SPACE(1) + QUOTENAME(t2.[TABLE_CATALOG]) + '.' + QUOTENAME(t2.[TABLE_SCHEMA]) + '.' + QUOTENAME(t2.[TABLE_NAME]) + SPACE(1) + 'REBUILD WITH (' + SPACE(1) + + CASE
WHEN @PadIndex IS NULL
THEN 'PAD_INDEX =' + SPACE(1) + CASE i.[is_padded]
WHEN 1
THEN 'ON'
WHEN 0
THEN 'OFF'
END
ELSE 'PAD_INDEX =' + SPACE(1) + @PadIndex
END + CASE
WHEN @FillFactor IS NULL
THEN ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), REPLACE(i.[fill_factor], 0, 100))
ELSE ', FILLFACTOR =' + SPACE(1) + CONVERT([varchar](3), @FillFactor)
END + CASE
WHEN @SortInTempDB IS NULL
THEN ''
ELSE ', SORT_IN_TEMPDB =' + SPACE(1) + @SortInTempDB
END + CASE
WHEN @OnlineRebuild IS NULL
THEN ''
ELSE ', ONLINE =' + SPACE(1) + @OnlineRebuild
END + ', STATISTICS_NORECOMPUTE =' + SPACE(1) + CASE st.[no_recompute]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + ', ALLOW_ROW_LOCKS =' + SPACE(1) + CASE i.[allow_row_locks]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + ', ALLOW_PAGE_LOCKS =' + SPACE(1) + CASE i.[allow_page_locks]
WHEN 0
THEN 'OFF'
WHEN 1
THEN 'ON'
END + CASE
WHEN @IncludeDataCompressionArgument = N'Y'
THEN CASE
WHEN @DataCompression IS NULL
THEN ''
ELSE ', DATA_COMPRESSION =' + SPACE(1) + @DataCompression
END
ELSE ''
END + CASE
WHEN @MaxDop IS NULL
THEN ''
ELSE ', MAXDOP =' + SPACE(1) + CONVERT([varchar](2), @MaxDOP)
END + SPACE(1) + ')'
,0
FROM [sys].[tables] t1
INNER JOIN [sys].[indexes] i ON t1.[object_id] = i.[object_id]
AND i.[index_id] > 0
AND i.[type] IN (1, 2)
INNER JOIN [INFORMATION_SCHEMA].[TABLES] t2 ON t1.[name] = t2.[TABLE_NAME]
AND t2.[TABLE_TYPE] = 'BASE TABLE'
INNER JOIN [sys].[stats] AS st WITH (NOLOCK) ON st.[object_id] = t1.[object_id]
AND st.[name] = i.[name]
SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0
WHILE @SQLStatementID IS NOT NULL
BEGIN
SELECT @CurrentTSQLToExecute = [tsql_text]
FROM #Work_To_Do
WHERE [sql_id] = @SQLStatementID
PRINT @CurrentTSQLToExecute
EXEC [sys].[sp_executesql] @CurrentTSQLToExecute
UPDATE #Work_To_Do
SET [completed] = 1
WHERE [sql_id] = @SQLStatementID
SELECT @SQLStatementID = MIN([sql_id])
FROM #Work_To_Do
WHERE [completed] = 0
END
char[] result = "Stack Me 123 Heppa1 oeu".toCharArray();
This will give you the current screen based on the top left of the window just call this.CurrentScreen() to get info on the current screen.
using System.Windows;
using System.Windows.Forms;
namespace Common.Helpers
{
public static class WindowHelpers
{
public static Screen CurrentScreen(this Window window)
{
return Screen.FromPoint(new System.Drawing.Point((int)window.Left,(int)window.Top));
}
}
}
Code for Future Date only with disable today's date.
var d = new Date();
$("#delivdate").datepicker({
showOn: "button",
buttonImage: base_url+"images/cal.png",
minDate:new Date(d.setDate(d.getDate() + 1)),
buttonImageOnly: true
});
$('.ui-datepicker-trigger').attr('title','');
I had this problem: My Web API 2 project on .NET 4.7.2 was working as expected, then I changed the project properties to use a Specific Page path under the Web tab. When I ran it every time since, it was giving me a 404 error - it didn't even hit the controller.
Solution: I found the .vs hidden folder in my parent directory of my VS solution file (sometimes the same directory), and deleted it. When I opened my VS solution once more, cleaned it, and rebuilt it with the Rebuild option, it ran again. There was a problem with the cached files created by Visual Studio. When these were deleted, and the solution was rebuilt, the files were recreated.
FROM openjdk:8-jdk-alpine
RUN apk update && apk add wget openssl lsof procps curl
RUN apk update
RUN mkdir -p /apps/agent
RUN mkdir -p /apps/lib
ADD ./app/agent /apps/agent
ADD ./app/lib /apps/lib
ADD ./app/* /apps/app/
RUN ls -lrt /apps/app/
CMD sh /apps/app/launch.sh
by using DockerFile, I'm copying agent and lib directories to /apps/agent,/apps/lib directories and bunch of files to target.
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
If you want a pair (not supposedly key-value pair) just to hold two generic data together neither of the solutions above really handy since first (or so called Key) cannot be changed (neither in Apache Commons Lang's Pair nor in AbstractMap.SimpleEntry). They have thier own reasons, but still you may need to be able to change both of the components. Here is a Pair class in which both elements can be set
public class Pair<First, Second> {
private First first;
private Second second;
public Pair(First first, Second second) {
this.first = first;
this.second = second;
}
public void setFirst(First first) {
this.first = first;
}
public void setSecond(Second second) {
this.second = second;
}
public First getFirst() {
return first;
}
public Second getSecond() {
return second;
}
public void set(First first, Second second) {
setFirst(first);
setSecond(second);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
if (second != null ? !second.equals(pair.second) : pair.second != null) return false;
return true;
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
}
To get the "today" value in SQL:
convert(date, GETDATE())
To get "yesterday":
DATEADD(day, -1, convert(date, GETDATE()))
To get "today minus X days": change the -1 into -X.
So for all yesterday's rows, you get:
select * from tablename
where date >= DATEADD(day, -1, convert(date, GETDATE()))
and date < convert(date, GETDATE())
If you are using Python2.5 or older try
from operator import mul
def factorial(n):
return reduce(mul, range(1,n+1))
for newer Python, there is factorial in the math module as given in other answers here
Solution is very simple.
1 Add Internet permission in Androidmanifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
[2] Change your httpd.config file
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
TO
Order Deny,Allow
Allow from all
Allow from 127.0.0.1
And restart your server.
[3] And most impotent step. MAKE YOUR NETWORK AS YOUR HOME NETWORK
Go to Control Panel > Network and Internet > Network and Sharing Center
Click on your Network and select HOME NETWORK
document.getElementById("placehere").appendChild(elem);
not
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
elem.src = 'images/hydrangeas.jpg';
I have just tried to install that extension on my dev server.
First, make sure that the extension is correctly enabled. Your phpinfo()
output doesn't seem complete.
If it is indeed installed properly, your phpinfo()
should have a section that looks like this:
If you do not get that section in your phpinfo()
. Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.
Finally, check your extension_dir
setting. By default it's this: extension_dir = "ext"
, for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext"
.
===========================================================================
EDIT given new info:
You are using the wrong function. mssql_connect()
is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect()
, for the API for the microsoft driver, look at SQLSRV_Help.chm
which should be extracted to your ext
directory when you extracted the extension.
This is what worked best for me:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"../"));
Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end.
Surrounding it with Path.GetFullPath()
will give you the absolute path, making it usable.
Why not the following?
//How to check if a string begins with another string
$haystack = "valuehaystack";
$needle = "value";
if (strpos($haystack, $needle) === 0){
echo "Found " . $needle . " at the beginning of " . $haystack . "!";
}
Output:
Found value at the beginning of valuehaystack!
Keep in mind, strpos
will return false if the needle was not found in the haystack, and will return 0 if, and only if, needle was found at index 0 (AKA the beginning).
And here's endsWith:
$haystack = "valuehaystack";
$needle = "haystack";
//If index of the needle plus the length of the needle is the same length as the entire haystack.
if (strpos($haystack, $needle) + strlen($needle) === strlen($haystack)){
echo "Found " . $needle . " at the end of " . $haystack . "!";
}
In this scenario there is no need for a function startsWith() as
(strpos($stringToSearch, $doesItStartWithThis) === 0)
will return true or false accurately.
It seems odd it's this simple with all the wild functions running rampant here.
Datetime is a datatype.
Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.
For more information:
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
This works for me! be careful with the new java versions because they cause error, check that you have everything installed and in your specific directory,
I did not use openJDK
export JAVA_HOME="/usr/lib/jvm/java-8-jdk" \
&& export PATH=$JAVA_HOME/bin:$PATH \
&& export ANDROID_HOME=$HOME/Android/Sdk \
&& export PATH=${PATH}:${ANDROID_HOME}/tools \
&& export PATH=${PATH}:${ANDROID_HOME}/platform-tools \
&& export GRADLE_HOME=/usr/share/java/gradle/bin/gradle \
export PATH=$PATH:$GRADLE_HOME/bin
Linux 4.14.39-1-MANJARO #1 SMP PREEMPT Wed May 2 19:03:39 UTC 2018 x86_64 GNU/Linux
While this only works for scalar arrays (see note below), it is short:
array1.length === array2.length && array1.every(function(value, index) { return value === array2[index]})
Rr, in ECMAScript 6 / CoffeeScript / TypeScript with Arrow Functions:
array1.length === array2.length && array1.every((value, index) => value === array2[index])
(Note: 'scalar' here means values that can be compared directly using ===
. So: numbers, strings, objects by reference, functions by reference. See the MDN reference for more info about the comparison operators).
UPDATE
From what I read from the comments, sorting the array and comparing may give accurate result:
const array2Sorted = array2.slice().sort();
array1.length === array2.length && array1.slice().sort().every(function(value, index) {
return value === array2Sorted[index];
});
Eg:
array1 = [2,3,1,4];
array2 = [1,2,3,4];
Then the above code would give true
You can comma-separate shadows:
box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;
I use this function for dd/mm/yyyy format :
// (new Date()).fromString("3/9/2013") : 3 of september
// (new Date()).fromString("3/9/2013", false) : 9 of march
Date.prototype.fromString = function(str, ddmmyyyy) {
var m = str.match(/(\d+)(-|\/)(\d+)(?:-|\/)(?:(\d+)\s+(\d+):(\d+)(?::(\d+))?(?:\.(\d+))?)?/);
if(m[2] == "/"){
if(ddmmyyyy === false)
return new Date(+m[4], +m[1] - 1, +m[3], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
return new Date(+m[4], +m[3] - 1, +m[1], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
}
return new Date(+m[1], +m[3] - 1, +m[4], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
}
If you already installed "MongoDB", if you accidentally exit from the MongoDB server, then "restart your system".
This method solved me...
[On Windows only]
And also another method is there:
press:
Windows + R
type:
services.msc
and click "ok", it opens "services" window, and then search for "MongoDB Server" in the list. After you find "MongoDB Server", right-click and choose "start" from the pop-up menu.
The MongoDb Server will start running.
Hope it works!!
To get activity state data stored in onCreate()
, first you have to save data in savedInstanceState by overriding SaveInstanceState(Bundle savedInstanceState)
method.
When activity destroy SaveInstanceState(Bundle savedInstanceState)
method gets called and there you save data you want to save. And you get same in onCreate()
when activity restart.(savedInstanceState wont be null since you have saved some data in it before activity get destroyed)
To remove duplicates from a single column
Sub removeDuplicate()
'removeDuplicate Macro
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A1").Select
End Sub
if you have header then use Header:=xlYes
Increase your range as per your requirement.
you can make it to 1000 like this :
ActiveSheet.Range("$A$1:$A$1000")
More info here here
Use (keyup.enter)
.
Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter
pseudo-event.
It seems to work fine in Postgresql 9.5:
SELECT current_setting('TIMEZONE');
You can use DateFormat
(java.text.*) to parse the date:
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date d = df.parse("Mon May 27 11:46:15 IST 2013")
You will have to change the locale to match your own (with this you will get 10:46:15). Then you can use the same code you have to convert it to a timestamp.
/* Didn't test it but this should work "out of the box" */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//you should edit this to fit your needs
builder.setTitle("Double Edit Text");
final EditText one = new EditText(this);
from.setHint("one");//optional
final EditText two = new EditText(this);
to.setHint("two");//optional
//in my example i use TYPE_CLASS_NUMBER for input only numbers
from.setInputType(InputType.TYPE_CLASS_NUMBER);
to.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout lay = new LinearLayout(this);
lay.setOrientation(LinearLayout.VERTICAL);
lay.addView(one);
lay.addView(two);
builder.setView(lay);
// Set up the buttons
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//get the two inputs
int i = Integer.parseInt(one.getText().toString());
int j = Integer.parseInt(two.getText().toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
or programatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Me too! http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
And tests:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
Results in:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
I've found that (at Chrome 56, OSX) the favicon state appears to be cached for the browser lifetime, so if a favicon isn't being loaded, it won't be until after restarting Chrome. It appears that it doesn't show up in the "application" tab in dev tools and isn't cleared by a hard reload or 'Clear site data'.
When I used Electron + Angular such order helped me to solve problem
<script src="./assets/js/jquery-3.3.1.min.js"></script>
<script src="./assets/js/jquery-3.3.1.slim.min.js"></script>
<script src="./assets/js/popper.min.js"></script>
<script src="./assets/js/bootstrap.min.js"></script>
// The answer that I was looking for when searching
public void Answer()
{
IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
// Assign to empty list so we can use later
IEnumerable<YourClass> second = new List<YourClass>();
if (IwantToUseSecondList)
{
second = this.GetSecondIEnumerableList();
}
IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}
Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json"
and format to .json
I had similar problem and i solved it following way.
Solve as follows:
Function prototype declarations and global variable should be in test.h file and you can not initialize global variable in header file.
Function definition and use of global variable in test.c file
if you initialize global variables in header it will have following error
multiple definition of `_ test'| obj\Debug\main.o:path\test.c|1|first defined here|
Just declarations of global variables in Header file no initialization should work.
Hope it helps
Cheers
Your main problem is you create new figures in your loop, so each vector gets drawn on a different figure. Here's what I came up with, let me know if it's still not what you expect:
CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
for i,l in enumerate(range(0,cols)):
xs = [0,M[i,0]]
ys = [0,M[i,1]]
plt.plot(xs,ys)
plt.plot(0,0,'ok') #<-- plot a black point at the origin
plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.legend(['V'+str(i+1) for i in range(cols)]) #<-- give a legend
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
OUTPUT:
EDIT CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array([[1,1],[-2,2],[4,-7]])
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
colors = ['b','r','k']
for i,l in enumerate(range(0,cols)):
plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.05,head_length=0.1,color = colors[i])
plt.plot(0,0,'ok') #<-- plot a black point at the origin
plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
I found the following command to run from command line:
vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt
FormBorderStyle = FormBorderStyle.Sizable;
TopMost = false;
WindowState = FormWindowState.Normal;
THIS CODE MAKE YOUR WINDOWS FULL SCREEN THIS WILL ALSO COVER WHOLE SCREEN
A form is not allowed to be a child element of a table
, tbody
or tr
. Attempting to put one there will tend to cause the browser to move the form to it appears after the table (while leaving its contents — table rows, table cells, inputs, etc — behind).
You can have an entire table inside a form. You can have a form inside a table cell. You cannot have part of a table inside a form.
Use one form around the entire table. Then either use the clicked submit button to determine which row to process (to be quick) or process every row (allowing bulk updates).
HTML 5 introduces the form
attribute. This allows you to provide one form per row outside the table and then associate all the form control in a given row with one of those forms using its id
.
Switching to the smartphone network & disabling the web security tool installed on my computer solved the problem.
Many hosts will not allow you to create your own database through PHP, but you seem to have solved that.
Once the DB has been created, you can manipulate and populate it simply:
mysql_connect("localhost");
mysql_query("SOURCE file.sql");
If you are using non-parallel direct path loads then consider and benchmark not dropping the indexes at all, particularly if the indexes only cover a minority of the columns. Oracle has a mechanism for efficient maintenance of indexes on direct path loads.
Otherwise, I'd also advise making the indexes unusable instead of dropping them. Less chance of accidentally not recreating an index.
You are looking for the break statement.
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
Use WebElement.send_keys
method to simulate key typing.
name
in the code (Username
, Password
) does not match actual name
of the elements (username
, password
).
username = browser.find_element_by_name('username')
username.send_keys('user1')
password = browser.find_element_by_name('password')
password.send_keys('secret')
form = browser.find_element_by_id('loginForm')
form.submit()
# OR browser.find_element_by_id('submit').click()
Since you are in a controller, the action method is given a Request
parameter.
You can access all POST data with $request->request->all();
.
This returns a key-value pair array.
When using GET requests you access data using $request->query->all();
holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...
#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);
int main()
{
int i;
float maxSize=3, size;
float lettergrades[5], numericgrades[100], average;
size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}
int getgrades(float a[])
{
int i, max=3;
for (i = 0; i <max; i++)
{
//ask use for input
cout << "\nPlease Enter grade " << i+1 << " : ";
cin >> a[i];
//makes sure that user enters a vlue between 0 and 100
if(a[i] < 0 || a[i] >100)
{
cout << "Wrong input. Please
enter a value between 0 and 100 only." << endl;
cout << "\nPlease Reenter grade " << i+1 << " : ";
cin >> a[i];
return i;
}
}
}
int getaverage(float a[], float n)
{
int i;
float sum = 0;
if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int printResults(float a[], float n, float average, float letters[])
{
int i;
cout << "Index Number | input |
array values address in memory " << endl;
for (i = 0; i < 3; i++)
{
cout <<" "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;
}
At first, you must specify your path, the path that your *.csv
files are in there
path = 'f:\project\dataset'
You can change it based on your system.
then,
use dir
function :
files = dir (strcat(path,'\*.csv'))
L = length (files);
for i=1:L
image{i}=csvread(strcat(path,'\',file(i).name));
% process the image in here
end
pwd
also can be used.
One example in order to understand, where the usage of ZEROFILL
might be interesting:
In Germany, we have 5 digit zipcodes. However, those Codes may start with a Zero, so 80337
is a valid zipcode for munic, 01067
is a zipcode of Berlin.
As you see, any German citizen expects the zipcodes to be displayed as a 5 digit code, so 1067
looks strange.
In order to store those data, you could use a VARCHAR(5)
or INT(5) ZEROFILL
whereas the zerofilled integer has two big advantages:
1067
, you still get 01067
backMaybe this example helps understanding the use of ZEROFILL
.
Procedural elements like loops are not part of the SQL language and can only be used inside the body of a procedural language function, procedure (Postgres 11 or later) or a DO
statement, where such additional elements are defined by the respective procedural language. The default is PL/pgSQL, but there are others.
Example with plpgsql:
DO
$do$
BEGIN
FOR i IN 1..25 LOOP
INSERT INTO playtime.meta_random_sample
(col_i, col_id) -- declare target columns!
SELECT i, id
FROM tbl
ORDER BY random()
LIMIT 15000;
END LOOP;
END
$do$;
For many tasks that can be solved with a loop, there is a shorter and faster set-based solution around the corner. Pure SQL equivalent for your example:
INSERT INTO playtime.meta_random_sample (col_i, col_id)
SELECT t.*
FROM generate_series(1,25) i
CROSS JOIN LATERAL (
SELECT i, id
FROM tbl
ORDER BY random()
LIMIT 15000
) t;
About generate_series()
:
About optimizing performance of random selections:
An activity populates the ActionBar in its onCreateOptionsMenu()
method.
Instead of using setcustomview()
, just override onCreateOptionsMenu
like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
If an actions in the ActionBar is selected, the onOptionsItemSelected()
method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
break;
case R.id.menuitem2:
Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
When passing parameters through the URL you're able to retrieve the values as GET parameters.
Use this:
$variable = $_GET['param_name'];
//Or as you have it
$ppc = $_GET['ppc'];
It is safer to check for the variable first though:
if (isset($_GET['ppc'])) {
$ppc = $_GET['ppc'];
} else {
//Handle the case where there is no parameter
}
Here's a bit of reading on GET/POST params you should look at: http://php.net/manual/en/reserved.variables.get.php
EDIT: I see this answer still gets a lot of traffic years after making it. Please read comments attached to this answer, especially input from @emc who details a WordPress function which accomplishes this goal securely.
You have two possibilities:
org.springframework.beans.factory.config.MethodInvokingFactoryBean
to invoke a static setter.In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.
public void setTheProperty(Object value) {
foo.bar.Class.STATIC_VALUE = value;
}
but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).
In the second case it would be done as follows:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Class.setTheProperty"/> <property name="arguments"> <list> <ref bean="theProperty"/> </list> </property> </bean>
On you case you will add a new setter on the Utils
class:
public static setDataBaseAttr(Properties p)
and in your context you will configure it with the approach exemplified above, more or less like:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/> <property name="arguments"> <list> <ref bean="dataBaseAttr"/> </list> </property> </bean>
This solution can be applied only if the issue is on a WordPress installation!
If you don't have FTP access or too lazy to edit files,
You can use Increase Maximum Upload File Size plugin to increase the maximum upload file size.
Is your server single-threaded? If so, what polling / multiplexing function are you using?
Using select() does not work beyond the hard-coded maximum file descriptor limit set at compile-time, which is hopeless (normally 256, or a few more).
poll() is better but you will end up with the scalability problem with a large number of FDs repopulating the set each time around the loop.
epoll() should work well up to some other limit which you hit.
10k connections should be easy enough to achieve. Use a recent(ish) 2.6 kernel.
How many client machines did you use? Are you sure you didn't hit a client-side limit?
What I do usually when I commit and push (if anyone pushed his commit this solve the problem):
git reset --hard HEAD~1
git push -f origin
hope this help
Note: The first() method doesn't throw an exception as described in the original question. If you're getting this kind of exception, there is another error in your code.
The correct way to user first() and check for a result:
$user = User::where('mobile', Input::get('mobile'))->first(); // model or null
if (!$user) {
// Do stuff if it doesn't exist.
}
Other techniques (not recommended, unnecessary overhead):
$user = User::where('mobile', Input::get('mobile'))->get();
if (!$user->isEmpty()){
$firstUser = $user->first()
}
or
try {
$user = User::where('mobile', Input::get('mobile'))->firstOrFail();
// Do stuff when user exists.
} catch (ErrorException $e) {
// Do stuff if it doesn't exist.
}
or
// Use either one of the below.
$users = User::where('mobile', Input::get('mobile'))->get(); //Collection
if (count($users)){
// Use the collection, to get the first item use $users->first().
// Use the model if you used ->first();
}
Each one is a different way to get your required result.
The following selects all descendant elements and disables them:
$("#dcacl").find("*").prop("disabled", true);
But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:
$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);
To re-enable you just set "disabled" to false.
I want to Disable them at loading the page and then by a click i can enable them
OK, so put the above code in a document ready handler, and setup an appropriate click handler:
$(document).ready(function() {
var $dcac1kids = $("#dcac1").find(":input");
$dcac1kids.prop("disabled",true);
// not sure what you want to click on to re-enable
$("selector for whatever you want to click").one("click",function() {
$dcac1kids.prop("disabled",false);
}
}
I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one()
since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one()
to .click()
if appropriate.
Try using the passive
command before using ls
.
From FTP client, to check if the FTP server supports passive mode, after login, type quote PASV
.
Following are connection examples to a vsftpd server with passive mode on and off
vsftpd
with pasv_enable=NO
:
# ftp localhost
Connected to localhost.localdomain.
220 (vsFTPd 2.3.5)
Name (localhost:john): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quote PASV
550 Permission denied.
ftp>
vsftpd
with pasv_enable=YES
:
# ftp localhost
Connected to localhost.localdomain.
220 (vsFTPd 2.3.5)
Name (localhost:john): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quote PASV
227 Entering Passive Mode (127,0,0,1,173,104).
ftp>
This blog explains your problem neatly Async Best Practices.
The gist of it being you shouldn't use void as return for an async method, unless it's an async event handler, this is bad practice because it doesn't allow exceptions to be caught ;-).
Best practice would be to change the return type to Task. Also, try to code async all the way trough, make every async method call and be called from async methods. Except for a Main method in a console, which can't be async (before C# 7.1).
You will run into deadlocks with GUI and ASP.NET applications if you ignore this best practice. The deadlock occurs because these applications runs on a context that allows only one thread and won't relinquish it to the async thread. This means the GUI waits synchronously for a return, while the async method waits for the context: deadlock.
This behaviour won't happen in a console application, because it runs on context with a thread pool. The async method will return on another thread which will be scheduled. This is why a test console app will work, but the same calls will deadlock in other applications...
In my case, the error was triggered by duplicating an import of a component in the module.
it was the update version of Codemwnci. his code is quite fine and works great except the error message. To avoid error you must change the condition statement.
// Listen for changes in the text
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
if (textField.getText().length()>0){
JOptionPane.showMessageDialog(null,
"Error: Please enter number bigger than 0", "Error Massage",
JOptionPane.ERROR_MESSAGE);
}
}
});
Using $emit and $broadcast, (as mentioned by walv in the comments above)
To fire an event upwards (from child to parent)
$scope.$emit('myTestEvent', 'Data to send');
To fire an event downwards (from parent to child)
$scope.$broadcast('myTestEvent', {
someProp: 'Sending you some data'
});
and finally to listen
$scope.$on('myTestEvent', function (event, data) {
console.log(data);
});
For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
Enjoy :)
1st Reason could be the ending tag of your application's web.xml file which could not have been closed properly.
web.xml might be ending with <web-app>
, but must end with </web-app>
2nd Reason which worked in my case could be the lib folder of your tomcat must contain the supporting jar file of your database.
ojdbc
on case of Oracle or sqljdbc
in case of SqlServer
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token) {
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld) {
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
}
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
}
The first and foremost step to diagnose is to check the Cassandra logs.
Find out the process and there will be hints in the command line parameters to tell you where the logs files are.
ps aux | grep cassandra
In my case, it was in default location /etc/cassandra/conf/cassandra.yaml
(if you installed the yum package).
Make sure three things are configured and configured the same host/ip.
listen_address
- you may leave it blank it will default to hostname/first IP binding with eth0
network cardrpc_address
- this is optional, leave blank if you want it to be same as listen_address
seeds
- this is a double quoted string of comma-separated list of IP addresses or hostnames. This was default to a hardcoded "127.0.0.1", changing it to the same as list_address
and restart of Cassandra service made it work for me.References:
HTML
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
JS
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
sendbtn.disabled = !!this.checked;
};
Odds are good you did the right stuff on the back end in getting the date, but there's nothing to indicate that you didn't take that GMT time and format it according to your machine's current locale.
final Date currentTime = new Date();
final SimpleDateFormat sdf =
new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
// Give it to me in GMT time.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT time: " + sdf.format(currentTime));
The key is to use your own DateFormat, not the system provided one. That way you can set the DateFormat's timezone to what you wish, instead of it being set to the Locale's timezone.
Spring provides an elegant org.springframework.util.StopWatch
class (spring-core
module).
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// Do something
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());
No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.
Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.
as ehogue said, put this in your CREATE TABLE
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
alternatively, if you already have the table created, use an ALTER TABLE command:
ALTER TABLE `accounts`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;
One good way to start learning these commands is using the MySQL GUI Tools, which give you a more "visual" interface for working with your database. The real benefit to that (over Access's method), is that after designing your table via the GUI, it shows you the SQL it's going to run, and hence you can learn from that.
Got mine working with
react-native run-ios --device="My’s iPhone"
And notice that your iphone name, the apostrophe s ' might be different. Mine is using this ’
Try with below code.
Like GridView in LinkButton, Label, HtmlAnchor and HtmlInputControl.
<asp:GridView ID="mainGrid" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-hover tablesorter"
OnRowDataBound="mainGrid_RowDataBound" EmptyDataText="No Data Found.">
<Columns>
<asp:TemplateField HeaderText="HeaderName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label runat="server" ID="lblName" Text=' <%# Eval("LabelName") %>'></asp:Label>
<asp:LinkButton ID="btnLink" runat="server">ButtonName</asp:LinkButton>
<a href="javascript:void(0);" id="btnAnchor" runat="server">ButtonName</a>
<input type="hidden" runat="server" id="hdnBtnInput" value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Handling RowDataBound event,
protected void mainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblName = (Label)e.Row.FindControl("lblName");
LinkButton btnLink = (LinkButton)e.Row.FindControl("btnLink");
HtmlAnchor btnAnchor = (HtmlAnchor)e.Row.FindControl("btnAnchor");
HtmlInputControl hdnBtnInput = (HtmlInputControl)e.Row.FindControl("hdnBtnInput");
}
}
Here is an example that lists all the files on my desktop. you should change the path variable to your path.
Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.
public static void main(String[] args) {
File path = new File("c:/documents and settings/Zachary/desktop");
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i]);
}
}
}
Similar to POsha's answer but this is what worked for me on ubuntu 19
sudo npm i -g ngrok --unsafe-perm=true --allow-root
From this link
For you to output foo {1, 2, 3}
you have to do something like:
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
To output a {
you use {{
and to output a }
you use }}
.
or Now, you can also use c# string interpolation like this (feature available in C# 6.0)
Escaping Brackets: String Interpolation $(""). it is new feature in C# 6.0
var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
//Output will be: foo {1, 2, 3}
Some examples of formatted output to stdout and stderr:
printf("%s", "Hello world\n"); // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n"); // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)
This worked for me:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@$!%*?&])([a-zA-Z0-9@$!%*?&]{8,})$
With ps
or similar tools you will only get the amount of memory pages allocated by that process. This number is correct, but:
does not reflect the actual amount of memory used by the application, only the amount of memory reserved for it
can be misleading if pages are shared, for example by several threads or by using dynamically linked libraries
If you really want to know what amount of memory your application actually uses, you need to run it within a profiler. For example, Valgrind can give you insights about the amount of memory used, and, more importantly, about possible memory leaks in your program. The heap profiler tool of Valgrind is called 'massif':
Massif is a heap profiler. It performs detailed heap profiling by taking regular snapshots of a program's heap. It produces a graph showing heap usage over time, including information about which parts of the program are responsible for the most memory allocations. The graph is supplemented by a text or HTML file that includes more information for determining where the most memory is being allocated. Massif runs programs about 20x slower than normal.
As explained in the Valgrind documentation, you need to run the program through Valgrind:
valgrind --tool=massif <executable> <arguments>
Massif writes a dump of memory usage snapshots (e.g. massif.out.12345
). These provide, (1) a timeline of memory usage, (2) for each snapshot, a record of where in your program memory was allocated. A great graphical tool for analyzing these files is massif-visualizer. But I found ms_print
, a simple text-based tool shipped with Valgrind, to be of great help already.
To find memory leaks, use the (default) memcheck
tool of valgrind.
You'll need to use sp_addlinkedserver
to create a server link. See the reference documentation for usage. Once the server link is established, you'll construct the query as normal, just prefixing the database name with the other server. I.E:
-- FROM DB1
SELECT *
FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
INNER JOIN [DB2].[MyDatabaseOnDB2].[dbo].[MyOtherTable] tab2
ON tab1.ID = tab2.ID
Once the link is established, you can also use OPENQUERY
to execute a SQL statement on the remote server and transfer only the data back to you. This can be a bit faster, and it will let the remote server optimize your query. If you cache the data in a temporary (or in-memory) table on DB1
in the example above, then you'll be able to query it just like joining a standard table. For example:
-- Fetch data from the other database server
SELECT *
INTO #myTempTable
FROM OPENQUERY([DB2], 'SELECT * FROM [MyDatabaseOnDB2].[dbo].[MyOtherTable]')
-- Now I can join my temp table to see the data
SELECT * FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
INNER JOIN #myTempTable tab2 ON tab1.ID = tab2.ID
Check out the documentation for OPENQUERY to see some more examples. The example above is pretty contrived. I would definitely use the first method in this specific example, but the second option using OPENQUERY
can save some time and performance if you use the query to filter out some data.
I know it's an old question, but I believe still valid even in 2018.
There is an option to Take a bug report hidden in Developer options in every android device.
NOTE: This would dump whole system log
How to enable developer options? see: https://developer.android.com/studio/debug/dev-options
What works for me:
how to read this? open bugreport-1960-01-01-hh-mm-ss.txt
you probably want to look for something like this:
------ SYSTEM LOG (logcat -v threadtime -v printable -d *:v) ------
--------- beginning of crash
06-13 14:37:36.542 19294 19294 E AndroidRuntime: FATAL EXCEPTION: main
or:
------ SYSTEM LOG (logcat -v threadtime -v printable -d *:v) ------
--------- beginning of main
For those who are struggling to get this working with IE11
HTML
<div ng-style="getBackgroundStyle(imagepath)"></div>
JS
$scope.getBackgroundStyle = function(imagepath){
return {
'background-image':'url(' + imagepath + ')'
}
}
You can use sed
for this. For example:
$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...
The -n
switch tells sed to not output each line of the file it reads (default behaviour).
The last p
after the regular expressions tells it to print lines that match the preceding expression.
The expression '/pattern1/,/pattern2/'
will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55
and the string Feb 23 14:00
.
I know this is old, but Google sent me here so I guess others will come too like me.
The answer on 2018 is the selected one here: Pycharm: "unresolved reference" error on the IDE when opening a working project
Just be aware that you can only add one Content Root
but you can add several Source Folders
. No need to touch __init__.py
files.
You can use GetCustomAttributesData()
and GetCustomAttributes()
:
var attributeData = typeof(Book).GetProperty("Name").GetCustomAttributesData();
var attributes = typeof(Book).GetProperty("Name").GetCustomAttributes(false);
If you use the database information_schema, you can use this mysql code (the where part makes the query not show tables that have a null value for rows):
SELECT TABLE_NAME, TABLE_ROWS
FROM `TABLES`
WHERE `TABLE_ROWS` >=0
To expound on Numenor's answer you can do something like, Format(Now(),"HH:mm:ss") using these custom date/time formating options
For everyone who is tempted to downvote this answer please be aware that the question was originally tagged VB and vbscript hence my answer, the VB tag was edited out leaving only the vbscript tag. The OP accepted this answer which I take to mean that it gave him the information that he needed.
All of the above is just over-complicating something very simple. An application server contains a web server, an application server just has a couple more additions/extensions to it than standard web servers. If you look at TomEE as an example:
CDI - Apache OpenWebBeans
EJB - Apache OpenEJB
JPA - Apache OpenJPA
JSF - Apache MyFaces
JSP - Apache Tomcat
JSTL - Apache Tomcat
JTA - Apache Geronimo Transaction
Servlet - Apache Tomcat
Javamail - Apache Geronimo JavaMail
Bean Validation - Apache BVal
You will see that Tomcat (Web container/server) is just another tool in the app servers arsenal. You can get JPA and the other tech in the web server as well if you want, but the application servers just package all of these things for your convenience. To be fully classified as an app server you essentially need to comply with a list of tools set forth by some standard.
You could check whether the value of your selectOneMenu
component belongs to the list of subjects.
Namely:
public void subjectSelectionChanged() {
// Cancel if subject is manually written
if (!subjectList.contains(aktNachricht.subject)) { return; }
// Write your code here in case the user selected (or wrote) an item of the list
// ....
}
Supposedly subjectList
is a collection type, like ArrayList
. Of course here your code will run in case the user writes an item of your selectOneMenu
list.
IF the table is alias t
SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM temp1 as t
I needed a solution with a retry. This code will run until the process is found and then kill it. You can set a timeout or anything if you like.
Notes:
:: Set programm you want to kill
:: Fileextension is mandatory
SET KillProg=explorer.exe
:: Set waiting time between 2 requests in seconds
SET /A "_wait=3"
:ProcessNotFound
tasklist /NH /FI "IMAGENAME eq %KillProg%" | FIND /I "%KillProg%"
IF "%ERRORLEVEL%"=="0" (
TASKKILL.EXE /F /T /IM %KillProg%
) ELSE (
timeout /t %_wait%
GOTO :ProcessNotFound
)
taskkill.bat
:
:: Get program name from argumentlist
IF NOT "%~1"=="" (
SET "KillProg=%~1"
) ELSE (
ECHO Usage: "%~nx0" ProgramToKill.exe & EXIT /B
)
:: Set waiting time between 2 requests in seconds
SET /A "_wait=3"
:ProcessNotFound
tasklist /NH /FI "IMAGENAME eq %KillProg%" | FIND /I "%KillProg%"
IF "%ERRORLEVEL%"=="0" (
TASKKILL.EXE /F /T /IM %KillProg%
) ELSE (
timeout /t %_wait%
GOTO :ProcessNotFound
)
Run with .\taskkill.bat ProgramToKill.exe
I know this is an old question, but since php7.0 you can use the null coalescing operator (another resource).
It similar to the ternary operator, but will behave like isset on the lefthand operand instead of just using its boolean value.
$slide = $_GET["id"] ?? 'fallback';
So if $_GET["id"]
is set, it returns the value. If not, it returns the fallback. I found this very helpful for $_POST, $_GET, or any passed parameters, etc
$slide = $_GET["id"] ?? '';
if (trim($slide) == 'link1') ...
This :
$a = array ('zero','one','two', 'three');
foreach ($a as &$v) {
}
foreach ($a as $v) {
echo $v.PHP_EOL;
}
is the same as
$a = array ('zero','one','two', 'three');
$v = &$a[3];
for ($i = 0; $i < 4; $i++) {
$v = $a[$i];
echo $v.PHP_EOL;
}
OR
$a = array ('zero','one','two', 'three');
for ($i = 0; $i < 4; $i++) {
$a[3] = $a[$i];
echo $a[3].PHP_EOL;
}
OR
$a = array ('zero','one','two', 'three');
$a[3] = $a[0];
echo $a[3].PHP_EOL;
$a[3] = $a[1];
echo $a[3].PHP_EOL;
$a[3] = $a[2];
echo $a[3].PHP_EOL;
$a[3] = $a[3];
echo $a[3].PHP_EOL;
For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.
With your question edit, I see your problem. Let's say the current directory is /home/yourname
... in this case, your command below:
sed 's/xxx/'$PWD'/'
will be expanded to
sed `s/xxx//home/yourname//
which is not valid. You need to put a \
character in front of each /
in your $PWD if you want to do this.
Find out the element which is larger than the body (element which is causing the page to scroll) and just set it's position to fixed. NOTE: I'm not talking to change the position of draggable elements. Draggable elements can be dragged out of body only when there's an element larger than body (mostly in width).
I combined, minified and extended (some more checks) the answers from @Bijay Rungta and @J.C. Inacio
<?php
if(!extension_loaded('Memcache'))
{
die("Memcache extension is not loaded");
}
if (!class_exists('Memcache'))
{
die('Memcache class not available');
}
$memcacheObj = new Memcache;
if(!$memcacheObj)
{
die('Could not create memcache object');
}
if (!$memcacheObj->connect('localhost'))
{
die('Could not connect to memcache server');
}
// testdata to store in memcache
$testData = array(
'the' => 'cake',
'is' => 'a lie',
);
// set data (if not present)
$aData = $memcacheObj->get('data');
if (!$aData)
{
if(!$memcacheObj->set('data', $testData, 0, 300))
{
die('Memcache could not set the data');
}
}
// try to fetch data
$aData = $memcacheObj->get('data');
if (!$aData)
{
die('Memcache is not responding with data');
}
if($aData !== $testData)
{
die('Memcache is responding but with wrong data');
}
die('Memcache is working fine');
Here is the what I have done to avoid CrossThreadException
and writing to the textbox from another thread.
Here is my Button.Click
function- I want to generate a random number of threads and then get their IDs
by calling the getID()
method and the TextBox value while being in that worker thread.
private void btnAppend_Click(object sender, EventArgs e)
{
Random n = new Random();
for (int i = 0; i < n.Next(1,5); i++)
{
label2.Text = "UI Id" + ((Thread.CurrentThread.ManagedThreadId).ToString());
Thread t = new Thread(getId);
t.Start();
}
}
Here is getId
(workerThread) code:
public void getId()
{
int id = Thread.CurrentThread.ManagedThreadId;
//Note that, I have collected threadId just before calling this.Invoke
//method else it would be same as of UI thread inside the below code block
this.Invoke((MethodInvoker)delegate ()
{
inpTxt.Text += "My id is" +"--"+id+Environment.NewLine;
});
}
If the audio wrapped into the avi is not mp3-format to start with, you may need to specify -acodec mp3
as an additional parameter. Or whatever your mp3 codec is (on Linux systems its probably -acodec libmp3lame
). You may also get the same effect, platform-agnostic, by instead specifying -f mp3
to "force" the format to mp3, although not all versions of ffmpeg still support that switch. Your Mileage May Vary.
Well seeing this thread as a beginner got my head spinning. Hence came up with a simple shortcut.
Though str.strip() works to remove leading & trailing spaces it does nothing for spaces between characters.
words=input("Enter the word to test")
# If I have a user enter discontinous threads it becomes a problem
# input = " he llo, ho w are y ou "
n=words.strip()
print(n)
# output "he llo, ho w are y ou" - only leading & trailing spaces are removed
Instead use str.replace() to make more sense plus less error & more to the point. The following code can generalize the use of str.replace()
def whitespace(words):
r=words.replace(' ','') # removes all whitespace
n=r.replace(',','|') # other uses of replace
return n
def run():
words=input("Enter the word to test") # take user input
m=whitespace(words) #encase the def in run() to imporve usability on various functions
o=m.count('f') # for testing
return m,o
print(run())
output- ('hello|howareyou', 0)
Can be helpful while inheriting the same in diff. functions.
If you don't care about a minimum width for the div and really just don't want the div to expand across the whole container, you can float it left -- floated divs by default expand to support their contents, like so:
<form>
<div style="float: left; background-color: blue">
<input type="button" name="blah" value="lots and lots of characters"/>
<input type="button" name="blah2" value="some characters"/>
</div>
</form>
You can also use a Subject and trigger its next() function from promise. See sample below:
Add code like below ( I used service )
class UserService {_x000D_
private createUserSubject: Subject < any > ;_x000D_
_x000D_
createUserWithEmailAndPassword() {_x000D_
if (this.createUserSubject) {_x000D_
return this.createUserSubject;_x000D_
} else {_x000D_
this.createUserSubject = new Subject < any > ();_x000D_
firebase.auth().createUserWithEmailAndPassword(email,_x000D_
password)_x000D_
.then(function(firebaseUser) {_x000D_
// do something to update your UI component_x000D_
// pass user object to UI component_x000D_
this.createUserSubject.next(firebaseUser);_x000D_
})_x000D_
.catch(function(error) {_x000D_
// Handle Errors here._x000D_
var errorCode = error.code;_x000D_
var errorMessage = error.message;_x000D_
this.createUserSubject.error(error);_x000D_
// ..._x000D_
});_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
Create User From Component like below
class UserComponent {_x000D_
constructor(private userService: UserService) {_x000D_
this.userService.createUserWithEmailAndPassword().subscribe(user => console.log(user), error => console.log(error);_x000D_
}_x000D_
}
_x000D_
For Perfect DateTime
Match in SQL Server
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
To solve the problem I use ${string_prompt} variable. It shows a input dialog when application runs. I can set the date/time manually at that dialog.
I am promoting my comment to an answer:
The easy way is:
You could draw in the original 'frame' itself instead of using gray image.
The hard way (method you were trying to implement):
backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
is the correct syntax.
If you want to fix vbs associations type
regsvr32 vbscript.dll
regsvr32 jscript.dll
regsvr32 wshext.dll
regsvr32 wshom.ocx
regsvr32 wshcon.dll
regsvr32 scrrun.dll
Also if you can't use vbs due to management then convert your script to a vb.net program which is designed to be easy, is easy, and takes 5 minutes.
Big difference is functions and subs are both called using brackets rather than just functions.
So the compilers are installed on all computers with .NET installed.
See this article here on how to make a .NET exe. Note the sample is for a scripting host. You can't use this, you have to put your vbs code in as .NET code.
How to import images into the gallery of an Android Virtual Device using Android Studio: I'm using Android Studio 1.4.1 and a API 15 virtual device.
Warning: This is manual intensive so it is not a good solution for a large number of images.
cast to an int then do a .toString()
. It is ugly but it works.
Mark Russinovich wrote a terrific tool called AccessChk that lets you get this information from the command line. No installation is necessary.
http://technet.microsoft.com/en-us/sysinternals/bb664922.aspx
For example:
accesschk.exe /accepteula -q -a SeServiceLogonRight
Returns this for me:
IIS APPPOOL\DefaultAppPool
IIS APPPOOL\Classic .NET AppPool
NT SERVICE\ALL SERVICES
By contrast, whoami /priv
and whoami /all
were missing some entries for me, like SeServiceLogonRight
.
Have a look at the documentation. Use the intValue
method:
NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];
Great article i found what worked best for me was to add a % to the size
.wrap {
margin-top:5%;
margin-bottom:5%;
height:100%;
display:block;}
I agree with japollock way up there--throw an acception when you are uncertain about the outcome of an operation. Calls to APIs, accessing filesystems, database calls, etc. Anytime you are moving past the "boundaries" of your programming languages.
I'd like to add, feel free to throw a standard exception. Unless you are going to do something "different" (ignore, email, log, show that twitter whale picture thingy, etc), then don't bother with custom exceptions.
Update table set column = (select...)
never worked for me since set only expects 1 value - SQL Error: ORA-01427: single-row subquery returns more than one row.
here's the solution:
BEGIN
For i in (select id, name, desc from table1)
LOOP
Update table2 set name = i.name, desc = i.desc where id = i.id;
END LOOP;
END;
That's how exactly you run it on SQLDeveloper worksheet. They say it's slow but that's the only solution that worked for me on this case.
There is an overload of Url.Action that takes your desired protocol (e.g. http, https) as an argument - if you specify this, you get a fully qualified URL.
Here's an example that uses the protocol of the current request in an action method:
var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);
HtmlHelper (@Html) also has an overload of the ActionLink method that you can use in razor to create an anchor element, but it also requires the hostName and fragment parameters. So I'd just opt to use @Url.Action again:
<span>
Copy
<a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a>
and post it anywhere on the internet!
</span>
This is also working at my end...
<div style="width: 100px; height: 100px; float: left; position: relative;">
<div
style="width: 100%; height: 40px; position: absolute; top: 50%; left: 0; margin-top: -20px; line-height:19px; text-align: center; z-index: 999999999999999">
99%<Br />
Total
</div>
<canvas id="chart-area" width="100" height="100" />
</div>
I think you can use SeriesGroupBy.nunique
:
print (df.groupby('param')['group'].nunique())
param
a 2
b 1
Name: group, dtype: int64
Another solution with unique
, then create new df
by DataFrame.from_records
, reshape to Series
by stack
and last value_counts
:
a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a 2
b 1
dtype: int64
In addition at the Daniel Vassallo solution, if you use SQL Server 2016+, there is another solution that I used in some cases without considerable lost of performances.
You can create just a table with only the common field and add a single column with the JSON string that contains all the subtype specific fields.
I have tested this design for manage inheritance and I am very happy for the flexibility that I can use in the relative application.
the following code works for me. It requires openCV (import cv2).
The code is composed of an infinite loop that is continuously looking for a key pressed. In this case, when the 'q' key is pressed, the program ends. Other keys can be pressed (in this example 'b' or 'k') to perform different actions such as change a variable value or execute a function.
import cv2
while True:
k = cv2.waitKey(1) & 0xFF
# press 'q' to exit
if k == ord('q'):
break
elif k == ord('b'):
# change a variable / do something ...
elif k == ord('k'):
# change a variable / do something ...
you can use super while extending Exception
if (pass.length() < minPassLength)
throw new InvalidPassException("The password provided is too short");
} catch (NullPointerException e) {
throw new InvalidPassException("No password provided", e);
}
// A custom business exception
class InvalidPassException extends Exception {
InvalidPassException() {
}
InvalidPassException(String message) {
super(message);
}
InvalidPassException(String message, Throwable cause) {
super(message, cause);
}
}
}
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
Get encoding from headers and convert it to utf-8.
$post_url='http://website.domain';
/// Get headers ////////////////////////////////////////////////////////////
function get_headers_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$r = curl_exec($ch);
return $r;
}
$the_header = get_headers_curl($post_url);
/// check for redirect /////////////////////////////////////////////////
if (preg_match("/Location:/i", $the_header)) {
$arr = explode('Location:', $the_header);
$location = $arr[1];
$location=explode(chr(10), $location);
$location = $location[0];
$the_header = get_headers_curl(trim($location));
}
/// Get charset /////////////////////////////////////////////////////////////////////
if (preg_match("/charset=/i", $the_header)) {
$arr = explode('charset=', $the_header);
$charset = $arr[1];
$charset=explode(chr(10), $charset);
$charset = $charset[0];
}
///////////////////////////////////////////////////////////////////////////////
// echo $charset;
if($charset && $charset!='UTF-8') { $html = iconv($charset, "UTF-8", $html); }
At first see this question to see how you can find if a link has a jQuery handler assigned to it.
Next use:
$("a").attr("onclick")
to see if there is a javascript event assigned to it.
If any of the above is true, then call the click method. If not, get the link:
$("a").attr("href")
and follow it.
I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.
Backup
..PLAIN
for Format USE INSERT COMMANDS
Use Column Inserts
if you want column names in your inserts.Backup
buttonedit: With Flash you can communicate between any window, ANY browser (yes, from FF to IE at runtime ) ..ANY form of instance of flash (ShockWave/activeX)
LDAP is also used to store your credentials in a network security system and retrieve it with your password and decrypted key giving you access to the services.
Note: if you need to use sudo, do this:
sudo bash -c 'cat file2 >> file1'
The usual method of simply prepending sudo
to the command will fail, since the privilege escalation doesn't carry over into the output redirection.
Small improvement to the code from ryyst (who got the most votes) is to not use dynamically allocated decoding table but rather static const precomputed table. This eliminates the use of pointer and initialization of the table, and also avoids memory leakage if one forgets to clean up the decoding table with base64_cleanup() (by the way, in base64_cleanup(), after calling free(decoding_table), one should have decoding_table=NULL, otherwise accidentally calling base64_decode after base64_cleanup() will crash or cause undetermined behavior). Another solution could be to use std::unique_ptr...but I'm satisfied with just having const char[256] on the stack and avoid using pointers alltogether - the code looks cleaner and shorter this way.
The decoding table is computed as follows:
const char encoding_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
unsigned char decoding_table[256];
for (int i = 0; i < 256; i++)
decoding_table[i] = '\0';
for (int i = 0; i < 64; i++)
decoding_table[(unsigned char)encoding_table[i]] = i;
for (int i = 0; i < 256; i++)
cout << "0x" << (int(decoding_table[i]) < 16 ? "0" : "") << hex << int(decoding_table[i]) << (i != 255 ? "," : "") << ((i+1) % 16 == 0 ? '\n' : '\0');
cin.ignore();
and the modified code I am using is:
static const char encoding_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
static const unsigned char decoding_table[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x3f,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
char* base64_encode(const unsigned char *data, size_t input_length, size_t &output_length) {
const int mod_table[] = { 0, 2, 1 };
output_length = 4 * ((input_length + 2) / 3);
char *encoded_data = (char*)malloc(output_length);
if (encoded_data == nullptr)
return nullptr;
for (int i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for (int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[output_length - 1 - i] = '=';
return encoded_data;
};
unsigned char* base64_decode(const char *data, size_t input_length, size_t &output_length) {
if (input_length % 4 != 0)
return nullptr;
output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') (output_length)--;
if (data[input_length - 2] == '=') (output_length)--;
unsigned char* decoded_data = (unsigned char*)malloc(output_length);
if (decoded_data == nullptr)
return nullptr;
for (int i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (j < output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
return decoded_data;
};
I love jtbandes answer, but since it is pretty long, I will add my own compact answer:
==
, ===
, eql?
, equal?
are 4 comparators, ie. 4 ways to compare 2 objects, in Ruby.
As, in Ruby, all comparators (and most operators) are actually method-calls, you can change, overwrite, and define the semantics of these comparing methods yourself. However, it is important to understand, when Ruby's internal language constructs use which comparator:
==
(value comparison)
Ruby uses :== everywhere to compare the values of 2 objects, eg. Hash-values:
{a: 'z'} == {a: 'Z'} # => false
{a: 1} == {a: 1.0} # => true
===
(case comparison)
Ruby uses :=== in case/when constructs. The following code snippets are logically identical:
case foo
when bar; p 'do something'
end
if bar === foo
p 'do something'
end
eql?
(Hash-key comparison)
Ruby uses :eql? (in combination with the method hash) to compare Hash-keys. In most classes :eql? is identical with :==.
Knowledge about :eql? is only important, when you want to create your own special classes:
class Equ
attr_accessor :val
alias_method :initialize, :val=
def hash() self.val % 2 end
def eql?(other) self.hash == other.hash end
end
h = {Equ.new(3) => 3, Equ.new(8) => 8, Equ.new(15) => 15} #3 entries, but 2 are :eql?
h.size # => 2
h[Equ.new(27)] # => 15
Note: The commonly used Ruby-class Set also relies on Hash-key-comparison.
equal?
(object identity comparison)
Ruby uses :equal? to check if two objects are identical. This method (of class BasicObject) is not supposed to be overwritten.
obj = obj2 = 'a'
obj.equal? obj2 # => true
obj.equal? obj.dup # => false
You can use jackson library and simply use these 3 lines to convert your json file to Java Object.
ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.
As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:
div#top-level
declarations: ...
div.inside
declarations: ...
&:first-child
declarations: ...
which compiles as one would expect:
div#top-level{
declarations... }
div#top-level div.inside {
declarations... }
div#top-level div.inside:first-child {
declarations... }
I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.
The xsd file is the schema of the xml file - it defines which elements may occur and their restrictions (like amount, order, boundaries, relationships,...)
This is my working solution:
select tabname as table_name
from syscat.tables
where tabschema = 'schema_name' -- put schema name here
and type = 'T'
order by tabname
See this snippet: (C#)
private Microsoft.Office.Interop.Excel.Application xla;
Workbook wb;
Worksheet ws;
Range rg;
..........
xla = new Microsoft.Office.Interop.Excel.Application();
wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
ws = (Worksheet)xla.ActiveSheet;
rg = (Range)ws.Cells[1, 2];
rg.ColumnWidth = 10;
rg.Value2 = "Frequency";
rg = (Range)ws.Cells[1, 3];
rg.ColumnWidth = 15;
rg.Value2 = "Impudence";
rg = (Range)ws.Cells[1, 4];
rg.ColumnWidth = 8;
rg.Value2 = "Phase";
First download this JavaScript code, JSON2.js, that will help us serialize the object into a string.
In my example I'm posting the rows of a jqGrid via Ajax:
var commissions = new Array();
// Do several row data and do some push. In this example is just one push.
var rowData = $(GRID_AGENTS).getRowData(ids[i]);
commissions.push(rowData);
$.ajax({
type: "POST",
traditional: true,
url: '<%= Url.Content("~/") %>' + AREA + CONTROLLER + 'SubmitCommissions',
async: true,
data: JSON.stringify(commissions),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Result) {
jQuery(GRID_AGENTS).trigger('reloadGrid');
}
else {
jAlert("A problem ocurred during updating", "Commissions Report");
}
}
});
Now on the controller:
[HttpPost]
[JsonFilter(Param = "commissions", JsonDataType = typeof(List<CommissionsJs>))]
public ActionResult SubmitCommissions(List<CommissionsJs> commissions)
{
var result = dosomething(commissions);
var jsonData = new
{
Result = true,
Message = "Success"
};
if (result < 1)
{
jsonData = new
{
Result = false,
Message = "Problem"
};
}
return Json(jsonData);
}
Create a JsonFilter Class (thanks to JSC reference).
public class JsonFilter : ActionFilterAttribute
{
public string Param { get; set; }
public Type JsonDataType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
{
string inputContent;
using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
{
inputContent = sr.ReadToEnd();
}
var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
filterContext.ActionParameters[Param] = result;
}
}
}
Create another class so the filter can parse the JSON string to the actual manipulable object: This class comissionsJS are all the rows of my jqGrid.
public class CommissionsJs
{
public string Amount { get; set; }
public string CheckNumber { get; set; }
public string Contract { get; set; }
public string DatePayed { get; set; }
public string DealerName { get; set; }
public string ID { get; set; }
public string IdAgentPayment { get; set; }
public string Notes { get; set; }
public string PaymentMethodName { get; set; }
public string RowNumber { get; set; }
public string AgentId { get; set; }
}
I hope this example helps to illustrate how to post a complex object.
The outfile should be in binary mode.
outFile = open('output.xml', 'wb')
To avoid unnecessary duplication, I added the following to my ~/.bash_profile
case ":$PATH:" in
*:/usr/local/bin:*) ;; # do nothing if $PATH already contains /usr/local/bin
*) PATH=/usr/local/bin:$PATH ;; # in every other case, add it to the front
esac
Credit: https://superuser.com/a/580611
The error is explicit ...
Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.
Error: could not find java.dll
Error: Could not find Java SE Runtime Environment.
... you are attempting to use the java.exe
1.7 executable while the HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment
> CurrentVersion
registry key has the value 1.8.
The recurring theme to proposed solutions is that the error is a configuration error. The error can be solved in various different manners (e.g. reconfiguration of the users environment or removal of java executables with fingers-crossed and hope that there exists another fallback java.exe
in the users %PATH%
and that the fallback java.exe
is the correct executable).
The correct solution depends on what you're trying to achieve: "are you trying to downgrade from jdk-8 to jdk-7? Are trying to upgrade to jdk-8? ..."
notes:
- the
java.exe
executable available in the users%PATH%
is installed inC:\Windows\System32
- the installation does not update the users
%PATH%
- the
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
>CurrentVersion
string registry entry is created (among others) with the value1.7
notes:
- the users
%PATH%
is updated to includeC:\Program Files (x86)\Common Files\Oracle\Java\javapath
as the first entry- the the
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
>CurrentVersion
string registry entries value is updated to1.8
update the users %PATH%
environment variable, remove C:\Program Files (x86)\Common Files\Oracle\Java\javapath
in a new command prompt java -version
Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' has value '1.8', but '1.7' is required.
Error: could not find java.dll
Error: Could not find Java SE Runtime Environment.
OP's solution https://stackoverflow.com/a/29769311/1423507 is a "fingers-crossed and hope that there exists a fallback java.exe
in the users %PATH%
and that the fallback executable is correct" approach to the error. Given the reproduction steps, removing the java.exe
, javaw.exe
and javaws.exe
executables from C:\Windows\System32
(only in my case) will result in no longer having any java.exe
present in the users %PATH%
resulting in the error 'java' is not recognized as an internal or external command, operable program or batch file.
which is not so much of a solution.
answers https://stackoverflow.com/a/35775493/1423507 and https://stackoverflow.com/a/36516620/1423507 work however you're reverting to using java.exe
1.7 (e.g. update the CurrentVersion
registry key's value to match the java.exe
version found in the users %PATH%
).
make surejava.exe
1.8 is the first found in the users %PATH%
(how you do that is irrelevant) i.e.:
%PATH%
to include C:\Program Files (x86)\Common Files\Oracle\Java\javapath
first (ensure that the executables in that directory are correct)%PATH%
to include the absolute path of your java binaries first (set PATH="C:\Program Files\Java\jre1.8.0_191\bin;%PATH%"
)%PATH%
with them (set JAVA_HOME="C:\Program Files\Java"
; set JRE_HOME=%JAVA_HOME%\jre1.8.0_191
; set PATH=%JRE_HOME%\bin;%PATH%
) div{_x000D_
border: 1px solid;_x000D_
}_x000D_
span{_x000D_
display: flex;_x000D_
align-items: center;_x000D_
}_x000D_
.col-5{_x000D_
width: 100px;_x000D_
height: 50px;_x000D_
float: left;_x000D_
background: red;_x000D_
}_x000D_
.col-7{_x000D_
width: 200px;_x000D_
height: 24px;_x000D_
_x000D_
float: left;_x000D_
background: green;_x000D_
}
_x000D_
<span>_x000D_
<div class="col-5">_x000D_
</div>_x000D_
<div class="col-7"></div>_x000D_
</span>
_x000D_
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
This error occurs when we parse json content to model object. Json content type is string. For example: https://dotnetfiddle.net/uFClKj Some times, an api that we call may return an error. If we do not check the response status, but proceed to parse the response to model, this issue will occur.
These are the options currently documented in the tests: ctrl, shift, enter and escape. These are some valid examples of key bindings:
keydown.control.shift.enter
keydown.control.esc
You can track this here while no official docs exist, but they should be out soon.
Here is another solution, If you are using ES6 using spread operator:
var arr = [0, 21, 22, 7];
const indexOfMaxValue = arr.indexOf(Math.max(...arr));
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: http://www.ndepend.com/. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link
There is also the possibility to use the Vector Asset Studio in combination with Scalable Vector Graphics (SVG). Android Studio will handle the rest for you. As the official documentation says:
Vector Asset Studio helps you add material icons and import Scalable Vector Graphic (SVG) files into your app project as a drawable resource. Compared to raster images, vector drawables can reduce the size of your app and be resized without loss of image quality. They help you to more easily support different Android devices with varying screen sizes and resolutions because you can display one vector drawable on all of them.
I consider this the future approach.
Had this problem and solved typing this : C:\Program Files (x86)\Java\jdk1.7.0_51\bin\javadoc.exe
Just copy this:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your text:"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
/>
</LinearLayout>
Happy codding! :)
You can appendChild
to document.body
but not if the document hasn't been loaded. So you should
put everything in:
window.onload=function(){
//your code
}
This works or you can make appendChild
to be dependent on something else like another event for eg.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append
As a matter of fact you can try changing the innerHTML
of the document.body
it works...!
I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.
Casting pointers is usually invalid in C. There are several reasons:
Alignment. It's possible that, due to alignment considerations, the destination pointer type is not able to represent the value of the source pointer type. For example, if int *
were inherently 4-byte aligned, casting char *
to int *
would lose the lower bits.
Aliasing. In general it's forbidden to access an object except via an lvalue of the correct type for the object. There are some exceptions, but unless you understand them very well you don't want to do it. Note that aliasing is only a problem if you actually dereference the pointer (apply the *
or ->
operators to it, or pass it to a function that will dereference it).
The main notable cases where casting pointers is okay are:
When the destination pointer type points to character type. Pointers to character types are guaranteed to be able to represent any pointer to any type, and successfully round-trip it back to the original type if desired. Pointer to void (void *
) is exactly the same as a pointer to a character type except that you're not allowed to dereference it or do arithmetic on it, and it automatically converts to and from other pointer types without needing a cast, so pointers to void are usually preferable over pointers to character types for this purpose.
When the destination pointer type is a pointer to structure type whose members exactly match the initial members of the originally-pointed-to structure type. This is useful for various object-oriented programming techniques in C.
Some other obscure cases are technically okay in terms of the language requirements, but problematic and best avoided.
Change your model to specify what columns you want selected:
public function user() {
return $this->belongs_to('User')->select(array('id', 'username'));
}
And don't forget to include the column you're joining on.
On Eclipse I was able to solve the above issue by following the below steps :
Right-click on the test file which you want to run, Select Run As -> Run Configurations -> Select Classpath tab -> Select to the bootstrap Entries -> Select Advanced -> Select Add library -> Select JUnit -> Next ->Select JUnit4 from the drop-down -> Finish
Then Select Apply -> Run
in implementation detail.
CLR2's System.String is mutable. StringBuilder.Append calling String.AppendInplace (private method)
CLR4's System.String is immutable. StringBuilder have Char array with chunking.
If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^
. Then add all files and commit again.
Using change
event you can do something like this:
var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
It has been mentioned in earlier answers that using dependency walker is the way to go, in my case (my application keeps failing with the error code), dependency walker showed a few dll that are NOT relevant!
Finally figured out that I can run profiling by going to "profile" menu and it will run the application and stop at the exact dll that's cause the problem! I found out a 32bit dll was picked because of path and fixed it.
For me the problem was invalid permissions - I was requesting "birthday" instead of "user_birthday". It's a shame the error message isn't at least minimally descriptive - just saying "permissions invalid" rather than ERROR CODE 2 would have saved me so much time.
In case you are using node.js (with express)
If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:
app.use(express.static("public"));
Where app is:
const express = require("express");
const app = express();
Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)
Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.
After you add them change the stylesheet accordingly. For example if it was:
href="cssFileName.css"
and
src="imgName.png"
Make them:
href="css/cssFileName.css"
src="css/images/imgName.png"
That should work
I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects
import Image
import numpy as np
im = Image.load('foo.jpg')
im = im.convert('L')
arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)
arr ^= 0xFF # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()
I dont know if there is a canonical way, but here's my method:
And use this code:
MyCustomViewCell *cell = (MyCustomViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
UIViewController* c = [[UIViewController alloc] initWithNibName:CellIdentifier bundle:nil];
cell = (MyCustomViewCell *)c.view;
[c release];
}
In your example, using
[nib objectAtIndex:0]
may break if Apple changes the order of items in the xib.
Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.
I know how to generate random number in C++ without using any headers, compiler intrinsics or whatever.
#include <cstdio> // Just for printf
int main() {
auto val = new char[0x10000];
auto num = reinterpret_cast<unsigned long long>(val);
delete[] val;
num = num / 0x1000 % 10;
printf("%llu\n", num);
}
I got the following stats after run for some period of time:
0: 5268
1: 5284
2: 5279
3: 5242
4: 5191
5: 5135
6: 5183
7: 5236
8: 5372
9: 5343
Looks random.
How it works:
Assuming SQL Server 2000, the following StackOverflow question should address your problem.
If using SQL Server 2005/2008, you can use the following code (taken from here):
select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable
Here's a method using display:flex
:
.container {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
display: flex;_x000D_
position: fixed;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>centered text!</div>_x000D_
</div>
_x000D_
For Picrofo EDY
It depends, if you use the ShowDialog()
as a way of showing your form and to close it you use the close button instead of this.Close()
. The form will not be disposed or destroyed, it will only be hidden and changes can be made after is gone. In order to properly close it you will need the Dispose()
or Close()
method. In the other hand, if you use the Show()
method and you close it, the form will be disposed and can not be modified after.
For modal component in React project, the open or close of the modal, controlling browser back is a necessary action.
The stopBrowserBack
: the stop of the browser back button functionality, also get a callback function. This callback function is what you want to do:
const stopBrowserBack = callback => {
window.history.pushState(null, "", window.location.href);
window.onpopstate = () => {
window.history.pushState(null, "", window.location.href);
callback();
};
};
The startBrowserBack
: the revival of the browser back button functionality:
const startBrowserBack = () => {
window.onpopstate = undefined;
window.history.back();
};
The usage in your project:
handleOpenModal = () =>
this.setState(
{ modalOpen: true },
() => stopBrowserBack(this.handleCloseModal)
);
handleCloseModal = () =>
this.setState(
{ modalOpen: false },
startBrowserBack
);
Pressing Shift+v would select that entire line and pressing d would delete it.
You can also use dd, which is does not require you to enter visual mode.