The solution that work for me is the following:
$('#myModal').modal({backdrop: 'static', keyboard: false})
backdrop: disabled the click outside event
keyboard: disabled the scape keyword event
Your question didnt ask how to use BETWEEN correctly, rather asked for help with the unexpectedly truncated results...
As mentioned/hinting at in the other answers, the problem is that you have time segments in addition to the dates.
In my experience, using date diff is worth the extra wear/tear on the keyboard. It allows you to express exactly what you want, and you are covered.
select *
from xxx
where datediff(d, '2012-10-26', dates) >=0
and datediff(d, dates,'2012-10-27') >=0
using datediff, if the first date is before the second date, you get a positive number. There are several ways to write the above, for instance always having the field first, then the constant. Just flipping the operator. Its a matter of personal preference.
you can be explicit about whether you want to be inclusive or exclusive of the endpoints by dropping one or both equal signs.
BETWEEN will work in your case, because the endpoints are both assumed to be midnight (ie DATEs). If your endpoints were also DATETIME, using BETWEEN may require even more casting. In my mind DATEDIFF was put in our lives to insulate us from those issues.
Some people may not like it, but this is what I do:
private void StartBackgroundWork() {
if (Application.RenderWithVisualStyles)
progressBar.Style = ProgressBarStyle.Marquee;
else {
progressBar.Style = ProgressBarStyle.Continuous;
progressBar.Maximum = 100;
progressBar.Value = 0;
timer.Enabled = true;
}
backgroundWorker.RunWorkerAsync();
}
private void timer_Tick(object sender, EventArgs e) {
if (progressBar.Value < progressBar.Maximum)
progressBar.Increment(5);
else
progressBar.Value = progressBar.Minimum;
}
The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.
I tried all the answers above to install Python 3.4.4. The installation of python worked, but PIP would not be installed and nothing I could do to make it work. I was using Mac OSX Mojave, which cause some issues with zlib, openssl.
What not to do:
Solution:
p.s: You don't have to uninstall your other version of Python on your system.
Edit:
I found a much much much better solution that work on MacOSX, Windows, Linux, etc.
conda init
conda create -n [NameOfYour VirtualEnvironment] python=3.4.4
conda info --envs
conda activate [The name of your virtual environment that was shown with the command at step 5]
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...
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
The follows might be helpful:
# Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, None
plt.xticks(
rotation=45,
horizontalalignment='right',
fontweight='light',
fontsize='medium',
)
Here is the function xticks
[reference] with example and API
def xticks(ticks=None, labels=None, **kwargs):
"""
Get or set the current tick locations and labels of the x-axis.
Call signatures::
locs, labels = xticks() # Get locations and labels
xticks(ticks, [labels], **kwargs) # Set locations and labels
Parameters
----------
ticks : array_like
A list of positions at which ticks should be placed. You can pass an
empty list to disable xticks.
labels : array_like, optional
A list of explicit labels to place at the given *locs*.
**kwargs
:class:`.Text` properties can be used to control the appearance of
the labels.
Returns
-------
locs
An array of label locations.
labels
A list of `.Text` objects.
Notes
-----
Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
Examples
--------
Get the current locations and labels:
>>> locs, labels = xticks()
Set label locations:
>>> xticks(np.arange(0, 1, step=0.2))
Set text labels:
>>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
Set text labels and properties:
>>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)
Disable xticks:
>>> xticks([])
"""
You can just delete that directory that you cloned the repo into, and re-clone it wherever you'd like.
Linux dotnet core doesn't support namedpipes!
Try TcpListener if you deploy to Linux
This NamedPipe Client/Server code round trips a byte to a server.
DotNet Core 2.0 Server ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static void Main(string[] args)
{
var server = new NamedPipeServerStream("A", PipeDirection.InOut);
server.WaitForConnection();
for (int i =0; i < 10000; i++)
{
var b = new byte[1];
server.Read(b, 0, 1);
Console.WriteLine("Read Byte:" + b[0]);
server.Write(b, 0, 1);
}
}
}
}
DotNet Core 2.0 Client ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Client
{
class Program
{
public static int threadcounter = 1;
public static NamedPipeClientStream client;
static void Main(string[] args)
{
client = new NamedPipeClientStream(".", "A", PipeDirection.InOut, PipeOptions.Asynchronous);
client.Connect();
var t1 = new System.Threading.Thread(StartSend);
var t2 = new System.Threading.Thread(StartSend);
t1.Start();
t2.Start();
}
public static void StartSend()
{
int thisThread = threadcounter;
threadcounter++;
StartReadingAsync(client);
for (int i = 0; i < 10000; i++)
{
var buf = new byte[1];
buf[0] = (byte)i;
client.WriteAsync(buf, 0, 1);
Console.WriteLine($@"Thread{thisThread} Wrote: {buf[0]}");
}
}
public static async Task StartReadingAsync(NamedPipeClientStream pipe)
{
var bufferLength = 1;
byte[] pBuffer = new byte[bufferLength];
await pipe.ReadAsync(pBuffer, 0, bufferLength).ContinueWith(async c =>
{
Console.WriteLine($@"read data {pBuffer[0]}");
await StartReadingAsync(pipe); // read the next data <--
});
}
}
}
opacity
applies to the whole element, so if you have a background, border or other effects on that element, those will also become transparent. If you only want the text to be transparent, use rgba
.
#foo {
color: #000; /* Fallback for older browsers */
color: rgba(0, 0, 0, 0.5);
font-size: 16pt;
font-family: Arial, sans-serif;
}
Also, steer far, far away from <font>
. We have CSS for that now.
If you have indexed ID and OrderNo You can use IN: (I hate trading simplicity for obscurity, just to save some cycles):
select * from myTab where ID in(select max(ID) from myTab group by OrderNo);
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n
will work.
If you use anything else you will cause issues with cut and paste on Windows platforms.
The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n
linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.
Interestingly, in spite of the Unix line end convention being \n
, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n
. Yes, it may not make a lot of sense, but that's history and evolving standards for you!
You can write a query as follows:
IF OBJECT_ID('ProcedureName','P') IS NOT NULL
DROP PROC ProcedureName
GO
CREATE PROCEDURE [dbo].[ProcedureName]
...your query here....
To be more specific on the above syntax:
OBJECT_ID is a unique id number for an object within the database, this is used internally by SQL Server. Since we are passing ProcedureName followed by you object type P which tells the SQL Server that you should find the object called ProcedureName which is of type procedure i.e., P
This query will find the procedure and if it is available it will drop it and create new one.
For detailed information about OBJECT_ID and Object types please visit : SYS.Objects
There are two solutions:
Formatter
is more recent even though it takes over printf()
which is 40 years old...
Your placeholder as you currently define it is one MessageFormat
can use, but why use an antique technique? ;) Use Formatter
.
There is all the more reason to use Formatter
that you don't need to escape single quotes! MessageFormat
requires you to do so. Also, Formatter
has a shortcut via String.format()
to generate strings, and PrintWriter
s have .printf()
(that includes System.out
and System.err
which are both PrintWriter
s by default)
The following definition might be more efficient than the first solution proposed
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
This uses a helper batch file called repl.bat
- download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat
Place repl.bat
in the same folder as the batch file or in a folder that is on the path.
Repl.bat is a hybrid batch file using native Windows scripting and is far faster than a regular batch script.
The L
switch makes the text search and replace a literal string and I'd expect the 12 MB file to complete in several seconds on a modern PC.
@echo off &setlocal
set "search=%~1"
set "replace=%~2"
set "textfile=Input.txt"
set "newfile=Output.txt"
call repl.bat "%search%" "%replace%" L < "%textfile%" >"%newfile%"
del "%textfile%"
rename "%newfile%" "%textfile%"
Use
git clone https://github.com/<path>/repository
or
git clone https://github.com/<path>/<master>.git
examples
git clone https://github.com/spring-projects/spring-data-graph-examples
git clone https://github.com/spring-projects/spring-data-graph-examples.git
I have experimented many of the backslash escape characters. \n
which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.
Code:
#include <stdio.h>
int main(void){
printf("Hello World!");
printf("Goodbye \a");
printf("Hi \b");
printf("Yo\f");
printf("What? \t");
printf("pewpew");
return 0;
}
I think this is what you want, from the bootstrap documentation "Horizontal form Use Bootstrap's predefined grid classes to align labels and groups of form controls in a horizontal layout by adding .form-horizontal to the form. Doing so changes .form-groups to behave as grid rows, so no need for .row". So:
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
Take a closer look at the ?axis
documentation. If you look at the description of the labels
argument, you'll see that it is:
"a logical value specifying whether (numerical) annotations are
to be made at the tickmarks,"
So, just change it to true, and you'll get your tick labels.
x <- seq(10,200,10)
y <- runif(x)
plot(x,y,xaxt='n')
axis(side = 1, at = x,labels = T)
# Since TRUE is the default for labels, you can just use axis(side=1,at=x)
Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.
It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis
into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.
I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state.
Precisely. In fact, it's still being used for this purpose today because HTTP as we know it today is still, at least fundamentally, a stateless protocol.
This use case was actually first described in HTML 3.2 (I'm surprised HTML 2.0 didn't include such a description):
type=hidden
These fields should not be rendered and provide a means for servers to store state information with a form. This will be passed back to the server when the form is submitted, using the name/value pair defined by the corresponding attributes. This is a work around for the statelessness of HTTP. Another approach is to use HTTP "Cookies".<input type=hidden name=customerid value="c2415-345-8563">
While it's worth mentioning that HTML 3.2 became a W3C Recommendation only after JavaScript's initial release, it's safe to assume that hidden fields have pretty much always served the same purpose.
I would omit the * { text-align:center }
declaration, as it sets center alignment for all elements.
Usually with a fixed width container margin: 0 auto
should be enough
function parseJsonDate(jsonDate) {
var fullDate = new Date(parseInt(jsonDate.substr(6)));
var twoDigitMonth = (fullDate.getMonth() + 1) + ""; if (twoDigitMonth.length == 1) twoDigitMonth = "0" + twoDigitMonth;
var twoDigitDate = fullDate.getDate() + ""; if (twoDigitDate.length == 1) twoDigitDate = "0" + twoDigitDate;
var currentDate = twoDigitMonth + "/" + twoDigitDate + "/" + fullDate.getFullYear();
return currentDate;
};
There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:
appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5
Appcmd is located in %windir%\System32\inetsrv
. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.
<div class="row">
<div class="col-sm-6">
<div class="card">
Content one
</div>
</div>
<div class="col-sm-6">
<div class="card">
Content two
</div>
</div>
</div>
std::vector
is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin()
, end()
, iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).
Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.
std::array
is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.
It's more limited than std::vector
, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector
and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector
.
For an introduction to std::array
, have a look at this article; for a quick introduction to std::vector
and to the the operations that are possible on it, you may want to look at its documentation.
What do you mean by impacts? Content will flow around a float. That's how they work.
If you want it to appear above your design, try setting:
z-index: 10;
position: absolute;
right: 0;
top: 0;
With jquery you could do to sth. like this, which will simply switch classes.
$('.showhide').click(function() {
$(this).removeClass('myclass');
$(this).addClass('showhidenew');
});
If you want to switch classes back and forth on each click, you can use toggleClass, like so:
$('.showhide').click(function() {
$(this).toggleClass('myclass');
$(this).toggleClass('showhidenew');
});
use desc with orderby at the end of the query to get the last values.
the complete know how, i have included a example of the triggers and sequence
create table temasforo(
idtemasforo NUMBER(5) PRIMARY KEY,
autor VARCHAR2(50) NOT NULL,
fecha DATE DEFAULT (sysdate),
asunto LONG );
create sequence temasforo_seq
start with 1
increment by 1
nomaxvalue;
create or replace
trigger temasforo_trigger
before insert on temasforo
referencing OLD as old NEW as new
for each row
begin
:new.idtemasforo:=temasforo_seq.nextval;
end;
reference: http://thenullpointerexceptionx.blogspot.mx/2013/06/llaves-primarias-auto-incrementales-en.html
In Perl the switch is \s
(whitespace).
A quick, non-elegant but working standalone solution with inline CSS and no jQuery requirements. AFAIK it works from IE9 too.
<body style="overflow:hidden; margin:0">
<form id="form1" runat="server">
<div id="main" style="background-color:red">
<div id="content">
</div>
<div id="footer">
</div>
</div>
</form>
<script language="javascript">
function autoResizeDiv()
{
document.getElementById('main').style.height = window.innerHeight +'px';
}
window.onresize = autoResizeDiv;
autoResizeDiv();
</script>
</body>
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
This is not a reply (I cant post comments), just few random ideas might be helpful. Unfortunately I've never dealt with citrix, only with regular windows servers.
_0. Ensure you're not a victim of Windows Firewall, or any other personal firewall that selectively blocks processes.
Add 10 minutes Sleep() to the first line of your .NET app, then run both VBScript file and your stand-alone application, run sysinternals process explorer, and compare 2 processes.
_1. Same tab, "command line" and "current directory". Make sure they are the same.
_2. "Environment" tab. Make sure they are the same. Normally child processes inherit the environment, but this behaviour can be easily altered.
The following check is required if by "run my script" you mean anything else then double-clicking the .VBS file:
_3. Image tab, "User". If they differ - it may mean user has no access to the network (like localsystem), or user token restricted to delegation and thus can only access local resources (like in the case of IIS NTLM auth), or user has no access to some local files it wants.
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
I was able to get this to work...
SELECT CAST('<![CDATA[' + LargeTextColumn + ']]>' AS XML) FROM TableName;
After you extract the classes.dex file, just drag and drop it to d2j-dex2jar
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
You have two " "
before the =
let imageToDeleteParameters = imagesToDelete.map { ["id": $0.id, "url": $0.url.absoluteString, "_destroy": true] }
your thinking about this program below
#include <stdio.h>
#include <string.h>
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6
when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below
#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;
int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];
for(int j=0; j<=Projects-1; j++){
for(int i=0; i<=Students; i++) {
cout <<"Please give grade of student "<< j <<"in project "<< i << ":";
cin >> Grades[j][i];
}
Sum2 = Sum2 + Grades[i][j];
Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}
change to string except it only reads 1 input and throws the rest out maybe need two for loops and two pointers
#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;
char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}
int length = 0;
while(name[length] != '\0')
{
length++;
}
for(n=0; n<4; n++)
{
if (strncmp(ptr, "snit", 4) == 0)
{
cout << "you found the snitch " << ptr[i];
}
}
cout<<name <<"is"<<length<<"chars long";
}
Your classpath is broken (which is a very common problem in the Java world).
Depending on how you start your application, you need to revise the argument to -cp
, your Class-Path entry in MANIFEST.MF or your disk layout.
If you already have checked out the code, the files are already indexed. After changing your git settings, say by running:
git config --global core.autocrlf input
you should refresh the indexes with
git rm --cached -r .
and re-write git index with
git reset --hard
Note: this is will remove your local changes, consider stashing them before you do this.
Put this at the top of the other files where you want to access the class:
using CLIck10.App_Code;
OR access the class from other files like this:
CLIck10.App_Code.Glob
Not sure if that's your issue or not but if you were new to C# then this is an easy one to get tripped up on.
Update: I recently found that if I add an App_Code folder to a project, then I must close/reopen Visual Studio for it to properly recognize this "special" folder.
In addition to what @ckal suggested, it is critical to give each renamed Configuration.cs its own namespace. If you do not, EF will attempt to apply migrations to the wrong context.
Here are the specific steps that work well for me.
If Migrations are messed up and you want to create a new "baseline":
Creating the initial migration:
In Package Manager Console:
Enable-Migrations -EnableAutomaticMigrations -ContextTypeName
NamespaceOfContext.ContextA -ProjectName ProjectContextIsInIfNotMainOne
-StartupProjectName NameOfMainProject -ConnectionStringName ContextA
In Solution Explorer: Rename Migrations.Configuration.cs to Migrations.ConfigurationA.cs. This should automatically rename the constructor if using Visual Studio. Make sure it does. Edit ConfigurationA.cs: Change the namespace to NamespaceOfContext.Migrations.MigrationsA
Enable-Migrations -EnableAutomaticMigrations -ContextTypeName
NamespaceOfContext.ContextB -ProjectName ProjectContextIsInIfNotMainOne
-StartupProjectName NameOfMainProject -ConnectionStringName ContextB
In Solution Explorer: Rename Migrations.Configuration.cs to Migrations.ConfigurationB.cs. Again, make sure the constructor is also renamed appropriately. Edit ConfigurationB.cs: Change the namespace to NamespaceOfContext.Migrations.MigrationsB
add-migration InitialBSchema -IgnoreChanges -ConfigurationTypeName
ConfigurationB -ProjectName ProjectContextIsInIfNotMainOne
-StartupProjectName NameOfMainProject -ConnectionStringName ContextB
Update-Database -ConfigurationTypeName ConfigurationB -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextB
add-migration InitialSurveySchema -IgnoreChanges -ConfigurationTypeName
ConfigurationA -ProjectName ProjectContextIsInIfNotMainOne -StartupProjectName
NameOfMainProject -ConnectionStringName ContextA
Update-Database -ConfigurationTypeName ConfigurationA -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextA
Steps to create migration scripts in Package Manager Console:
Run command
Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationA -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextA
or -
Add-Migration MYMIGRATION -ConfigurationTypeName ConfigurationB -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextB
It is OK to re-run this command until changes are applied to the DB.
Either run the scripts against the desired local database, or run Update-Database without -Script to apply locally:
Update-Database -ConfigurationTypeName ConfigurationA -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextA
or -
Update-Database -ConfigurationTypeName ConfigurationB -ProjectName
ProjectContextIsInIfNotMainOne -StartupProjectName NameOfMainProject
-ConnectionStringName ContextB
try this
function demoShow() {
document.getElementById("but1").style.display="none";
}
<input type="button" value="click me" onclick="demoShow()" id="but" />
<input type="button" value="hide" id="but1" />
I hear a lot of people complain the first one is too difficult to understand and that it is unclear. I don't see a problem with it, but after having that discussion, I use the second one even on INNER JOINS for clarity.
I think what you are doing is subject to the same origin policy. This should be the reason why you are getting permission denied type errors.
This could be simpler and easy to remember and it works for me.
mv $(ls ~/folder | grep -v ~/folder/exclude.png) ~/destination
From Overview of Numeric Types;
BIT[(M)]
A bit-field type. M indicates the number of bits per value, from 1 to 64. The default is 1 if M is omitted.
This data type was added in MySQL 5.0.3 for MyISAM, and extended in 5.0.5 to MEMORY, InnoDB, BDB, and NDBCLUSTER. Before 5.0.3, BIT is a synonym for TINYINT(1).
TINYINT[(M)] [UNSIGNED] [ZEROFILL]
A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.
Additionally consider this;
BOOL, BOOLEAN
These types are synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.
One thing that hasn't been pointed out, is that there is little to no difference between not having an active environment and and activating the base environment, if you just want to run applications from Conda's (Python's) scripts directory (as @DryLabRebel wants).
You can install and uninstall via conda and conda shows the base environment as active - which essentially it is:
> echo $Env:CONDA_DEFAULT_ENV
> conda env list
# conda environments:
#
base * F:\scoop\apps\miniconda3\current
> conda activate
> echo $Env:CONDA_DEFAULT_ENV
base
> conda env list
# conda environments:
#
base * F:\scoop\apps\miniconda3\current
Just to demonstrate the flexibility of javascript: you can use a oneliner for this
function padLeft(nr, n, str){
return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5)); //=> '00023'
console.log((23).padLeft(5)); //=> '00023'
console.log((23).padLeft(5,' ')); //=> ' 23'
console.log(padLeft(23,5,'>>')); //=> '>>>>>>23'
If you want to use this for negative numbers also:
Number.prototype.padLeft = function (n,str) {
return (this < 0 ? '-' : '') +
Array(n-String(Math.abs(this)).length+1)
.join(str||'0') +
(Math.abs(this));
}
console.log((-23).padLeft(5)); //=> '-00023'
Alternative if you don't want to use Array
:
number.prototype.padLeft = function (len,chr) {
var self = Math.abs(this)+'';
return (this<0 && '-' || '')+
(String(Math.pow( 10, (len || 2)-self.length))
.slice(1).replace(/0/g,chr||'0') + self);
}
Check out ea-async which does Java bytecode rewriting to simulate async/await pretty nicely. Per their readme: "It is heavily inspired by Async-Await on the .NET CLR"
There's a jquery plugin for this: jquery.floatThead
A soft real time is easiest to understand, in which even if the result is obtained after the deadline, the results are still considered as valid.
Example: Web browser- We request for certain URL, it takes some time in loading the page. If the system takes more than expected time to provide us with the page, the page obtained is not considered as invalid, we just say that the system's performance wasn't up to the mark (system gave low performance!).
In hard real time system, if the result is obtained after the deadline, the system is considered to have failed completely.
Example: In case of a robot doing some job like line tracing, etc. If a hindrance comes on its path, and the robot doesn't process this information within some programmed deadline (almost instant!), the robot is said to have failed in its task (the robot system may also get completely destroyed!).
In firm real time system, if the result of process execution comes after the deadline, we discard that result, but the system is not termed to have been failed.
Example: Satellite communication for enemy position monitoring or some other task. If the ground computer station to which the satellites send the frames periodically is overloaded, and the current frame (packet) is not processed in time and the next frame comes up, the current packet (the one who missed the deadline) doesn't matter whether the processing was done (or half done or almost done) is dropped/discarded. But the ground computer is not termed to have completely failed.
I couldn't get any of the answers to work on Windows in a simple command window (Windows 7 in my case). awk
, grep
and Select-string
weren't recognized as commands. So I tried a different approach:
git fsck --unreachable | findstr "commit"
start cmd /k git show
will look something like this:
start cmd /k git show 8506d235f935b92df65d58e7d75e9441220537a4
start cmd /k git show 44078733e1b36962571019126243782421fcd8ae
start cmd /k git show ec09069ec893db4ec1901f94eefc8dc606b1dbf1
start cmd /k git show d00aab9198e8b81d052d90720165e48b287c302e
git stash apply (your hash)
may not be the best solution, but worked for me
One way of doing it is to use the ClientScriptManager
:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
Solution for change TextView
width to wrap content.
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.requestLayout();
// Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button).
// If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()
// Another useful example
// textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel
<option value="" selected style="display:none">Please select one item</option>
Using selected
and using display: none;
for hidden item in list.
You can assign a const
object to a non-const
object just fine. Because you're copying and thus creating a new object, const
ness is not violated.
int main() {
const int a = 3;
int b = a;
}
It's different if you want to obtain a pointer or reference to the original, const
object:
int main() {
const int a = 3;
int& b = a; // or int* b = &a;
}
// error: invalid initialization of reference of type 'int&' from
// expression of type 'const int'
You can use const_cast
to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a
through b
in the below example:
int main() {
const int a = 3;
int& b = const_cast<int&>(a);
b = 3;
}
Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.
If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.
Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:
The following program would determine that:
#include <stdio.h>
#include <stdint.h>
int is_big_endian(void)
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
int main(void)
{
printf("System is %s-endian.\n",
is_big_endian() ? "big" : "little");
return 0;
}
You also have this approach; from Quake II:
byte swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
bigendien = false;
And !is_big_endian()
is not 100% to be little as it can be mixed/middle.
Believe this can be checked using same approach only change value from 0x01000000
to i.e. 0x01020304
giving:
switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE
But not entirely sure about that one ...
Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)
https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search
Here's what I did:
function noRightClick() {_x000D_
alert("You cannot save this video for copyright reasons. Sorry about that.");_x000D_
}
_x000D_
<body oncontextmenu="noRightClick();">_x000D_
<video>_x000D_
<source src="http://calumchilds.com/videos/big_buck_bunny.mp4" type="video/mp4">_x000D_
</video>_x000D_
</body>
_x000D_
Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
private double latitudeVillageApartmets= 53.385952001750184;
private double longitudeVillageApartments= -6.599087119102478;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/*These methods all have to do with the map and wht happens if the activity is paused etc*/
//contains lat and lon of another marker
private void setUpMap() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.
Like Andrew said /exclude
parameter of xcopy should be existing file that has list of excludes.
Documentation of xcopy says:
Using /exclude
List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
Example:
xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
and list-of-excluded-files.txt
should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:
exclusion.txt
You want to use pyplot.grid
:
x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)
fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.grid()
plt.show()
ax.xaxis.grid
and ax.yaxis.grid
can control grid lines properties.
Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray()
and be done with it.
If you only have a non-generic IEnumerable, do something like this:
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
public static void T[] PerformQuery<T>()
{
IEnumerable query = ...;
T[] array = query.Cast<T>().ToArray();
return array;
}
You can use case
in bash to simulate a goto:
#!/bin/bash
case bar in
foo)
echo foo
;&
bar)
echo bar
;&
*)
echo star
;;
esac
produces:
bar
star
Try something like this:
var prop;
for(prop in obj) {
if(!obj.hasOwnProperty(prop)) continue;
console.log(prop + " - "+ obj[prop]);
}
Try placing your text-decoration: none;
on your a:hover css.
I was hitting this error with phpMailer + Amazon SES. The phpMailer error is not very descriptive:
2: message: SERVER -> CLIENT: 554 Transaction failed: Expected ';', got "\"
1: message:
2: message: SMTP Error: data not accepted.
For me the issue was simply that I had the following as content type:
$phpmailer->ContentType = 'text/html; charset=utf-8\r\n';
But that it shouldn't have the linebreak in it:
$phpmailer->ContentType = 'text/html; charset=utf-8';
... I suspect this was legacy code from our older version. So basically, triple check every $phpmailer setting you're adding - the smallest detail counts.
List of Special Character codes in JavaScript:
Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
This works for me:
val personsMap = persons.foldLeft(scala.collection.mutable.Map[Int, PersonDTO]()) {
(m, p) => m(p.id) = p; m
}
The Map has to be mutable and the Map has to be return since adding to a mutable Map does not return a map.
When working with continuations I find it useful to think of the place where I write .ContinueWith as the place from which execution immediately continues to the statements following it, not the statements 'inside' it. In that case it becomes clear that you would get an empty string returned in Send. If your only processing of the response is writing it to the console, you don't need any Wait in Ito's solution - the console printout will happen without waits but both Send and Print should return void in that case. Run this in console app and you will get printout of the page.
IMO, waits and Task.Result calls (which block) are necessary sometimes, depending on your desired flow of control, but more often they are a sign that you don't really use asynchronous functionality correctly.
namespace TaskTest
{
class Program
{
static void Main(string[] args)
{
Send();
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
private static void Send()
{
HttpClient client = new HttpClient();
Task<HttpResponseMessage> responseTask = client.GetAsync("http://google.com");
responseTask.ContinueWith(x => Print(x));
}
private static void Print(Task<HttpResponseMessage> httpTask)
{
Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
Task continuation = task.ContinueWith(t =>
{
Console.WriteLine("Result: " + t.Result);
});
}
}
}
It worked to me:
String javaHome = System.getProperty("java.home");
File f = new File(javaHome);
f = new File(f, "bin");
f = new File(f, "javaw.exe"); //or f = new File(f, "javaws.exe"); //work too
System.out.println(f + " exists: " + f.exists());
You can use this for color without alpha:
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
or this with alpha:
String hexColor = String.format("#%08X", (0xFFFFFFFF & intColor));
Here is my solution:
axios({
method: "POST",
url: "https://URL.com/api/services/fetchQuizList",
headers: {
"x-access-key": data,
"x-access-token": token,
},
data: {
quiz_name: quizname,
},
})
.then(res => {
console.log("res", res.data.message);
})
.catch(err => {
console.log("error in request", err);
});
This should help
switch($someString.ToLower())
{
"yes" { $_ = "y" }
"y" { "You entered Yes." }
default { "You entered No." }
}
You can arbitrarily branch, cascade, and merge cases in this fashion, as long as the target case is located below/after the case or cases where the $_ variable is respectively reassigned.
n.b. As cute as this behavior is, it seems to reveal that the PowerShell interpreter is not implementing switch/case as efficiently as one might hope or assume. For one, stepping with the ISE debugger suggests that instead of optimized lookup, hashing, or binary branching, each case is tested in turn, like so many if-else statements. (If so, consider putting your most common cases first.) Also, as shown in this answer, PowerShell continues testing cases after having satisfied one. And cruelly enough, there even happens to be a special optimized 'switch' opcode available in .NET CIL which, because of this behavior, PowerShell can't take advantage of.
It is worth pointing out that on Safari on the iPhone, at least, inserting basic HTML tags such as <b>
, <i>
, and <img>
(which ideally you shouldn't use in other circumstances anymore anyway, preferring CSS) into the body parameter in the mailto:
does appear to work - they are honored within the email client. I haven't done exhaustive testing to see if this is supported by other mobile or desktop browser/email client combos. It's also dubious whether this is really standards-compliant. Might be useful if you are building for that platform, though.
As other responses have noted, you should also use encodeURIComponent on the entire body before embedding it in the mailto:
link.
If you're on the New Google Sheets, this is all you need to do, according to the docs:
change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.
This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.
If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:
=GoogleClock()
EDIT to include old and new Google Sheets and change to =GoogleClock()
.
I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.
I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
Later in the ajax call I just asked for this property to know if I had an exception:
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
Hope this helps. Happy code! :P
Quick solution MySQL
By the way: I'm using MySQL PDO.
(1) In an auto increment table just get the highest value (my column name = id) from the incremented column once every script run first:
$select = "
SELECT MAX(id) AS maxid
FROM [tablename]
LIMIT 1
";
(2) Run the MySQL query as you normaly would, and cast the result to integer, e.g.:
$iMaxId = (int) $result[0]->maxid;
(3) After the "INSERT INTO ... ON DUPLICATE KEY UPDATE" query get the last inserted id your prefered way, e.g.:
$iLastInsertId = (int) $db->lastInsertId();
(4) Compare and react: If the lastInsertId is higher than the highest in the table, it's probably an INSERT, right? And vice versa.
if ($iLastInsertId > $iMaxObjektId) {
// IT'S AN INSERT
}
else {
// IT'S AN UPDATE
}
I know it's quick and maybe dirty. And it's an old post. But, hey, I was searching for a solution a for long time, and maybe somebody finds my way somewhat useful anyway. All the best!
Specifying the column type as serial for PostgreSQL to generate the id.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }
https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL
How about a one-liner using a list comprehension within join?
>>> foobar = "aaa bbb\t\t\tccc\nddd"
>>> print(foobar)
aaa bbb ccc
ddd
>>> print(''.join([c for c in foobar if c not in [' ', '\t', '\n']]))
aaabbbcccddd
In python or any other convert to bin string then split it with '0' to get rid of 0's then combine and get the length.
len(''.join(str(bin(122011)).split('0')))-1
This will may be the simplest answer one can find for the PCA including easily understandable steps. Let say we want to retain 2 principal dimensions from the 144 which provides maximum information.
Firstly, convert your 2-D array to a dataframe:
import pandas as pd
# Here X is your array of size (26424 x 144)
data = pd.DataFrame(X)
Then, there are two methods one can go with:
Method 1: Manual calculation
Step 1: Apply column standardization on X
from sklearn import preprocessing
scalar = preprocessing.StandardScaler()
standardized_data = scalar.fit_transform(data)
Step 2: Find Co-variance matrix S of original matrix X
sample_data = standardized_data
covar_matrix = np.cov(sample_data)
Step 3: Find eigen values and eigen vectors of S (here 2D, so 2 of each)
from scipy.linalg import eigh
# eigh() function will provide eigen-values and eigen-vectors for a given matrix.
# eigvals=(low value, high value) takes eigen value numbers in ascending order
values, vectors = eigh(covar_matrix, eigvals=(142,143))
# Converting the eigen vectors into (2,d) shape for easyness of further computations
vectors = vectors.T
Step 4: Transform the data
# Projecting the original data sample on the plane formed by two principal eigen vectors by vector-vector multiplication.
new_coordinates = np.matmul(vectors, sample_data.T)
print(new_coordinates.T)
This new_coordinates.T
will be of size (26424 x 2) with 2 principal components.
Method 2: Using Scikit-Learn
Step 1: Apply column standardization on X
from sklearn import preprocessing
scalar = preprocessing.StandardScaler()
standardized_data = scalar.fit_transform(data)
Step 2: Initializing the pca
from sklearn import decomposition
# n_components = numbers of dimenstions you want to retain
pca = decomposition.PCA(n_components=2)
Step 3: Using pca to fit the data
# This line takes care of calculating co-variance matrix, eigen values, eigen vectors and multiplying top 2 eigen vectors with data-matrix X.
pca_data = pca.fit_transform(sample_data)
This pca_data
will be of size (26424 x 2) with 2 principal components.
Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.
<?php
$script = <<< JS
$(function() {
// js code goes here
});
JS;
?>
After closing the heredoc construction the $script variable contains your JS code that can be used like this:
<script><?= $script ?></script>
The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.
It's printing out the actual, exact value of the double
.
Double.toString()
, which converts double
s to String
s, does not print the exact decimal value of the input -- if x
is your double value, it prints out exactly enough digits that x
is the closest double
to the value it printed.
The point is that there is no such double
as 47.48 exactly. Doubles store values as binary fractions, not as decimals, so it can't store exact decimal values. (That's what BigDecimal
is for!)
This worked for me:
// Change default JQuery validation Messages.
$("#addnewcadidateform").validate({
rules: {
firstname: "required",
lastname: "required",
email: "required email",
},
messages: {
firstname: "Enter your First Name",
lastname: "Enter your Last Name",
email: {
required: "Enter your Email",
email: "Please enter a valid email address.",
}
}
})
Update your node
and it will resolve this problem.
MySQL uses CONCAT() to concatenate strings
SELECT * FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)
I was having issue in the passed parameter. I passed integer from a for loop to the function and displayed it , but it always gave out different results. like (1,2,2,3) (1,2,3,3) (1,1,2,3) etc with ParametrizedThreadStart delegate.
this simple code worked as a charm
Thread thread = new Thread(Work);
thread.Start(Parameter);
private void Work(object param)
{
string Parameter = (string)param;
}
In my case, I was setting the adapter inside onLocationChanged()
callback AND debugging in the emulator. Since it didn't detected a location change it never fired. When I set them manually in the Extended controls of the emulator it worked as expected.
The answer of @NeplatnyUdaj is right but consider that Excel want the function name in the set language, in my case German. Then you need to use "DATUM" instead of "DATE":
=(((COLUMN_ID_HERE/60)/60)/24)+DATUM(1970,1,1)
My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.
If you're facing this issue in Flutter then you're good to go here.
Issue is indicating you're using .png as image asset. Just try to replace .png to .jpg and build your project again..!!
Use this plugin. - flutter_launcher_icons: ^0.8.1
flutter_icons:
android: "ic_launcher"
image_path_android: "assets/logo_panda.jpg"
ios: true
image_path_ios: "assets/logo_panda.jpg"
Make sure you're using the .jpg image extension as the image path.
This help me to upload the app to the App Store.
I've managed to get it working using curl:
curl -u <username>:<password> https://myrepo.example/v1/repositories/<username>/<image_name>/tags
Note that image_name
should not contain user details etc. For example if you're pushing image named myrepo.example/username/x
then image_name
should be x
.
This is a very old question, but I found a new solution, so I wrote about it.
First of all, is this way of solution possible while using AutoGenerateColumns?
Yes, that can be done with AttachedProperty as follows.
<DataGrid AutoGenerateColumns="True"
local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
ItemsSource="{Binding}" />
There are two AttachedProperty defined that allow you to specify two formats.
DateTimeFormatAutoGenerate
for DateTime
and TimeSpanFormatAutoGenerate
for TimeSpan
.
class DataGridOperation
{
public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));
public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));
private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is DataGrid dGrid))
return;
if ((e.NewValue is string format))
dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
}
private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
{
if (e.PropertyType == typeof(T))
(e.Column as DataGridTextColumn).Binding.StringFormat = format;
}
}
<Window
x:Class="DataGridAutogenerateCustom.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataGridAutogenerateCustom"
Width="400" Height="250">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<StackPanel>
<TextBlock Text="DEFAULT FORMAT" />
<DataGrid ItemsSource="{Binding Dates}" />
<TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
<DataGrid
local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
ItemsSource="{Binding Dates}" />
</StackPanel>
</Window>
public class MainWindowViewModel
{
public DatePairs[] Dates { get; } = new DatePairs[]
{
new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
};
}
public class DatePairs
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public TimeSpan Span => EndDate - StartDate;
}
What do you want to validate? The email address?
The email address can only be checked for its format conformance. See the standard: RFC2822. Best way to do that is a regular expression. You will never know if really exists without sending an email.
I checked the commons validator. It contains an org.apache.commons.validator.EmailValidator class. Seems to be a good starting point.
Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(
There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.
Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.
With the current search facility brackets of any form () {} []
are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb)
and [aaa|bbb]
are equivalent and will both find words aaa
or bbb
. Most other punctuation characters, including \
, are treated as a space or a word-separator, +
-
:
and "
do have special meaning though, see the help.
As of 2016, only the form "{term1 term2}
" is documented for this, and is equivalent to the search "term1 OR term2
".
You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor
to get the complete source).
You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.
For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected]
it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]
. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
public static TreeMap<String, String> sortMap(HashMap<String, String> passedMap, String byParam) {
if(byParam.trim().toLowerCase().equalsIgnoreCase("byValue")) {
// Altering the (key, value) -> (value, key)
HashMap<String, String> newMap = new HashMap<String, String>();
for (Map.Entry<String, String> entry : passedMap.entrySet()) {
newMap.put(entry.getValue(), entry.getKey());
}
return new TreeMap<String, String>(newMap);
}
return new TreeMap<String, String>(passedMap);
}
Whether or not YouTube videos play in HTML5 format depends on the setting at https://www.youtube.com/html5, per browser. Chrome prefers HTML5 playback automatically, but even the latest Firefox and Internet Explorer still use Flash if it is installed on the machine.
The parameter html5=1 does not do anything (anymore) now. (Note it is not even listed at https://developers.google.com/youtube/player_parameters.)
This problem arises when you have a custom class that extends a different class (in this case a view) and does not import all the constructors required by the class.
For eg : public class CustomTextView extends TextView{}
This class would have 4 constructors and if you miss out on any one it would crash. For the matter of fact I missed out the last one which was used by Lollipop added that constructor and worked fine.
if your bundle id carried a capital letter and you've changed it to a lower case letter, you must run the application in the simulator before attempting to archive and upload to app store connect (this was the issue and solution for me).
//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)
if you are developing QGIS plugins then simply
self.dlg.cbo_load_net.currentIndex()
Made a category like mxcl, but this is slightly faster.
My testing shows ~15% improvement (I could be wrong, feel free to compare the two yourself).
Basically I take the portion of the array thats in front of the object and the portion behind and combine them. Thus excluding the element.
- (NSArray *)prefix_arrayByRemovingObject:(id)object
{
if (!object) {
return self;
}
NSUInteger indexOfObject = [self indexOfObject:object];
NSArray *firstSubArray = [self subarrayWithRange:NSMakeRange(0, indexOfObject)];
NSArray *secondSubArray = [self subarrayWithRange:NSMakeRange(indexOfObject + 1, self.count - indexOfObject - 1)];
NSArray *newArray = [firstSubArray arrayByAddingObjectsFromArray:secondSubArray];
return newArray;
}
In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.
If you're doing this in the context of a asp.Net Core API action, the conversion to Json is done implicitly.
[HttpGet]
public ActionResult Get()
{
return Ok(TheList);
}
In my case, my Comodo firewall had sandboxed the ssh agent. Once I disabled sandboxing I was able to clone the repository.
FYI, I am using Comodo firewall on Windows 7.
open dconf Editor and go to org > gnome > desktop > application > terminal and change gnome-terminal to terminator
Use nc command,
nc -zv <hostname/ip> <port/port range>
For example,
nc -zv localhost 27017-27019
or
nc -zv localhost 27017
You can also use telnet command
telnet <ip/host> port
From the Aspose Cells forums: How to use new line char with in a cell?
After you supply text you should set the cell's IsTextWrapped style to true
worksheet.Cells[0, 0].Style.WrapText = true;
Run php
in lint mode from the command line to validate syntax without execution:
php -l FILENAME
Higher-level static analyzers include:
Lower-level analyzers include:
Runtime analyzers, which are more useful for some things due to PHP's dynamic nature, include:
The documentation libraries phpdoc and Doxygen perform a kind of code analysis. Doxygen, for example, can be configured to render nice inheritance graphs with Graphviz.
Another option is xhprof, which is similar to Xdebug, but lighter, making it suitable for production servers. The tool includes a PHP-based interface.
REST webservice: (http://localhost:8080/your-app/rest/data/post)
package com.yourorg.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/data")
public class JSONService {
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Data post: "+data;
return Response.status(201).entity(result).build();
}
Client send a post:
package com.yourorg.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");
String input = "{\"message\":\"Hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
The one I used to use was:
git log | grep "^commit" | wc -l
Simple but it worked.
OUTDATED See Lukas Eder's answer below.
With about 100 lines of code ;-) Here is an example.
The main point: Unlike with other JDBC drivers, the one from Oracle doesn't support using Reader
and InputStream
as parameters of an INSERT
. Instead, you must SELECT
the CLOB
column FOR UPDATE
and then write into the ResultSet
I suggest that you move this code into a helper method/class. Otherwise, it will pollute the rest of your code.
I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:
df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)
I heard Jeff/Joel talk about this on the podcast today (episode 34, 2008-12-16 (MP3, 31 MB), 1 h 03 min 38 secs - 1 h 06 min 45 secs), and I thought I recalled Stack Overflow was using LINQ to SQL, but maybe it was ditched. Here's the same thing in LINQ to SQL.
var inValues = new [] { "ruby","rails","scruffy","rubyonrails" };
var results = from tag in Tags
where inValues.Contains(tag.Name)
select tag;
That's it. And, yes, LINQ already looks backwards enough, but the Contains
clause seems extra backwards to me. When I had to do a similar query for a project at work, I naturally tried to do this the wrong way by doing a join between the local array and the SQL Server table, figuring the LINQ to SQL translator would be smart enough to handle the translation somehow. It didn't, but it did provide an error message that was descriptive and pointed me towards using Contains.
Anyway, if you run this in the highly recommended LINQPad, and run this query, you can view the actual SQL that the SQL LINQ provider generated. It'll show you each of the values getting parameterized into an IN
clause.
In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.
It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.
As a note for the future: if you need a sentence parsed out and tag it as linguistics
(and syntax
or whatnot, if that's available), someone can probably parse it out for you and guide you through it.
Remember that a multi-dimensional array is like a table. You don't have an x element and a y element for each entry; you have a string at (for instance) table[1,2]
.
So, each entry is still only one string (in your example), it's just an entry at a specific x/y value. So, to get both entries at table[1, x]
, you'd do a nested for loop. Something like the following (not tested, but should be close)
for (int x = 0; x < table.Length; x++)
{
for (int y = 0; y < table.Length; y += 2)
{
Console.WriteLine("{0} {1}", table[x, y], table[x, y + 1]);
}
}
Here's a rewrite of the accepted answer that ideally clarifies the advantages/risks of possible approaches:
You're trying to cherry pick fd9f578, which was a merge with two parents.
Instead of cherry-picking a merge, the simplest thing is to cherry pick the commit(s) you actually want from each branch in the merge.
Since you've already merged, it's likely all your desired commits are in your list. Cherry-pick them directly and you don't need to mess with the merge commit.
The way a cherry-pick works is by taking the diff that a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying the changeset to your current branch.
If a commit has two or more parents, as is the case with a merge, that commit also represents two or more diffs. The error occurs because of the uncertainty over which diff should apply.
If you determine you need to include the merge vs cherry-picking the related commits, you have two options:
(More complicated and obscure; also discards history) you can indicate which parent should apply.
Use the -m
option to do so. For example, git cherry-pick -m 1 fd9f578
will use the first parent listed in the merge as the base.
Also consider that when you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
(Simpler and more familiar; preserves history) you can use git merge
instead of git cherry-pick
.
git merge
, it will attempt to apply all commits that exist on the branch you are merging, and list them individually in your git log.There is no mention about nine-patch files here. Yes, you have to create the file, however it's quite easy job and it's really "cross-version and transparency supporting" solution. If the file is placed to the drawable-nodpi
directory, it works px
based, and in the drawable-mdpi
works approximately as dp base (thanks to resample).
Example file for the original question (border-right:1px solid red;) is here:
Just place it to the drawable-nodpi
directory.
You could just do it like this
$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
foreach($result_select as $row){
$ename = stripslashes($row['name']);
$eemail = stripcslashes($row['email']);
$epost = stripslashes($row['post']);
$eid = $row['id'];
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";
echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');
echo $eid . '<br/>';
echo $ename . '<br/>';
echo $eemail . '<br/>';
echo $epost . '<br/><br/><br/><br/>';
}
use this to catch the exception details:
String stackTrace = Log.getStackTraceString(exception);
store this in database and maintain the log.
Make sure the format of the cell is set to 'general' not 'text' (right click on cell and choose format cell)
Formula should look something like this:
=1+2
A JAR file extension is .jar and is created with jar command from command prompt (like javac command is executed). Generally, a JAR file contains Java related resources like libraries, classes etc.JAR file is like winzip file except that Jar files are platform independent.
A WAR file is simply a JAR file but contains only Web related Java files like Servlets, JSP, HTML.
To execute a WAR file, a Web server or Web container is required, for example, Tomcat or Weblogic or Websphere. To execute a JAR file, simple JDK is enough.
Some of the other answers here inspired me to write a script for automating the mixed sequential execution of SQL tasks using SQLPLUS along with shell commands for a project, a process that was previously manually done. Maybe this (highly sanitized) example will be useful to someone else:
#!/bin/bash
acreds="user_a/supergreatpassword"
bcreds="user_b/anothergreatpassword"
hoststring='fancyoraclehoststring'
runsql () {
# param 1 is $1
sqlplus -S /nolog << EOF
CONNECT $1@$hoststring;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
$2
exit;
EOF
}
echo "TS::$(date): Starting SCHEM_A.PROC_YOU_NEED()..."
runsql "$acreds" "execute SCHEM_A.PROC_YOU_NEED();"
echo "TS::$(date): Starting superusefuljob..."
/var/scripts/superusefuljob.sh
echo "TS::$(date): Starting SCHEM_B.SECRET_B_PROC()..."
runsql "$bcreds" "execute SCHEM_B.SECRET_B_PROC();"
echo "TS::$(date): DONE"
runsql
allows you to pass a credential string as the first argument, and any SQL you need as the second argument. The variables containing the credentials are included for illustration, but for security I actually source them from another file. If you wanted to handle multiple database connections, you could easily modify the function to accept the hoststring as an additional parameter.
Had the same problem when Load external without cache using Javascript
Load external <script> without cache using Javascript
Had a good solution for cache problem here:
But this happend: Uncaught TypeError: Cannot read property 'appendChild' of null.
Here is good explanation: https://stackoverflow.com/a/58824439/14491024
As it said your script tag is in the head, the JavaScript is loaded before your HTML.
In Visual Studio by C# this problem is solved like this by adding Guid:
Here is how it looks in the View page source:
In a few words: The constructor is called first, then any @FXML
annotated fields are populated, then initialize()
is called.
This means the constructor does not have access to @FXML
fields referring to components defined in the .fxml file, while initialize()
does have access to them.
Quoting from the Introduction to FXML:
[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.
So the suggested answer from TheHippo did not work for me, instead I ended up sending the form as a parameter to the function like so:
<form name="loginform" novalidate ng-submit="login.submit(loginForm)" class="css-form">
This makes the form available in the controller method:
$scope.login = {
submit : function(form) {
if(form.$valid)....
}
(This answer was updated, as the previous method using vq
isn't recognized anymore.)
Specifying the height of the video will change the quality accordingly. example for html 5;
<iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe>
If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.
Tested on a working server + passes the w3.org nuhtml validator.
You can turn on your PHP errors with error_reporting
:
error_reporting(E_ALL);
ini_set('display_errors', 'on');
Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:
Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.
You should set display_errors = 1
in your php.ini
file and restart the server.
If you want to have this work with images of any height and without fixing the height, just do this:
$('#myCarousel').on("slide.bs.carousel", function(){
$(".carousel-control",this).css('top',($(".active img",this).height()*0.46)+'px');
$(this).off("slide.bs.carousel");
});
Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout
like below:
[Violation] 'setTimeout' handler took 43129ms
That number (43129ms) depends on how long you stop in your async function
If using Django, you can use the timezone.localtime
method:
from django.utils import timezone
date
# datetime.datetime(2014, 8, 1, 20, 15, 0, 513000, tzinfo=<UTC>)
timezone.localtime(date)
# datetime.datetime(2014, 8, 1, 16, 15, 0, 513000, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
.g-recaptcha{
-moz-transform:scale(1.1);
-ms-transform:scale(1.1);
-o-transform:scale(1.1);
-moz-transform-origin:0;
-ms-transform-origin:0;
-o-transform-origin:0;
-webkit-transform:scale(1.1);
transform:scale(1.1);
-webkit-transform-origin:0 0;
transform-origin:0;
filter: progid:DXImageTransform.Microsoft.Matrix(M11=1.1,M12=0,M21=0,M22=1.1,SizingMethod='auto expand');
}
Is this solution ok?
int[] a = { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
Integer count = map.get(i);
map.put(i, count != null ? count + 1 : 0);
}
Integer max = Collections.max(map.keySet());
System.out.println(max);
System.out.println(map);
This happened to me because I had moved the following line close to the beginning of the .csproj file:
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>
It needs to be placed after the PropertyGroups that define your Configuration|Platform.
Even if this question is a little older:
If you want to use if cond1 or cond 2
- you should not use complicated loops or stuff like that.
Simple provide both ifs
after each other combined with goto
- that's an implicit or.
//thats an implicit IF cond1 OR cond2 OR cond3
if cond1 GOTO doit
if cond2 GOTO doit
if cond3 GOTO doit
//thats our else.
GOTO end
:doit
echo "doing it"
:end
Without goto but an "inplace" action, you might execute the action 3 times, if ALL conditions are matching.
For xcode 8.3.3 I just checked tried the above code and observe that, now in this casewe have to change the commands to like this
first you can create a .gitignore file by using
touch .gitignore
after that you can delete all the userInterface file by using this command and by using this command it will respect your .gitignore file.
git rm --cached [project].xcworkspace/xcuserdata/[username].xcuserdatad/UserInterfaceState.xcuserstate
git commit -m "Removed file that shouldn't be tracked"
You have to let the compiler know where the mysql.h file can be found. This can be done by giving the path to the header before compiling. In IDEs you have a setting where you can give these paths.
This link gives you more info on what options to use while compiling.
To your second problem You need to link the libraries. The linker needs to know where the library files are which has the implementation for the mysql functions that you use.
This link gives you more info on how to link libraries.
The answer of @alexandre with base64 does the trick.
The explanation why that works for IE is here
https://en.m.wikipedia.org/wiki/Data_URI_scheme
Under header 'format' where it says
Some browsers (Chrome, Opera, Safari, Firefox) accept a non-standard ordering if both ;base64 and ;charset are supplied, while Internet Explorer requires that the charset's specification must precede the base64 token.
You have your storyboard set up to expect an outlet called tableView
but the actual outlet name is myTableView
.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
you can add the username and password to the SOAP Header
BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"your end point"));
Map<String, List<String>> headers = new HashMap<String, List<String>>();
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
prov.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers);
I took aberke's solution and modified it to suit my taste.
My Code Pen
var myApp = angular.module('myApp', []);_x000D_
_x000D_
myApp.controller('exampleController',_x000D_
function exampleController($scope) {_x000D_
$scope.user = { profile: {HomePhone: '(719) 465-0001 x1234'}};_x000D_
$scope.homePhonePrompt = "Home Phone";_x000D_
});_x000D_
_x000D_
myApp_x000D_
/*_x000D_
Intended use:_x000D_
<phone-number placeholder='prompt' model='someModel.phonenumber' />_x000D_
Where: _x000D_
someModel.phonenumber: {String} value which to bind formatted or unformatted phone number_x000D_
_x000D_
prompt: {String} text to keep in placeholder when no numeric input entered_x000D_
*/_x000D_
.directive('phoneNumber',_x000D_
['$filter',_x000D_
function ($filter) {_x000D_
function link(scope, element, attributes) {_x000D_
_x000D_
// scope.inputValue is the value of input element used in template_x000D_
scope.inputValue = scope.phoneNumberModel;_x000D_
_x000D_
scope.$watch('inputValue', function (value, oldValue) {_x000D_
_x000D_
value = String(value);_x000D_
var number = value.replace(/[^0-9]+/g, '');_x000D_
scope.inputValue = $filter('phoneNumber')(number, scope.allowExtension);_x000D_
scope.phoneNumberModel = scope.inputValue;_x000D_
});_x000D_
}_x000D_
_x000D_
return {_x000D_
link: link,_x000D_
restrict: 'E',_x000D_
replace: true,_x000D_
scope: {_x000D_
phoneNumberPlaceholder: '@placeholder',_x000D_
phoneNumberModel: '=model',_x000D_
allowExtension: '=extension'_x000D_
},_x000D_
template: '<input ng-model="inputValue" type="tel" placeholder="{{phoneNumberPlaceholder}}" />'_x000D_
};_x000D_
}_x000D_
]_x000D_
)_x000D_
/* _x000D_
Format phonenumber as: (aaa) ppp-nnnnxeeeee_x000D_
or as close as possible if phonenumber length is not 10_x000D_
does not allow country code or extensions > 5 characters long_x000D_
*/_x000D_
.filter('phoneNumber', _x000D_
function() {_x000D_
return function(number, allowExtension) {_x000D_
/* _x000D_
@param {Number | String} number - Number that will be formatted as telephone number_x000D_
Returns formatted number: (###) ###-#### x #####_x000D_
if number.length < 4: ###_x000D_
else if number.length < 7: (###) ###_x000D_
removes country codes_x000D_
*/_x000D_
if (!number) {_x000D_
return '';_x000D_
}_x000D_
_x000D_
number = String(number);_x000D_
number = number.replace(/[^0-9]+/g, '');_x000D_
_x000D_
// Will return formattedNumber. _x000D_
// If phonenumber isn't longer than an area code, just show number_x000D_
var formattedNumber = number;_x000D_
_x000D_
// if the first character is '1', strip it out _x000D_
var c = (number[0] == '1') ? '1 ' : '';_x000D_
number = number[0] == '1' ? number.slice(1) : number;_x000D_
_x000D_
// (###) ###-#### as (areaCode) prefix-endxextension_x000D_
var areaCode = number.substring(0, 3);_x000D_
var prefix = number.substring(3, 6);_x000D_
var end = number.substring(6, 10);_x000D_
var extension = number.substring(10, 15);_x000D_
_x000D_
if (prefix) {_x000D_
//formattedNumber = (c + "(" + area + ") " + front);_x000D_
formattedNumber = ("(" + areaCode + ") " + prefix);_x000D_
}_x000D_
if (end) {_x000D_
formattedNumber += ("-" + end);_x000D_
}_x000D_
if (allowExtension && extension) {_x000D_
formattedNumber += ("x" + extension);_x000D_
}_x000D_
return formattedNumber;_x000D_
};_x000D_
}_x000D_
);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="myApp" ng-controller="exampleController">_x000D_
<p>Phone Number Value: {{ user.profile.HomePhone || 'null' }}</p>_x000D_
<p>Formatted Phone Number: {{ user.profile.HomePhone | phoneNumber }}</p>_x000D_
<phone-number id="homePhone"_x000D_
class="form-control" _x000D_
placeholder="Home Phone" _x000D_
model="user.profile.HomePhone"_x000D_
ng-required="!(user.profile.HomePhone.length || user.profile.BusinessPhone.length || user.profile.MobilePhone.length)" />_x000D_
</div>
_x000D_
I solved my problem with changing "TabIndex" property of TextBox. I set 0 for TextBox that I want to focus it on Form when the program start.
Using Visual Studio 2015 adding the additional parameter
/deployonbuild=false
to the msbuild command line fixed the issue.
In CSharp, If you create the method/function outline with it's Parms, then when you add the three forward slashes it will auto generate the summary and parms section.
So I put in:
public string myMethod(string sImput1, int iInput2)
{
}
I then put the three /// before it and Visual Studio's gave me this:
/// <summary>
///
/// </summary>
/// <param name="sImput1"></param>
/// <param name="iInput2"></param>
/// <returns></returns>
public string myMethod(string sImput1, int iInput2)
{
}
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):
$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );
So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:
$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );
Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,
The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.
That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.
find . -type f -name '*php' -o -name '*js' -o -name '*html' |\
xargs grep -liE 'document\.cookie|setcookie'
function SingletonClass()
{
// demo variable
var names = [];
// instance of the singleton
this.singletonInstance = null;
// Get the instance of the SingletonClass
// If there is no instance in this.singletonInstance, instanciate one
var getInstance = function() {
if (!this.singletonInstance) {
// create a instance
this.singletonInstance = createInstance();
}
// return the instance of the singletonClass
return this.singletonInstance;
}
// function for the creation of the SingletonClass class
var createInstance = function() {
// public methodes
return {
add : function(name) {
names.push(name);
},
names : function() {
return names;
}
}
}
// wen constructed the getInstance is automaticly called and return the SingletonClass instance
return getInstance();
}
var obj1 = new SingletonClass();
obj1.add("Jim");
console.log(obj1.names());
// prints: ["Jim"]
var obj2 = new SingletonClass();
obj2.add("Ralph");
console.log(obj1.names());
// Ralph is added to the singleton instance and there for also acceseble by obj1
// prints: ["Jim", "Ralph"]
console.log(obj2.names());
// prints: ["Jim", "Ralph"]
obj1.add("Bart");
console.log(obj2.names());
// prints: ["Jim", "Ralph", "Bart"]
this can be achieved with the css calc()
operator
@media screen and (min-width: 480px) {
body {
background-color: lightgreen;
zoom:calc(100% / 480);
}
}
Here's what I've got so far (found it on the page Ben Alpert mentioned):
SELECT REPLACE(
SUBSTRING(
SUBSTRING_INDEX(c.`courseNames`, ',', e.`courseId` + 1)
, LENGTH(SUBSTRING_INDEX(c.`courseNames`, ',', e.`courseId`)
) + 1)
, ','
, ''
)
FROM `clients` c INNER JOIN `clientenrols` e USING (`clientId`)
A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.
The most commonly used type parameter names are:
In Java 7 it is permitted to instantiate like this:
Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6
df.shape
, where df
is your DataFrame.
One liner to disable scrolling including middle mouse button.
$(document).scroll(function () { $(document).scrollTop(0); });
edit: There's no need for jQuery anyway, below same as above in vanilla JS(that means no frameworks, just JavaScript):
document.addEventListener('scroll', function () { this.documentElement.scrollTop = 0; this.body.scrollTop = 0; })
this.documentElement.scrollTop - standard
this.body.scrollTop - IE compatibility
Here cplusplus example is an example how to use colors in console.
Your regular expression should be \btrue\b
to get around the 'miscontrue' issue Casper brings up. The full solution would look like this:
string searchText = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
string regexPattern = @"\btrue\b";
int numberOfTrues = Regex.Matches(searchText, regexPattern).Count;
Make sure the System.Text.RegularExpressions namespace is included at the top of the file.
When I want to have docstrings for my bash functions, I use a solution similar to the suggestion of user12205 in a duplicate of this question.
See how I define USAGE for a solution that:
function foo {
# Docstring
read -r -d '' USAGE <<' END'
# This method prints foo to the terminal.
#
# Enter `foo -h` to see the docstring.
# It has indentations and multiple lines.
#
# Change the delimiter if you need hashtag for some reason.
# This can include $$ and = and eval, but won't be evaluated
END
if [ "$1" = "-h" ]
then
echo "$USAGE" | cut -d "#" -f 2 | cut -c 2-
return
fi
echo "foo"
}
So foo -h
yields:
This method prints foo to the terminal.
Enter `foo -h` to see the docstring.
It has indentations and multiple lines.
Change the delimiter if you need hashtag for some reason.
This can include $$ and = and eval, but won't be evaluated
Explanation
cut -d "#" -f 2
: Retrieve the second portion of the #
delimited lines. (Think a csv with "#" as the delimiter, empty first column).
cut -c 2-
: Retrieve the 2nd to end character of the resultant string
Also note that if [ "$1" = "-h" ]
evaluates as False
if there is no first argument, w/o error, since it becomes an empty string.
Not sure if this is the best way to do it, but this makes the spinners disappear on Chrome 8.0.552.5 dev:
input[type=number]::-webkit-inner-spin-button {
-webkit-appearance: none;
}
After trying several things, this worked for me:
With addresses other than 0.0.0.0
I had no success.
Inside the function parameter list, char arr[]
is absolutely equivalent to char *arr
, so the pair of definitions and the pair of declarations are equivalent.
void function(char arr[]) { ... }
void function(char *arr) { ... }
void function(char arr[]);
void function(char *arr);
The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.
Treat string literals as if they were static const char literal[] = "string literal";
and do not attempt to modify them.
For integers:
public class Division {
public static void main(String[] args) {
System.out.println("Division: " + divide(100, 9));
}
public static int divide(int num, int divisor) {
int sign = 1;
if((num > 0 && divisor < 0) || (num < 0 && divisor > 0))
sign = -1;
return divide(Math.abs(num), Math.abs(divisor), Math.abs(divisor)) * sign;
}
public static int divide(int num, int divisor, int sum) {
if (sum > num) {
return 0;
}
return 1 + divide(num, divisor, sum + divisor);
}
}
The best way to load an image is through the ImageIO
API
BufferedImage img = ImageIO.read(new File("/path/to/some/image"));
There are a number of ways you can render an image to the screen.
You could use a JLabel
. This is the simplest method if you don't want to modify the image in anyway...
JLabel background = new JLabel(new ImageIcon(img));
Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.
If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.
First cavert: Don't ever paint directly to a top level container (like JFrame
). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...
Instead, create a custom component, extending from something like JPanel
. Override it's paintComponent
method and render your output to it, for example...
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, this);
}
Take a look at Performing Custom Painting and 2D Graphics for more details
If you want to use the catch()
of the Observable
you need to use Observable.throw()
method before delegating the error response to a method
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
constructor(private http: AuthHttp) {}_x000D_
_x000D_
envirArquivos(order): Observable < any > {_x000D_
const headers = new Headers();_x000D_
return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
new ResponseOptions({_x000D_
headers: headers_x000D_
}))_x000D_
.map(response => response.json())_x000D_
.catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
}_x000D_
_x000D_
errorHandler(error: any): void {_x000D_
console.log(error)_x000D_
}_x000D_
}
_x000D_
Using Observable.throw()
worked for me
Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.
You take that string, call it $place_older
say. And then when you want to eliminate the text, you call quotemeta
, and you use that value to substitute:
my $subs = quotemeta $place_holder;
s/$subs//g;
Just had to fix this myself. The above answers don't seem to take into account the
$mail->SMTPDebug = 0;
option. It may not have been available when the question was first asked.
If you got your code from the PHPMail site, the default will be
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
https://github.com/Synchro/PHPMailer/blob/master/examples/test_smtp_gmail_advanced.php
Set the value to 0 to suppress the errors and edit the 'catch' part of your code as explained above.
I had a similar issue and found that it was much simpler to to get rid of the Excel files as soon as possible. As part of the first steps in my package I used Powershell to extract the data out of the Excel files into CSV files. My own Excel files were simple but here
Extract and convert all Excel worksheets into CSV files using PowerShell
is an excellent article by Tim Smith on extracting data from multiple Excel files and/or multiple sheets.
Once the Excel files have been converted to CSV the data import is much less complicated.
You can also try this:
var data= _.reverse(_.sortBy(res.locals.subscriptionList.items, ['type', 'name']));
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
use copy() and unlink() function
$moveFile="path/filename";
if (copy($csvFile,$moveFile))
{
unlink($csvFile);
}
Since your problem is to downscale your image, there is no point in talking about interpolation -which is about creating pixel-. The issue here is downsampling.
To downsample an image, we need to turn each square of p * p pixels in the original image into a single pixel in the destination image.
For performances reasons Browsers do a very simple downsampling : to build the smaller image, they will just pick ONE pixel in the source and use its value for the destination. which 'forgets' some details and adds noise.
Yet there's an exception to that : since the 2X image downsampling is very simple to compute (average 4 pixels to make one) and is used for retina/HiDPI pixels, this case is handled properly -the Browser does make use of 4 pixels to make one-.
BUT... if you use several time a 2X downsampling, you'll face the issue that the successive rounding errors will add too much noise.
What's worse, you won't always resize by a power of two, and resizing to the nearest power + a last resizing is very noisy.
What you seek is a pixel-perfect downsampling, that is : a re-sampling of the image that will take all input pixels into account -whatever the scale-.
To do that we must compute, for each input pixel, its contribution to one, two, or four destination pixels depending wether the scaled projection of the input pixels is right inside a destination pixels, overlaps an X border, an Y border, or both.
( A scheme would be nice here, but i don't have one. )
Here's an example of canvas scale vs my pixel perfect scale on a 1/3 scale of a zombat.
Notice that the picture might get scaled in your Browser, and is .jpegized by S.O..
Yet we see that there's much less noise especially in the grass behind the wombat, and the branches on its right. The noise in the fur makes it more contrasted, but it looks like he's got white hairs -unlike source picture-.
Right image is less catchy but definitively nicer.
Here's the code to do the pixel perfect downscaling :
fiddle result :
http://jsfiddle.net/gamealchemist/r6aVp/embedded/result/
fiddle itself : http://jsfiddle.net/gamealchemist/r6aVp/
// scales the image by (float) scale < 1
// returns a canvas containing the scaled image.
function downScaleImage(img, scale) {
var imgCV = document.createElement('canvas');
imgCV.width = img.width;
imgCV.height = img.height;
var imgCtx = imgCV.getContext('2d');
imgCtx.drawImage(img, 0, 0);
return downScaleCanvas(imgCV, scale);
}
// scales the canvas by (float) scale < 1
// returns a new canvas containing the scaled image.
function downScaleCanvas(cv, scale) {
if (!(scale < 1) || !(scale > 0)) throw ('scale must be a positive number <1 ');
var sqScale = scale * scale; // square scale = area of source pixel within target
var sw = cv.width; // source image width
var sh = cv.height; // source image height
var tw = Math.floor(sw * scale); // target image width
var th = Math.floor(sh * scale); // target image height
var sx = 0, sy = 0, sIndex = 0; // source x,y, index within source array
var tx = 0, ty = 0, yIndex = 0, tIndex = 0; // target x,y, x,y index within target array
var tX = 0, tY = 0; // rounded tx, ty
var w = 0, nw = 0, wx = 0, nwx = 0, wy = 0, nwy = 0; // weight / next weight x / y
// weight is weight of current source point within target.
// next weight is weight of current source point within next target's point.
var crossX = false; // does scaled px cross its current px right border ?
var crossY = false; // does scaled px cross its current px bottom border ?
var sBuffer = cv.getContext('2d').
getImageData(0, 0, sw, sh).data; // source buffer 8 bit rgba
var tBuffer = new Float32Array(3 * tw * th); // target buffer Float32 rgb
var sR = 0, sG = 0, sB = 0; // source's current point r,g,b
/* untested !
var sA = 0; //source alpha */
for (sy = 0; sy < sh; sy++) {
ty = sy * scale; // y src position within target
tY = 0 | ty; // rounded : target pixel's y
yIndex = 3 * tY * tw; // line index within target array
crossY = (tY != (0 | ty + scale));
if (crossY) { // if pixel is crossing botton target pixel
wy = (tY + 1 - ty); // weight of point within target pixel
nwy = (ty + scale - tY - 1); // ... within y+1 target pixel
}
for (sx = 0; sx < sw; sx++, sIndex += 4) {
tx = sx * scale; // x src position within target
tX = 0 | tx; // rounded : target pixel's x
tIndex = yIndex + tX * 3; // target pixel index within target array
crossX = (tX != (0 | tx + scale));
if (crossX) { // if pixel is crossing target pixel's right
wx = (tX + 1 - tx); // weight of point within target pixel
nwx = (tx + scale - tX - 1); // ... within x+1 target pixel
}
sR = sBuffer[sIndex ]; // retrieving r,g,b for curr src px.
sG = sBuffer[sIndex + 1];
sB = sBuffer[sIndex + 2];
/* !! untested : handling alpha !!
sA = sBuffer[sIndex + 3];
if (!sA) continue;
if (sA != 0xFF) {
sR = (sR * sA) >> 8; // or use /256 instead ??
sG = (sG * sA) >> 8;
sB = (sB * sA) >> 8;
}
*/
if (!crossX && !crossY) { // pixel does not cross
// just add components weighted by squared scale.
tBuffer[tIndex ] += sR * sqScale;
tBuffer[tIndex + 1] += sG * sqScale;
tBuffer[tIndex + 2] += sB * sqScale;
} else if (crossX && !crossY) { // cross on X only
w = wx * scale;
// add weighted component for current px
tBuffer[tIndex ] += sR * w;
tBuffer[tIndex + 1] += sG * w;
tBuffer[tIndex + 2] += sB * w;
// add weighted component for next (tX+1) px
nw = nwx * scale
tBuffer[tIndex + 3] += sR * nw;
tBuffer[tIndex + 4] += sG * nw;
tBuffer[tIndex + 5] += sB * nw;
} else if (crossY && !crossX) { // cross on Y only
w = wy * scale;
// add weighted component for current px
tBuffer[tIndex ] += sR * w;
tBuffer[tIndex + 1] += sG * w;
tBuffer[tIndex + 2] += sB * w;
// add weighted component for next (tY+1) px
nw = nwy * scale
tBuffer[tIndex + 3 * tw ] += sR * nw;
tBuffer[tIndex + 3 * tw + 1] += sG * nw;
tBuffer[tIndex + 3 * tw + 2] += sB * nw;
} else { // crosses both x and y : four target points involved
// add weighted component for current px
w = wx * wy;
tBuffer[tIndex ] += sR * w;
tBuffer[tIndex + 1] += sG * w;
tBuffer[tIndex + 2] += sB * w;
// for tX + 1; tY px
nw = nwx * wy;
tBuffer[tIndex + 3] += sR * nw;
tBuffer[tIndex + 4] += sG * nw;
tBuffer[tIndex + 5] += sB * nw;
// for tX ; tY + 1 px
nw = wx * nwy;
tBuffer[tIndex + 3 * tw ] += sR * nw;
tBuffer[tIndex + 3 * tw + 1] += sG * nw;
tBuffer[tIndex + 3 * tw + 2] += sB * nw;
// for tX + 1 ; tY +1 px
nw = nwx * nwy;
tBuffer[tIndex + 3 * tw + 3] += sR * nw;
tBuffer[tIndex + 3 * tw + 4] += sG * nw;
tBuffer[tIndex + 3 * tw + 5] += sB * nw;
}
} // end for sx
} // end for sy
// create result canvas
var resCV = document.createElement('canvas');
resCV.width = tw;
resCV.height = th;
var resCtx = resCV.getContext('2d');
var imgRes = resCtx.getImageData(0, 0, tw, th);
var tByteBuffer = imgRes.data;
// convert float32 array into a UInt8Clamped Array
var pxIndex = 0; //
for (sIndex = 0, tIndex = 0; pxIndex < tw * th; sIndex += 3, tIndex += 4, pxIndex++) {
tByteBuffer[tIndex] = Math.ceil(tBuffer[sIndex]);
tByteBuffer[tIndex + 1] = Math.ceil(tBuffer[sIndex + 1]);
tByteBuffer[tIndex + 2] = Math.ceil(tBuffer[sIndex + 2]);
tByteBuffer[tIndex + 3] = 255;
}
// writing result to canvas.
resCtx.putImageData(imgRes, 0, 0);
return resCV;
}
It is quite memory greedy, since a float buffer is required to store the intermediate values of the destination image (-> if we count the result canvas, we use 6 times the source image's memory in this algorithm).
It is also quite expensive, since each source pixel is used whatever the destination size, and we have to pay for the getImageData / putImageDate, quite slow also.
But there's no way to be faster than process each source value in this case, and situation is not that bad : For my 740 * 556 image of a wombat, processing takes between 30 and 40 ms.
There is a lot of really helpful info posted here, but there is one thing that all the posts seem to have wrong. I could not find any 'Settings' option under 'Files', and I hunted around for 10 minutes looking through all the menus until I found the settings under 'IntelliJ IDE' -> 'Preferences'.
I don't know if I am using a differing OS version or IntelliJ version from other posters, or if it is because I am a stupid Windows user that doesn't know that settings == preferences on a mac (Did I miss the memo?), but I hope this helps you if you aren't finding the paths that other posts are suggesting.
plt.errorbar
can be used to plot x, y, error data (as opposed to the usual plt.plot
)
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])
plt.errorbar(x, y, e, linestyle='None', marker='^')
plt.show()
plt.errorbar
accepts the same arguments as plt.plot
with additional yerr
and xerr
which default to None (i.e. if you leave them blank it will act as plt.plot
).
Try adding the option:
dataType: "json"
The second function's signature is identical to the Array.prototype.splice
method.
function mutate(s) {
return function splice() {
var a = s.split('');
Array.prototype.splice.apply(a, arguments);
return a.join('');
};
}
mutate('101')(1, 1, '1');
I know there's already an accepted answer, but hope this is useful.
The constructor of your A object allocates another object dynamically and stores a pointer to that dynamically allocated object in a raw pointer.
For that scenario, you must define your own copy constructor , assignment operator and destructor. The compiler generated ones will not work correctly. (This is a corollary to the "Law of the Big Three": A class with any of destructor, assignment operator, copy constructor generally needs all 3).
You have defined your own destructor (and you mentioned creating a copy constructor), but you need to define both of the other 2 of the big three.
An alternative is to store the pointer to your dynamically allocated int[]
in some other object that will take care of these things for you. Something like a vector<int>
(as you mentioned) or a boost::shared_array<>
.
To boil this down - to take advantage of RAII to the full extent, you should avoid dealing with raw pointers to the extent possible.
And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling delete
- delete
handles that case by doing nothing so you don't have to clutter you code with the checks.
$('#btnSubmit').click(function(){
alert("button");
});
or
//Use this code if button is appended in the DOM
$(document).on('click','#btnSubmit',function(){
alert("button");
});
See documentation for more information:
https://api.jquery.com/click/
This is working to me
'int numRows = dgbDatos.Rows.Count;
for (int i = 0; i < numRows; i++)
{
try
{
int max = dgbDatos.Rows.Count - 1;
dgbDatos.Rows.Remove(dgbDatos.Rows[max]);
btnAgregar.Enabled = true;
}
catch (Exception exe)
{
MessageBox.Show("No se puede eliminar " + exe, "",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}`
To get this working with YAML, do this:
property-name: '{
key1: "value1",
key2: "value2"
}'
If your array of numbers always is starting with 1 and ending with X then you could use the following formula: sum = x * (x+1) / 2
from 1 till 100 the sum would be 100 * 101 / 2 = 5050
Sometimes brew update
fails on me because one package doesn't download properly. So you can just upgrade a specific library like this:
brew upgrade node
If you are only calling APIs that do not require user data, such as the Google Custom Search API, then API keys might be simpler to use than OAuth 2.0 access tokens. However, if your application already uses an OAuth 2.0 access token, then there is no need to generate an API key as well. Google ignores passed API keys if a passed OAuth 2.0 access token is already associated with the corresponding project.
Note: You must use either an OAuth 2.0 access token or an API key for all requests to Google APIs represented in the Google Developers Console. Not all APIs require authorized calls. To learn whether authorization is required for a specific call, see your API documentation.
Reference: https://developers.google.com/console/help/new/?hl=en_US#credentials-access-security-and-identity
You remove the original image here:
newImg.animate(css, SPEED, function() {
img.remove();
newImg.removeClass('morpher');
(callback || function() {})();
});
And all that's left behind is newImg
. Then you reset link references the image using #rocket
:
$("#rocket").attr('src', ...
But your newImg
doesn't have an id
attribute let alone an id
of rocket
.
To fix this, you need to remove img
and then set the id
attribute of newImg
to rocket
:
newImg.animate(css, SPEED, function() {
var old_id = img.attr('id');
img.remove();
newImg.attr('id', old_id);
newImg.removeClass('morpher');
(callback || function() {})();
});
And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/
UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:
$("#resetlink").click(function(){
clearInterval(timerRocket);
$("#wrapper").css('top', '250px');
$('.throbber, .morpher').remove(); // Clear out the new stuff.
$("#rocket").show(); // Bring the original back.
});
And in the newImg.load
function, grab the images original size:
var orig = {
width: img.width(),
height: img.height()
};
And finally, the callback for finishing the morphing animation becomes this:
newImg.animate(css, SPEED, function() {
img.css(orig).hide();
(callback || function() {})();
});
New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/
The leaking of $('.throbber, .morpher')
outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.
I've figured out how to work around this issue without mixing parent and sub scope data.
Set a ng-if
on the the ng-include
element and set it to a scope variable.
For example :
<div ng-include="{{ template }}" ng-if="show"/>
In your controller, when you have set all the data you need in your sub scope, then set show to true
. The ng-include
will copy at this moment the data set in your scope and set it in your sub scope.
The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.
Max
to search every column of every table for a particular value
This does not define how to match exactly.
Nor does it define what to return exactly.
Assuming:
regclass
) and the tuple ID (ctid
), because that's simplest.Here is a dead simple, fast and slightly dirty way:
CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
FOR _tbl IN
SELECT c.oid::regclass
FROM pg_class c
JOIN pg_namespace n ON n.oid = relnamespace
WHERE c.relkind = 'r' -- only tables
AND n.nspname !~ '^(pg_|information_schema)' -- exclude system schemas
ORDER BY n.nspname, c.relname
LOOP
RETURN QUERY EXECUTE format(
'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
, _tbl, '%' || _like_pattern || '%')
USING _tbl;
END LOOP;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM search_whole_db('mypattern');
Provide the search pattern without enclosing %
.
Why slightly dirty?
If separators and decorators for the row in text
representation can be part of the search pattern, there can be false positives:
,
by default()
"
\
may be added as escape charAnd the text representation of some columns may depend on local settings - but that ambiguity is inherent to the question, not to my solution.
Each qualifying row is returned once only, even when it matches multiple times (as opposed to other answers here).
This searches the whole DB except for system catalogs. Will typically take a long time to finish. You might want to restrict to certain schemas / tables (or even columns) like demonstrated in other answers. Or add notices and a progress indicator, also demonstrated in another answer.
The regclass
object identifier type is represented as table name, schema-qualified where necessary to disambiguate according to the current search_path
:
What is the ctid
?
You might want to escape characters with special meaning in the search pattern. See:
malloc does not allocate on specific boundaries, so it must be assumed that it allocates on a byte boundary.
The returned pointer can then not be used if converted to any other type, since accessing that pointer will probably produce a memory access violation by the CPU, and the application will be immediately shut down.
You could always just use gcc via cygwin.
Instead of using the IP address from whatismyipaddress.com, what if you just get the IP address directly from the machine and plug that in? whatismyipaddress.com will give you the address of your router (I'm assuming you're on a home network). I don't think port forwarding will work since your request will come from within the network, not outside.
java -cp "full-path-of-your-jar" Main
to run any other class having "public static void main" in some package,
java -cp "full-path-of-your-jar" package1.package2.packages-hierarchy.ClassHavingMain
Description of the possible values:
left
: No floating elements allowed on the left sideright
: No floating elements allowed on the right sideboth
: No floating elements allowed on either the left or the right sidenone
: Default. Allows floating elements on both sidesinherit
: Specifies that the value of the clear property should be inherited from the parent element
Source: w3schools.com
Here's the script I use:
#!/bin/bash
IFS=$'\n\t'
set -euox pipefail
CNAME="$1"
FILE_PATH="$2"
TMPFILE="$(mktemp)"
docker exec "$CNAME" cat "$FILE_PATH" > "$TMPFILE"
$EDITOR "$TMPFILE"
cat "$TMPFILE" | docker exec -i "$CNAME" sh -c 'cat > '"$FILE_PATH"
rm "$TMPFILE"
and the gist for when I fix it but forget to update this answer: https://gist.github.com/dmohs/b50ea4302b62ebfc4f308a20d3de4213
For a project I'm working on, I wrote a simple ko.unapplyBindings
function that accepts a jQuery node and the remove boolean. It first unbinds all jQuery events as ko.cleanNode
method doesn't take care of that. I've tested for memory leaks, and it appears to work just fine.
ko.unapplyBindings = function ($node, remove) {
// unbind events
$node.find("*").each(function () {
$(this).unbind();
});
// Remove KO subscriptions and references
if (remove) {
ko.removeNode($node[0]);
} else {
ko.cleanNode($node[0]);
}
};
it's worked for me
boolean hasPermission = (ContextCompat.checkSelfPermission(AddContactActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(AddContactActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_STORAGE);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_WRITE_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(AddContactActivity.this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}