I was facing this error while running Karma Unit Test cases Adding MatSelectModule in the imports fixes the issue
imports: [
HttpClientTestingModule,
FormsModule,
MatTableModule,
MatSelectModule,
NoopAnimationsModule
],
Your typedef
needs to be in the header file (or some other file that's #import
ed into your header), because otherwise the compiler won't know what size to make the PlayerState
ivar. Other than that, it looks ok to me.
(function(con) {
var oDate = new Date();
var nHrs = oDate.getHours();
var nMin = oDate.getMinutes();
var nDate = oDate.getDate();
var nMnth = oDate.getMonth();
var nYear = oDate.getFullYear();
con.log(nDate + ' - ' + nMnth + ' - ' + nYear);
con.log(nHrs + ' : ' + nMin);
})(console);
This produces an output like:
30 - 8 - 2013
21 : 30
Perhaps you may refer documentation on Date object at MDN for more information
Add this line on Click on button
loginButton.setReadPermissions(Arrays.asList( "public_profile", "email", "user_birthday", "user_friends"));
For WebAPI, check out this link: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
Basically, add this code to your Application_Start
:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
This happens when a session other than the one used to alter a table is holding a lock likely because of a DML (update/delete/insert). If you are developing a new system, it is likely that you or someone in your team issues the update statement and you could kill the session without much consequence. Or you could commit from that session once you know who has the session open.
If you have access to a SQL admin system use it to find the offending session. And perhaps kill it.
You could use v$session and v$lock and others but I suggest you google how to find that session and then how to kill it.
In a production system, it really depends. For oracle 10g and older, you could execute
LOCK TABLE mytable in exclusive mode;
alter table mytable modify mycolumn varchar2(5);
In a separate session but have the following ready in case it takes too long.
alter system kill session '....
It depends on what system do you have, older systems are more likely to not commit every single time. That is a problem since there may be long standing locks. So your lock would prevent any new locks and wait for a lock that who knows when will be released. That is why you have the other statement ready. Or you could look for PLSQL scripts out there that do similar things automatically.
In version 11g there is a new environment variable that sets a wait time. I think it likely does something similar to what I described. Mind you that locking issues don't go away.
ALTER SYSTEM SET ddl_lock_timeout=20;
alter table mytable modify mycolumn varchar2(5);
Finally it may be best to wait until there are few users in the system to do this kind of maintenance.
From the Framework Design Guidelines 2nd Edition (pg. 256):
DO NOT return null values from collection properties or from methods returning collections. Return an empty collection or an empty array instead.
Here's another interesting article on the benefits of not returning nulls (I was trying to find something on Brad Abram's blog, and he linked to the article).
Edit- as Eric Lippert has now commented to the original question, I'd also like to link to his excellent article.
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
I got the same error and figured out that i wrote my script using Anaconda but pyinstaller
tries to pack script on pure python. So, modules not exist in pythons library folder cause this problem.
<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
I had this issue and what I did and solved the problem was that I used AsEnumerable()
just before my Join clause.
here is my query:
List<AccountViewModel> selectedAccounts;
using (ctx = SmallContext.GetInstance()) {
var data = ctx.Transactions.
Include(x => x.Source).
Include(x => x.Relation).
AsEnumerable().
Join(selectedAccounts, x => x.Source.Id, y => y.Id, (x, y) => x).
GroupBy(x => new { Id = x.Relation.Id, Name = x.Relation.Name }).
ToList();
}
I was wondering why this issue happens, and now I think It is because after you make a query via LINQ, the result will be in memory and not loaded into objects, I don't know what that state is but they are in in some transitional state I think. Then when you use AsEnumerable()
or ToList()
, etc, you are placing them into physical memory objects and the issue is resolving.
In Node "Buffer
instances are also Uint8Array
instances", so buf.toString()
works in this case.
VS 2019 Professional:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\WcfTestClient.exe
VS 2019 Community:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\WcfTestClient.exe
VS 2019 Enterprise:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\WcfTestClient.exe
VS 2017 Community:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\WcfTestClient.exe
VS 2017 Professional:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\WcfTestClient.exe
VS 2017 Enterprise:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\WcfTestClient.exe
VS 2015:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\WcfTestClient.exe
VS 2013:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\WcfTestClient.exe
VS 2012:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\WcfTestClient.exe
To be simple,
Mono is third party implementation of .Net framework for Linux/Android/iOs
.Net Core is microsoft's own implementation for same.
.Net Core is future. and Mono will be dead eventually. Having said that .Net Core is not matured enough. I was struggling to implement it with IBM Bluemix and later dropped the idea. Down the time (may be 1-2 years), it should be better.
The authenticity token is used to prevent Cross-Site Request Forgery attacks (CSRF). To understand the authenticity token, you must first understand CSRF attacks.
Suppose that you are the author of bank.com
. You have a form on your site that is used to transfer money to a different account with a GET request:
A hacker could just send an HTTP request to the server saying GET /transfer?amount=$1000000&account-to=999999
, right?
Wrong. The hackers attack won't work. The server will basically think?
Huh? Who is this guy trying to initiate a transfer. It's not the owner of the account, that's for sure.
How does the server know this? Because there's no session_id
cookie authenticating the requester.
When you sign in with your username and password, the server sets a session_id
cookie on your browser. That way, you don't have to authenticate each request with your username and password. When your browser sends the session_id
cookie, the server knows:
Oh, that's John Doe. He signed in successfully 2.5 minutes ago. He's good to go.
A hacker might think:
Hmm. A normal HTTP request won't work, but if I could get my hand on that
session_id
cookie, I'd be golden.
The users browser has a bunch of cookies set for the bank.com
domain. Every time the user makes a request to the bank.com
domain, all of the cookies get sent along. Including the session_id
cookie.
So if a hacker could get you to make the GET request that transfers money into his account, he'd be successful. How could he trick you into doing so? With Cross Site Request Forgery.
It's pretty simply, actually. The hacker could just get you to visit his website. On his website, he could have the following image tag:
<img src="http://bank.com/transfer?amount=$1000000&account-to=999999">
When the users browser comes across that image tag, it'll be making a GET request to that url. And since the request comes from his browser, it'll send with it all of the cookies associated with bank.com
. If the user had recently signed in to bank.com
... the session_id
cookie will be set, and the server will think that the user meant to transfer $1,000,000 to account 999999!
Well, just don't visit dangerous sites and you'll be fine.
That isn't enough. What if someone posts that image to Facebook and it appears on your wall? What if it's injected into a site you're visiting with a XSS attack?
It's not so bad. Only GET requests are vulnerable.
Not true. A form that sends a POST request can be dynamically generated. Here's the example from the Rails Guide on Security:
<a href="http://www.harmless.com/" onclick="
var f = document.createElement('form');
f.style.display = 'none';
this.parentNode.appendChild(f);
f.method = 'POST';
f.action = 'http://www.example.com/account/destroy';
f.submit();
return false;">To the harmless survey</a>
When your ApplicationController
has this:
protect_from_forgery with: :exception
This:
<%= form_tag do %>
Form contents
<% end %>
Is compiled into this:
<form accept-charset="UTF-8" action="/" method="post">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
Form contents
</form>
In particular, the following is generated:
<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
To protect against CSRF attacks, if Rails doesn't see the authenticity token sent along with a request, it won't consider the request safe.
How is an attacker supposed to know what this token is? A different value is generated randomly each time the form is generated:
A Cross Site Scripting (XSS) attack - that's how. But that's a different vulnerability for a different day.
Given int& arr[] = {a,b,c,8};
, what is sizeof(*arr)
?
Everywhere else, a reference is treated as being simply the thing itself, so sizeof(*arr)
should simply be sizeof(int)
. But this would make array pointer arithmetic on this array wrong (assuming that references are not the same widths is ints). To eliminate the ambiguity, it's forbidden.
As a python neophyte, I just wanted to mention that if the data did actually look like this:
data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
then sorted()
would automatically sort by the second element in the tuple, as the first elements are all identical.
change your String to String phno="tel:10digits";
and try again.
You've got several options how to do this, either:
urlencode()
or rawurlencode()
- functions designed to encode URLs for http protocolstr_replace()
- "heavy machinery" string replacestrtr()
- would have better performance than str_replace()
when replacing multiple characterspreg_replace()
use regular expressions (perl compatible)strtr()
Assuming that you want to replace "\t"
and " "
with "%20"
:
$replace_pairs = array(
"\t" => '%20',
" " => '%20',
);
return strtr( $text, $replace_pairs)
preg_replace()
You've got few options here, either replacing just space ~ ~
, again replacing space and tab ~[ \t]~
or all kinds of spaces ~\s~
:
return preg_replace( '~\s~', '%20', $text);
Or when you need to replace string like this "\t \t \t \t"
with just one %20
:
return preg_replace( '~\s+~', '%20', $text);
I assumed that you really want to use manual string replacement and handle more types of whitespaces such as non breakable space (
)
In some cases, it's possible to automatically parallelize loops using Numba, though it only works with a small subset of Python:
from numba import njit, prange
@njit(parallel=True)
def prange_test(A):
s = 0
# Without "parallel=True" in the jit-decorator
# the prange statement is equivalent to range
for i in prange(A.shape[0]):
s += A[i]
return s
Unfortunately, it seems that Numba only works with Numpy arrays, but not with other Python objects. In theory, it might also be possible to compile Python to C++ and then automatically parallelize it using the Intel C++ compiler, though I haven't tried this yet.
You cant combine this to attributes.
But you can put both on one action method but you can encapsulate your logic into a other method and call this method from both actions.
The ActionName
Attribute allows to have 2 ActionMethods with the same name.
[HttpGet]
public ActionResult MyMethod()
{
return MyMethodHandler();
}
[HttpPost]
[ActionName("MyMethod")]
public ActionResult MyMethodPost()
{
return MyMethodHandler();
}
private ActionResult MyMethodHandler()
{
// handle the get or post request
return View("MyMethod");
}
Looks like you are missing a leading slash. Perhaps try:
Scanner s = new Scanner(new File("/home/me/java/ex.txt"));
(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)
Create a new sub with the following code and assign it to your button. Change the "DeleteProcess" to the name of your code to do the deletion. This will pop up a box with OK or Cancel and will call your delete sub if you hit ok and not if you hit cancel.
Sub AreYouSure()
Dim Sure As Integer
Sure = MsgBox("Are you sure?", vbOKCancel)
If Sure = 1 Then Call DeleteProcess
End Sub
Jesse
In addition to @sbedulin (Greeting, lovely Windows users!)
The general path on Windows should be
%USERPROFILE%\AppData\Local\atom\bin
If you are using a bash emulator like babun. You'd better checkout the shell files, which only available in the real app folders
/c/User/<username>/AppData/Local/atom/app-<version>/resources/cli/apm.sh # or atom.sh
The thing is that AsyncTask.cancel() call only calls the onCancel function in your task. This is where you want to handle the cancel request.
Here is a small task I use to trigger an update method
private class UpdateTask extends AsyncTask<Void, Void, Void> {
private boolean running = true;
@Override
protected void onCancelled() {
running = false;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
onUpdate();
}
@Override
protected Void doInBackground(Void... params) {
while(running) {
publishProgress();
}
return null;
}
}
Both :
The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access.
https://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping
use arrayOf, arrayOfNulls, emptyArray
var colors_1: Array<String> = arrayOf("green", "red", "blue")
var colors_2: Array<String?> = arrayOfNulls(3)
var colors_3: Array<String> = emptyArray()
For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.
<script type="text/javascript">
function Check() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
}
else {
document.getElementById('ifYes').style.display = 'none';
}
}
</script>
</head>
<body>
Select os :
<br>
Two
<input type="radio" onclick="Check();" value="Two" name="categor`enter code here`y" id="yesCheck"/>One
<input type="radio" onclick="Check();" value="One"name="category"/>
<br>
<div id="ifYes" style="display:none" >
Three<input type="radio" name="win" value="Three"/>
Four<input type="radio" name="win" value="Four"/>
In iOS,
conda update spyder
Your computer is going to start downloading and installing the new version. After finishing, just restart Spyder and that's it.
Try SELECT CAST(field1 AS DECIMAL(10,2)) field1
and replace 10,2
with whatever precision you need.
If you use the BOOLEAN type, this is aliased to TINYINT(1). This is best if you want to use standardised SQL and don't mind that the field could contain an out of range value (basically anything that isn't 0 will be 'true').
ENUM('False', 'True') will let you use the strings in your SQL, and MySQL will store the field internally as an integer where 'False'=0 and 'True'=1 based on the order the Enum is specified.
In MySQL 5+ you can use a BIT(1) field to indicate a 1-bit numeric type. I don't believe this actually uses any less space in the storage but again allows you to constrain the possible values to 1 or 0.
All of the above will use approximately the same amount of storage, so it's best to pick the one you find easiest to work with.
DEMO : http://jsfiddle.net/shfj70qp/
//dd/mm/yyyy
var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
console.log(month+"/"+day+"/"+year);
int[]
and int*
are represented the same way, except int[] allocates (IIRC).
ap
is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.
when you try to access it (x = *ap
), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.
You can perform this task using window.location.reload();
. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation
JavaScript window.location
object can be used
window
: in JavaScript represents an open window in a browser.
location
: in JavaScript holds information about current URL.
The location
object is like a fragment of the window
object and is called up through the window.location
property.
location
object has three methods:
assign()
: used to load a new documentreload()
: used to reload current documentreplace()
: used to replace current document with a new oneSo here we need to use reload()
, because it can help us in reloading the same document.
So use it like window.location.reload();
.
To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true
parameter to location.reload()
. This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.
Determine if a cell is within a range using VBA in Microsoft Excel:
From the linked site (maintaining credit to original submitter):
VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions
Function InRange(Range1 As Range, Range2 As Range) As Boolean
' returns True if Range1 is within Range2
InRange = Not (Application.Intersect(Range1, Range2) Is Nothing)
End Function
Sub TestInRange()
If InRange(ActiveCell, Range("A1:D100")) Then
' code to handle that the active cell is within the right range
MsgBox "Active Cell In Range!"
Else
' code to handle that the active cell is not within the right range
MsgBox "Active Cell NOT In Range!"
End If
End Sub
Website and Project>>website are two different methods of creating ASP.NET application using visual studio. One is projectless and another is project environment. Differences are as
there no much basic difference in using either approach. But if you are creating website that will take longer time, opt for project environment.
I know the OP ends his question with reference to the Eclipse plugin, but I arrived here with a search that didn't specify Eclipse. So here goes for Android Studio:
jar
file to libs directory (such as copy/paste)jar
file and select "Add as Library..."That's it!
If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1"
is exactly equivalent to having a single string "s1"
.
This has been answered quite a lot, but for me, the only working method is this one:
public static byte[] StringToByteArray(string str)
{
byte[] array = Convert.FromBase64String(str);
return array;
}
If you are using Anaconda, all you have to do is activate your virtual environment and then install geckodriver using the following command:
conda install -c conda-forge geckodriver
Far from bad practice, Python (and other languages?) extended the for
loop structure so part of it will only be executed if the loop doesn't break
.
for n in range(5):
for m in range(3):
if m >= n:
print('stop!')
break
print(m, end=' ')
else:
print('finished.')
Output:
stop!
0 stop!
0 1 stop!
0 1 2 finished.
0 1 2 finished.
Equivalent code without break
and that handy else
:
for n in range(5):
aborted = False
for m in range(3):
if not aborted:
if m >= n:
print('stop!')
aborted = True
else:
print(m, end=' ')
if not aborted:
print('finished.')
Connect offers a "higher level" APIs for common HTTP server functionality like session management, authentication, logging and more. Express is built on top of Connect with advanced (Sinatra like) functionality.
Even though Logger.log()
is technically the correct way to output something to the console, it has a few annoyances:
Logger.log(playerArray)
, and then after debugging you'd probably want to remove Logger.log(playerArray)
, hence an additional 1-2 more steps.Instead, whenever I want to debug something I add breakpoints (click on line number) and press the Debug button (bug icon). Breakpoints work well when you are assigning something to a variable, but not so well when you are initiating a variable and want to peek inside of it at a later point, which is similar to what the op is trying to do. In this case, I would force a break condition by entering "x" (x marks the spot!) to throw a run-time error:
Compare with viewing Logs:
The Debug console contains more information and is a lot easier to read than the Logs overlay. One minor benefit with this method is that you never have to worry about polluting your code with a bunch of logging commands if keeping clean code is your thing. Even if you enter "x", you are forced to remember to remove it as part of the debugging process or else your code won't run (built-in cleanup measure, yay).
Try this
$('#thisElement .classToSelect').each(function(i){
// do stuff
});
Hope it will help
You can override symbols in the stock libraries by creating a library with the same symbols and specifying the library in LD_PRELOAD
.
Some people use it to specify libraries in nonstandard locations, but LD_LIBRARY_PATH
is better for that purpose.
Another option is doing the following:
public class UserList extends List<User>{
}
public <T> T magicalListGetter(Class<T> clazz) {
List<?> list = doMagicalVooDooHere();
return (T)list;
}
List<User> users = magicalListGetter(UserList.class);
`
To state the obvious, the cup represents outerScopeVar
.
Asynchronous functions be like...
Guava API provides MoreCollectors.onlyElement() which is a collector that takes a stream containing exactly one element and returns that element.
The returned collector throws an IllegalArgumentException
if the stream consists of two or more elements, and a NoSuchElementException
if the stream is empty.
Refer the below code for usage:
import static com.google.common.collect.MoreCollectors.onlyElement;
Person matchingPerson = objects.stream
.filter(p -> p.email().equals("testemail"))
.collect(onlyElement());
click()
to the QMainWindow custom slot you have created).Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
void openNewWindow();
// ...
private:
NewWindow *mMyNewWindow;
// ...
}
MainWindow.cpp
// ...
MainWindow::MainWindow()
{
// ...
connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
// ...
}
// ...
void MainWindow::openNewWindow()
{
mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
mMyNewWindow->show();
// ...
}
This is an example on how display a custom new window. There are a lot of ways to do this.
Invoke-Sqlcmd -Query "sp_who" -ServerInstance . -QueryTimeout 3
The easiest and the most correct (and legal) way is to use graph api.
Just perform the request: http://graph.facebook.com/4
which returns
{
"id": "4",
"name": "Mark Zuckerberg",
"first_name": "Mark",
"last_name": "Zuckerberg",
"link": "http://www.facebook.com/zuck",
"username": "zuck",
"gender": "male",
"locale": "en_US"
}
and take the link
key.
You can also reduce the traffic by using fields
parameter: http://graph.facebook.com/4?fields=link to get only what you need:
{
"link": "http://www.facebook.com/zuck",
"id": "4"
}
It largely depends on the library you decide to use. For instance, if you use the wxWidgets library, the creation of a thread would look like this:
class RThread : public wxThread {
public:
RThread()
: wxThread(wxTHREAD_JOINABLE){
}
private:
RThread(const RThread ©);
public:
void *Entry(void){
//Do...
return 0;
}
};
wxThread *CreateThread() {
//Create thread
wxThread *_hThread = new RThread();
//Start thread
_hThread->Create();
_hThread->Run();
return _hThread;
}
If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it. More info here: wxThread documentation
Regarding Pax' solution: it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(.
The correct code should be like that:
var mouseDown = 0;
document.body.onmousedown = function() {
++mouseDown;
}
document.body.onmouseup = function() {
--mouseDown;
}
With the test like this:
if(mouseDown){
// crikey! isn't she a beauty?
}
If you want to know what button is pressed, be prepared to make mouseDown an array of counters and count them separately for separate buttons:
// let's pretend that a mouse doesn't have more than 9 buttons
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
mouseDownCount = 0;
document.body.onmousedown = function(evt) {
++mouseDown[evt.button];
++mouseDownCount;
}
document.body.onmouseup = function(evt) {
--mouseDown[evt.button];
--mouseDownCount;
}
Now you can check what buttons were pressed exactly:
if(mouseDownCount){
// alright, let's lift the little bugger up!
for(var i = 0; i < mouseDown.length; ++i){
if(mouseDown[i]){
// we found it right there!
}
}
}
Now be warned that the code above would work only for standard-compliant browsers that pass you a button number starting from 0 and up. IE uses a bit mask of currently pressed buttons:
So adjust your code accordingly! I leave it as an exercise.
And remember: IE uses a global event object called … "event".
Incidentally IE has a feature useful in your case: when other browsers send "button" only for mouse button events (onclick, onmousedown, and onmouseup), IE sends it with onmousemove too. So you can start listening for onmousemove when you need to know the button state, and check for evt.button as soon as you got it — now you know what mouse buttons were pressed:
// for IE only!
document.body.onmousemove = function(){
if(event.button){
// aha! we caught a feisty little sheila!
}
};
Of course you get nothing if she plays dead and not moving.
Relevant links:
Update #1: I don't know why I carried over the document.body-style of code. It will be better to attach event handlers directly to the document.
Have you tried: getElementbyId('ID_OF_ID').innerHTML
?
Assuming you are talking about the ActionEvent
class, then there is a big difference between the two methods.
getActionCommand()
gives you a String representing the action command. The value is component specific; for a JButton
you have the option to set the value with setActionCommand(String command)
but for a JTextField
if you don't set this, it will automatically give you the value of the text field. According to the javadoc this is for compatability with java.awt.TextField
.
getSource()
is specified by the EventObject
class that ActionEvent
is a child of (via java.awt.AWTEvent
). This gives you a reference to the object that the event came from.
Edit:
Here is a example. There are two fields, one has an action command explicitly set, the other doesn't. Type some text into each then press enter.
public class Events implements ActionListener {
private static JFrame frame;
public static void main(String[] args) {
frame = new JFrame("JTextField events");
frame.getContentPane().setLayout(new FlowLayout());
JTextField field1 = new JTextField(10);
field1.addActionListener(new Events());
frame.getContentPane().add(new JLabel("Field with no action command set"));
frame.getContentPane().add(field1);
JTextField field2 = new JTextField(10);
field2.addActionListener(new Events());
field2.setActionCommand("my action command");
frame.getContentPane().add(new JLabel("Field with an action command set"));
frame.getContentPane().add(field2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(220, 150);
frame.setResizable(false);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
JOptionPane.showMessageDialog(frame, "Command: " + cmd);
}
}
I faced this exact same issue with Laravel 8.x on Ubuntu 20.
I run: sudo apt install php7.4-xml
and composer update
within the project directory. This fixed the issue.
Type given command in your terminal..
For disable the selected PHP version...
For enable other PHP version....
It will upgrade Php version, same thing reverse if you want version downgrade, you can see it by PHP_INFO();
This is the only thing that I found to work
-(void) testHTTPS {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:[NSString stringWithFormat:@"%@", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
Pdftotext An open source program (part of Xpdf) which you could call from python (not what you asked for but might be useful). I've used it with no problems. I think google use it in google desktop.
for error : pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
No space between the driver and event
connection = Driver={SQL Server Native Client 11.0};
"Server=servername;"
"Database=dbname;"
"Trusted_Connection=yes;"
Here's some simple code to add a time out to your recv
function using poll
in C:
struct pollfd fd;
int ret;
fd.fd = mySocket; // your socket handler
fd.events = POLLIN;
ret = poll(&fd, 1, 1000); // 1 second for timeout
switch (ret) {
case -1:
// Error
break;
case 0:
// Timeout
break;
default:
recv(mySocket,buf,sizeof(buf), 0); // get your data
break;
}
Selectors work only for drawables, not styles. Reference
First, to make the button background transparent use the following attribute as this will not affect the material design animations:
style="?attr/buttonBarButtonStyle"
There are many ways to style your button. Check out this tutorial.
Second, to make the text bold on pressed, use this java code:
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
// When the user clicks the Button
case MotionEvent.ACTION_DOWN:
btn.setTypeface(Typeface.DEFAULT_BOLD);
break;
// When the user releases the Button
case MotionEvent.ACTION_UP:
btn.setTypeface(Typeface.DEFAULT);
break;
}
return false;
}
});
You could do something along this lines:
def static_example():
if not hasattr(static_example, "static_var"):
static_example.static_var = 0
static_example.static_var += 1
return static_example.static_var
print static_example()
print static_example()
print static_example()
For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.
import java.util.Random;
public class CodeWithPrivateMethod {
public void meaningfulPublicApi() {
if (doTheGamble("Whatever", 1 << 3)) {
throw new RuntimeException("boom");
}
}
private boolean doTheGamble(String whatever, int binary) {
Random random = new Random(System.nanoTime());
boolean gamble = random.nextBoolean();
return gamble;
}
}
The test class looks as follows:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;
@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
private CodeWithPrivateMethod classToTest;
@Test(expected = RuntimeException.class)
public void when_gambling_is_true_then_always_explode() throws Exception {
classToTest = PowerMockito.spy(classToTest);
doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());
classToTest.meaningfulPublicApi();
}
}
Here's one more for you that not only performs the php -l
check for you, but also does some secondary analysis for mistakes that would not be considered invalid (e.g. declaring a variable with a double equal sign).
According to W3:
Partial URLs are interpreted relative to the source of the style sheet, not relative to the document
Therefore, in answer to your question, it will be relative to /stylesheets/
.
If you think about this, this makes sense, since the CSS file could be added to pages in different directories, so standardising it to the CSS file means that the URLs will work wherever the stylesheets are linked.
a = double.Parse(Console.ReadLine());
Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.
Edit:
To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.
If you'd like to perform some sort of error checking, simply do this:
if ( double.TryParse(Console.ReadLine(), out a) ) {
Console.Writeline("Sonuç "+ a * Math.PI;);
}
else {
Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}
Thanks to Öyvind and abatischev for helping me refine my answer.
If you want to run the program to see what it does without infecting your computer, use with a virtual machine like VMWare or Microsoft VPC, or a program that can sandbox the program like SandboxIE
Use the following script tag in your jsp/js file:
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
this will work for sure.
During the installation if you think it has hung (notably during the "Android SDK Setup"), browse to your %temp% directory and order by "Date modified" (descending), there should be a bunch of log files created by the installer.
The one for the "Android SDK Setup" will be named "AndroidSDK_SI.log" (or similar).
Open the file and got to the end of it (Ctrl+End), this should indicate the progress of the current file that is being downloaded.
i.e: "(80%, 349 KiB/s, 99 seconds left)"
Reopening the file, again going to the end, you should see further indication that the download has progressed (or you could just track the modified timestamp of the file [in minutes]).
i.e: "(99%, 351 KiB/s, 1 seconds left)"
Unfortunately, the installer doesn't indicate this progress (it's running in a separate "Java.exe" process, used by the Android SDK).
This seems like a rather long-winded way to check what's happening but does give an indication that the installer hasn't hung and is doing something, albeit very slowly.
Everyone
to the user list.Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.
FYI in Joda Time you could do
DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);
You can set the cookie after having checked if it exists with a value.
$(document).ready(function(){
if ($.cookie('cookie')) { //if cookie isset
//do stuff here like hide a popup when cookie isset
//document.getElementById("hideElement").style.display = "none";
}else{
var CookieSet = $.cookie('cookie', 'value'); //set cookie
}
});
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
Boost Test Library is a very good choice especially if you're already using Boost.
// TODO: Include your class to test here.
#define BOOST_TEST_MODULE MyTest
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(MyTestCase)
{
// To simplify this example test, let's suppose we'll test 'float'.
// Some test are stupid, but all should pass.
float x = 9.5f;
BOOST_CHECK(x != 0.0f);
BOOST_CHECK_EQUAL((int)x, 9);
BOOST_CHECK_CLOSE(x, 9.5f, 0.0001f); // Checks differ no more then 0.0001%
}
It supports:
PS: I wrote an article about it that may help you getting started: C++ Unit Testing Framework: A Boost Test Tutorial
Yes, you can switch on the name...
switch (obj.GetType().Name)
{
case "TextBox":...
}
To fix this problem, simply delete the debug.keystore file.
The default storage location for AVDs is
In ~/.android/ on OS X and Linux.
In C:\Documents and Settings\.android\ on Windows XP
In C:\Users\.android\ on Windows Vista and Windows 7.
Also see this link, which can be helpful.
http://developer.android.com/tools/publishing/app-signing.html
Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.
Check this : Using Large Message Requests in Silverlight with WCF
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="TestLargeWCF.Web.MyServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="customBinding0">
<binaryMessageEncoding />
<!-- Start change -->
<httpTransport maxReceivedMessageSize="2097152"
maxBufferSize="2097152"
maxBufferPoolSize="2097152"/>
<!-- Stop change -->
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
<endpoint address=""
binding="customBinding"
bindingConfiguration="customBinding0"
contract="TestLargeWCF.Web.MyService"/>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount
property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).
If you cannot find it this way, try the menu: View/Properties Window.
Or try the F4 key.
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
I just wrote a class called JSON, which makes JSON handling in Swift as easy as JSON object in ES5.
Turn your swift object to JSON like so:
let obj:[String:AnyObject] = [
"array": [JSON.null, false, 0, "",[],[:]],
"object":[
"null": JSON.null,
"bool": true,
"int": 42,
"double": 3.141592653589793,
"string": "a a\t?\n",
"array": [],
"object": [:]
],
"url":"http://blog.livedoor.com/dankogai/"
]
let json = JSON(obj)
json.toString()
...or string...
let json = JSON.parse("{\"array\":[...}")
...or URL.
let json = JSON.fromURL("http://api.dan.co.jp/jsonenv")
Tree Traversal
Just traverse elements via subscript:
json["object"]["null"].asNull // NSNull()
// ...
json["object"]["string"].asString // "a a\t?\n"
json["array"][0].asNull // NSNull()
json["array"][1].asBool // false
// ...
Just like SwiftyJSON you don't worry if the subscripted entry does not exist.
if let b = json["noexistent"][1234567890]["entry"].asBool {
// ....
} else {
let e = json["noexistent"][1234567890]["entry"].asError
println(e)
}
If you are tired of subscripts, add your scheme like so:
//// schema by subclassing
class MyJSON : JSON {
init(_ obj:AnyObject){ super.init(obj) }
init(_ json:JSON) { super.init(json) }
var null :NSNull? { return self["null"].asNull }
var bool :Bool? { return self["bool"].asBool }
var int :Int? { return self["int"].asInt }
var double:Double? { return self["double"].asDouble }
var string:String? { return self["string"].asString }
}
And you go:
let myjson = MyJSON(obj)
myjson.object.null
myjson.object.bool
myjson.object.int
myjson.object.double
myjson.object.string
// ...
Hope you like it.
With the new xCode 7.3+ its important to add your domain to the exception list (How can I add NSAppTransportSecurity to my info.plist file?), refer to this posting for instructions, otherwise you will get a transport authority error.
Seems to work here:
>>> a=[[1,1],[2,1],[3,1]]
>>> a
[[1, 1], [2, 1], [3, 1]]
>>> a[1]
[2, 1]
>>> a[1][0]
2
>>> a[1][1]
1
import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions)
with open('data.csv', 'r') as f:
for rec in csv.DictReader(f):
for l, col in zip(data, cols):
l.append(float(rec[col]))
print data
# [[3.0, 3.0], [0.01, 0.01]]
Use max-width:100%;
, height: auto;
and display:block;
as follow:
image {
max-width:100%;
height: auto;
display:block;
}
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
There are 3 ways I can think of:
The way that is easiest to explain is
:%s/phrase to delete//gc
but you can also (personally I use this second one more often) do a regular search for the phrase to delete
/phrase to delete
Vim will take you to the beginning of the next occurrence of the phrase.
Go into insert mode (hit i) and use the Delete key to remove the phrase.
Hit escape when you have deleted all of the phrase.
Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed
Continue hitting n and dot until you are done.
Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you
Count the number of characters you want to delete
Type that number in (with number keys)
Hit the x key - characters should get deleted
Continue through with n and dot like in the second method.
PS - And if you didn't know already you can do a capital n to move backwards through the search matches.
I think it would be better to actually bind your listBoxes to a datasource, since it looks like you are adding the same elements to each listbox. A simple example would be something like this:
private List<String> _weight = new List<string>() { "kilogram", "pound" };
private List<String> _height = new List<string>() { "foot", "inch", "meter" };
public Window1()
{
InitializeComponent();
}
private void Weight_Click(object sender, RoutedEventArgs e)
{
listBox1.ItemsSource = _weight;
listBox2.ItemsSource = _weight;
}
private void Height_Click(object sender, RoutedEventArgs e)
{
listBox1.ItemsSource = _height;
listBox2.ItemsSource = _height;
}
Here is the code I use in my C++ app.
Positive points :
Negative points :
// Inspired from http://stackoverflow.com/a/15281070/1529139
// and http://stackoverflow.com/q/40059902/1529139
bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent)
{
bool success = false;
DWORD thisConsoleId = GetCurrentProcessId();
// Leave current console if it exists
// (otherwise AttachConsole will return ERROR_ACCESS_DENIED)
bool consoleDetached = (FreeConsole() != FALSE);
if (AttachConsole(dwProcessId) != FALSE)
{
// Add a fake Ctrl-C handler for avoid instant kill is this console
// WARNING: do not revert it or current program will be also killed
SetConsoleCtrlHandler(nullptr, true);
success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE);
FreeConsole();
}
if (consoleDetached)
{
// Create a new console if previous was deleted by OS
if (AttachConsole(thisConsoleId) == FALSE)
{
int errorCode = GetLastError();
if (errorCode == 31) // 31=ERROR_GEN_FAILURE
{
AllocConsole();
}
}
}
return success;
}
Usage example :
DWORD dwProcessId = ...;
if (signalCtrl(dwProcessId, CTRL_C_EVENT))
{
cout << "Signal sent" << endl;
}
There should be no single quotes here . Single quotes are for string literals: 'A'
'some value'
.
Either use double quotes to preserve the upper case spelling of "A":
CREATE TABLE "A" ...
Or don't use quotes at all:
CREATE TABLE A ...
which is identical to
CREATE TABLE a ...
because all unquoted identifiers are folded to lower case automatically in PostgreSQL.
You could avoid problems with the index name completely by using simpler syntax:
CREATE TABLE csd_relationship (
csd_relationship_id serial PRIMARY KEY,
type_id integer NOT NULL,
object_id integer NOT NULL
);
Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.
I just configured min as the following :
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
# changing the name of my data base for testing
spring.datasource.url= jdbc:h2:mem:mockedDB
spring.datasource.username=sa
spring.datasource.password=sa
# in testing i don`t need to know the port
#Feature that determines what happens when no accessors are found for a type
#(and there are no annotations to indicate it is meant to be serialized).
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false`enter code here`
I've encountered the same problem for years now, working in Visual Studio 2008. And I've tried every "solution" on StackOverflow and dozens of blogs, just like I'm sure all of you have. And sometimes they work, and sometimes they don't, just like I'm sure all of you have encountered. And apparently it's still an issue in VS2010 and VS2012.
So finally, a couple of months ago, I decided enough was enough, and over a few weeks I built a tool called "Redesigner" that generates .designer files. It's open-source under the BSD license, with the source code available on SourceForge — free to use, free to steal, free to do anything you please with. And it does what Visual Studio fails to do so often, which is generate .designer files quickly and reliably.
It's a stand-alone command-line tool that parses .aspx and .ascx files, performs all the necessary reflection magic, and spits out correct .designer files. It does all the parsing and reflection itself to avoid relying on existing code, which we all know too well is broken. It's written in C# against .NET 3.5, but it makes pains to avoid using even System.Web for anything other than type declarations, and it doesn't use or rely on Visual Studio at all.
Redesigner can generate new .designer files; and it offers a --verbose option so that when things go wrong, you get far better error messages than "Exception of type System.Exception was thrown." And there's a --verify option that can be used to tell you when your existing .designer files are broken — missing controls, bad property declarations, unreadable by Visual Studio, or otherwise just plain borked.
We've been using it at my workplace to get us out of jams for the better part of the last month now, and while Redesigner is still a beta, it's getting far enough along that it's worth sharing its existence with the public. I soon intend to create a Visual Studio plugin for it so you can simply right-click to verify or regenerate designer files the way you always wished you could. But in the interim, the command-line usage is pretty easy and will save you a lot of headaches.
Anyway, go download a copy of Redesigner now and stop pulling out your hair. You won't always need it, but when you do, you'll be glad you have it!
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
My MaxHeightScrollView
custom view
public class MaxHeightScrollView extends ScrollView {
private int maxHeight;
public MaxHeightScrollView(Context context) {
this(context, null);
}
public MaxHeightScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MaxHeightScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray styledAttrs =
context.obtainStyledAttributes(attrs, R.styleable.MaxHeightScrollView);
try {
maxHeight = styledAttrs.getDimensionPixelSize(R.styleable.MaxHeightScrollView_mhs_maxHeight, 0);
} finally {
styledAttrs.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (maxHeight > 0) {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
style.xml
<declare-styleable name="MaxHeightScrollView">
<attr name="mhs_maxHeight" format="dimension" />
</declare-styleable>
Using
<....MaxHeightScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:mhs_maxHeight="100dp"
>
...
</....MaxHeightScrollView>
There is the way of current thread getting:
Thread t = Thread.currentThread();
After you have got Thread class object (t) you are able to get information you need using Thread class methods.
Thread ID gettting:
long tId = t.getId(); // e.g. 14291
Thread name gettting:
String tName = t.getName(); // e.g. "pool-29-thread-7"
While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:
import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
print str(row)
I think groupby should work.
df.groupby(['A', 'B']).max()['C']
If you need a dataframe back you can chain the reset index call.
df.groupby(['A', 'B']).max()['C'].reset_index()
Assuming cloud is int cloud[10]
you can do it like this:
int *p = max_element(cloud, cloud + 10);
Do dtEmp
on your current working DataTable:
DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);
It's nice.
@thamme-gowda's solution works for images too!
| |
|:----------------------------------------------------------------------------:|
| ![](https://gravatar.com/avatar/4cc702785290b4934c531c56f6061e5e "Tonejito") |
You can check this out on a gist I made for that. Here is a render of the table hack on GitHub and GitLab:
I had the same issue when running it in Python and I had to manually run 'killall' command to kill all processes. However when I implemented the driver using the Python context management protocol all processes were gone. It seems that Python interpreter does a really good job of cleaning things up.
Here is the implementation:
class Browser:
def __enter__(self):
self.options = webdriver.ChromeOptions()
self.options.add_argument('headless')
self.driver = webdriver.Chrome(chrome_options=self.options)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.driver.close()
self.driver.quit()
And the usage:
with Browser() as browser:
browser.navigate_to_page()
The best loading and blocking that particular div for ajax call until it succeeded is Blockui
go through this link http://www.malsup.com/jquery/block/#element
example usage:
<span class="no-display smallLoader"><img src="/images/loader-small.png" /></span>
script
jQuery.ajax(
{
url: site_path+"/restaurantlist/addtocart",
type: "POST",
success: function (data) {
jQuery("#id").unblock();
},
beforeSend:function (data){
jQuery("#id").block({
message: jQuery(".smallLoader").html(),
css: {
border: 'none',
backgroundColor: 'none'
},
overlayCSS: { backgroundColor: '#afafaf' }
});
}
});
hope this helps really it is very interactive.
I normally use this statement:
ALTER TABLE `table_name`
CHANGE COLUMN `col_name` `col_name` VARCHAR(10000);
But, I think SET will work too, never have tried it. :)
For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it:
Button btn = new Button (this);
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
btn.setHeight((int)(display.getHeight()*0.68));
char arr[3] = "bo";
The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.
without jquery, e.g. with regular javascript:
document.querySelector('form input:not([type=hidden])').focus()
works on Safari but not Chrome 75 (april 2019)
The source of your confusion is evident in your comment:
The whole point of ceil/floor operations is to convert floats to integers!
The point of the ceil and floor operations is to round floating-point data to integral values. Not to do a type conversion. Users who need to get integer values can do an explicit conversion following the operation.
Note that it would not be possible to implement a round to integral value as trivially if all you had available were a ceil or float operation that returned an integer. You would need to first check that the input is within the representable integer range, then call the function; you would need to handle NaN and infinities in a separate code path.
Additionally, you must have versions of ceil and floor which return floating-point numbers if you want to conform to IEEE 754.
You may still want to use VARCHAR in cases where you don't always store a hash for the user (i.e. authenticating accounts/forgot login url). Once a user has authenticated/changed their login info they shouldn't be able to use the hash and should have no reason to. You could create a separate table to store temporary hash -> user associations that could be deleted but I don't think most people bother to do this.
I am started on Angular8 base live project got the above issue but When use "app-routing.module" we forget import "CommonModule". Remember to import!
import { CommonModule } from '@angular/common';
@NgModule({
imports: [
CommonModule
]})
It will solve your error.
You can do this with...
...depending on the extension you want to use. The first is not recommended because the mysql extension is deprecated. The third is still experimental.
The comments at these hyperlinks do a good job of explaining how to set your type from a plain old string to its original type in the database.
Some frameworks also abstract this (CodeIgniter provides $this->db->field_data()
).
You could also do guesswork--like looping through your resulting rows and using is_numeric() on each. Something like:
foreach($result as &$row){
foreach($row as &$value){
if(is_numeric($value)){
$value = (int) $value;
}
}
}
This would turn anything that looks like a number into one...definitely not perfect.
This is a very old post, but I recently encountered the problem and for me the following solved the issue by formatting the SQL as follows,
SELECT CONVERT (varchar, getdate(), 120) AS Date
If you copy the result from SQL Server and paste in Excel then Excel holds the proper formatting.
break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return
to break the execution flow of the current function and return to the caller.
function loop() {
if (isPlaying) {
jet1.draw();
drawAllEnemies();
requestAnimFrame(loop);
if (game == 1) {
return
}
}
}
Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies
and requestAnimFrame
method as well as how game
value is updated
From the GNU Make documentation,
5.3.1 Choosing the Shell
------------------------
The program used as the shell is taken from the variable `SHELL'. If
this variable is not set in your makefile, the program `/bin/sh' is
used as the shell.
So put SHELL := /bin/bash
at the top of your makefile, and you should be good to go.
BTW: You can also do this for one target, at least for GNU Make. Each target can have its own variable assignments, like this:
all: a b
a:
@echo "a is $$0"
b: SHELL:=/bin/bash # HERE: this is setting the shell for b only
b:
@echo "b is $$0"
That'll print:
a is /bin/sh
b is /bin/bash
See "Target-specific Variable Values" in the documentation for more details. That line can go anywhere in the Makefile, it doesn't have to be immediately before the target.
Wrap the textbox inside asp:Panel
tags
Hide a Button that has a click event that does what you want done and give the <asp:panel>
a DefaultButton
Attribute with the ID of the Hidden Button.
<asp:Panel runat="server" DefaultButton="Button1">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" OnClick="Button1_Click" />
</asp:Panel>
First method
For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.
Steps:
type PowerShell in search area and click on "Windows PowerShell"
If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)
run the .bat file with following command
PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt
This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.
Second method
You can use file redirection (>, >>) as suggest by Bali C above.
I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.
Some of the ways to convert String
into Int
are as follows:
You can use Integer.parseInt()
:
String test = "4568";
int new = Integer.parseInt(test);
Also you can use Integer.valueOf()
:
String test = "4568";
int new = Integer.valueOf(test);
Resolved with crontab root
10 * * * * /usr/bin/minidlnad -r
To further simplify B T's answer: Use refresh tokens when you don't typically want the user to have to type in credentials again, but still want the power to be able to revoke the permissions (by revoking the refresh token)
You cannot revoke an access token, only a refresh token.
Also you will need to zoom and center the map due to your country restrictions!
Just use zoom and center parameters! ;)
function initialize() {
var myOptions = {
zoom: countries['us'].zoom,
center: countries['us'].center,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false
};
... all other code ...
}
var test = parseInt($("#testid").val(), 10);
You have to tell it you want the value
of the input you are targeting.
And also, always provide the second argument (radix) to parseInt
. It tries to be too clever and autodetect it if not provided and can lead to unexpected results.
Providing 10
assumes you are wanting a base 10 number.
This answers improves on Rashmi Pandit's answer, which is in a way better than the rest because that it seems to completely resolve the exact problem detailed in the question.
The bad part is that is inefficient and not uses the IgnoreCase option consistently.
Inefficient part is because regex can be expensive to construct and execute, and in that answer it could have been constructed just once (calling Regex.IsMatch
was just constructing the regex again behind the scene). And Match
method could have been called only once and stored in a variable and then link
and name
should call Result
from that variable.
And the IgnoreCase option was only used in the Match
part but not in the Regex.IsMatch
part.
I also moved the Regex definition outside the method in order to construct it just once (I think is the sensible approach if we are storing that the assembly with the RegexOptions.Compiled
option).
private static Regex hrefRegex = new Regex("<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
var matches = hrefRegex.Match(htmlTd);
if (matches.Success)
{
link = matches.Result("${link}");
name = matches.Result("${name}");
return true;
}
else
{
link = null;
name = null;
return false;
}
}
My modified support library supports using both View animations (i.e. <translate>, <rotate>
) and Object Animators (i.e. <objectAnimator>
) for Fragment Transitions. It is implemented with NineOldAndroids. Refer to my documentation on github for details.
Instead of trying to center div's, just add this to your local css.
.col-md-offset-15 {
margin-left: 12.4999999%;
}
which is roughly offset-1 and half of offset-1. (8.333% + 4.166%) = 12.4999%
This worked for me.
public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private static final String LOGSERVICE = "#######";
@Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
Log.i(LOGSERVICE, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOGSERVICE, "onStartCommand");
if (!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
return START_STICKY;
}
@Override
public void onConnected(Bundle bundle) {
Log.i(LOGSERVICE, "onConnected" + bundle);
Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (l != null) {
Log.i(LOGSERVICE, "lat " + l.getLatitude());
Log.i(LOGSERVICE, "lng " + l.getLongitude());
}
startLocationUpdate();
}
@Override
public void onConnectionSuspended(int i) {
Log.i(LOGSERVICE, "onConnectionSuspended " + i);
}
@Override
public void onLocationChanged(Location location) {
Log.i(LOGSERVICE, "lat " + location.getLatitude());
Log.i(LOGSERVICE, "lng " + location.getLongitude());
LatLng mLocation = (new LatLng(location.getLatitude(), location.getLongitude()));
EventBus.getDefault().post(mLocation);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOGSERVICE, "onDestroy - Estou sendo destruido ");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(LOGSERVICE, "onConnectionFailed ");
}
private void initLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(2000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void startLocationUpdate() {
initLocationRequest();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
private void stopLocationUpdate() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
}
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
function showButtons () { $('#b1, #b2, #b3').show(); }
</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}
</style>
</head>
<body>
<a href="#" onclick="showButtons();">Show me the money!</a>
<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />
</body>
</html>
The onclick
attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.
An interface defines a contract for an API, that is a set of methods that both implementer and user of the API agree upon. An interface does not have an instanced implementation, hence no constructor.
The use case you describe is akin to an abstract class in which the constructor calls a method of an abstract method which is implemented in an child class.
The inherent problem here is that while the base constructor is being executed, the child object is not constructed yet, and therfore in an unpredictable state.
To summarize: is it asking for trouble when you call overloaded methods from parent constructors, to quote mindprod:
In general you must avoid calling any non-final methods in a constructor. The problem is that instance initialisers / variable initialisation in the derived class is performed after the constructor of the base class.
The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):
C:\xampp\php\PEAR\initcontrols\header_myworks.php
providing the path you pasted in the subject is correct. Make sure your file is located there.
For more info you can get and set the include path programmatically.
If you want to remove EVERYTHING :
textarea {
border: none;
background-color: transparent;
resize: none;
outline: none;
}
You might consider this for guidelines on when to go for struct or class, https://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx .
v CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
X AVOID defining a struct unless the type has all of the following characteristics:
It logically represents a single value, similar to primitive types (int, double, etc.).
It has an instance size under 16 bytes.
It is immutable.
It will not have to be boxed frequently.
This is a standard problem.
Note that MySQL allows you to omit columns from the GROUP BY clause, which Standard SQL does not, but you do not get deterministic results in general when you use the MySQL facility.
SELECT *
FROM Messages AS M
JOIN (SELECT To_ID, From_ID, MAX(TimeStamp) AS Most_Recent
FROM Messages
WHERE To_ID = 12345678
GROUP BY From_ID
) AS R
ON R.To_ID = M.To_ID AND R.From_ID = M.From_ID AND R.Most_Recent = M.TimeStamp
WHERE M.To_ID = 12345678
I've added a filter on the To_ID
to match what you're likely to have. The query will work without it, but will return a lot more data in general. The condition should not need to be stated in both the nested query and the outer query (the optimizer should push the condition down automatically), but it can do no harm to repeat the condition as shown.
We can mute it in this way (device and simulator need different values):
Add the Name OS_ACTIVITY_MODE
and the Value ${DEBUG_ACTIVITY_MODE}
and check it (in Product -> Scheme -> Edit Scheme -> Run -> Arguments -> Environment).
Add User-Defined Setting DEBUG_ACTIVITY_MODE
, then add Any iOS Simulator SDK
for Debug
and set it's value to disable
(in Project -> Build settings -> + -> User-Defined Setting)
Try this:
SELECT GETDATE(), 'Today'
UNION ALL
SELECT DATEADD(DAY, 10, GETDATE()), '10 Days Later'
UNION ALL
SELECT DATEADD(DAY, –10, GETDATE()), '10 Days Earlier'
UNION ALL
SELECT DATEADD(MONTH, 1, GETDATE()), 'Next Month'
UNION ALL
SELECT DATEADD(MONTH, –1, GETDATE()), 'Previous Month'
UNION ALL
SELECT DATEADD(YEAR, 1, GETDATE()), 'Next Year'
UNION ALL
SELECT DATEADD(YEAR, –1, GETDATE()), 'Previous Year'
Result Set:
———————– —————
2011-05-20 21:11:42.390 Today
2011-05-30 21:11:42.390 10 Days Later
2011-05-10 21:11:42.390 10 Days Earlier
2011-06-20 21:11:42.390 Next Month
2011-04-20 21:11:42.390 Previous Month
2012-05-20 21:11:42.390 Next Year
2010-05-20 21:11:42.390 Previous Year
Similar problem on Ubuntu 16.04.
Setting up jenkins (2.72) ...
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
invoke-rc.d: initscript jenkins, action "start" failed.
? jenkins.service - LSB: Start Jenkins at boot time
Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2017-08-01 05:39:06 UTC; 7ms ago
Docs: man:systemd-sysv-generator(8)
Process: 3700 ExecStart=/etc/init.d/jenkins start (code=exited, status=1/FAILURE)
Aug 01 05:39:06 ip-0 systemd[1]: Starting LSB: Start Jenkins ....
Aug 01 05:39:06 ip-0 jenkins[3700]: ERROR: No Java executable ...
Aug 01 05:39:06 ip-0 jenkins[3700]: If you actually have java ...
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Control pro...1
Aug 01 05:39:06 ip-0 systemd[1]: Failed to start LSB: Start J....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Unit entere....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Failed with....
To fix the issue manually install Java Runtime Environment:
JDK version 9:
sudo apt install openjdk-9-jre
JDK version 8:
sudo apt install openjdk-8-jre
Open Jenkins configuration file:
sudo vi /etc/init.d/jenkins
Finally, append path to the new java executable (line 16):
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/lib/jvm/java-8-openjdk-amd64/bin/
This a great example about share with Intents in Android:
* Share with Intents in Android
//Share text:
Intent intent2 = new Intent(); intent2.setAction(Intent.ACTION_SEND);
intent2.setType("text/plain");
intent2.putExtra(Intent.EXTRA_TEXT, "Your text here" );
startActivity(Intent.createChooser(intent2, "Share via"));
//via Email:
Intent intent2 = new Intent();
intent2.setAction(Intent.ACTION_SEND);
intent2.setType("message/rfc822");
intent2.putExtra(Intent.EXTRA_EMAIL, new String[]{EMAIL1, EMAIL2});
intent2.putExtra(Intent.EXTRA_SUBJECT, "Email Subject");
intent2.putExtra(Intent.EXTRA_TEXT, "Your text here" );
startActivity(intent2);
//Share Files:
//Image:
boolean isPNG = (path.toLowerCase().endsWith(".png")) ? true : false;
Intent i = new Intent(Intent.ACTION_SEND);
//Set type of file
if(isPNG)
{
i.setType("image/png");//With png image file or set "image/*" type
}
else
{
i.setType("image/jpeg");
}
Uri imgUri = Uri.fromFile(new File(path));//Absolute Path of image
i.putExtra(Intent.EXTRA_STREAM, imgUri);//Uri of image
startActivity(Intent.createChooser(i, "Share via"));
break;
//APK:
File f = new File(path1);
if(f.exists())
{
Intent intent2 = new Intent();
intent2.setAction(Intent.ACTION_SEND);
intent2.setType("application/vnd.android.package-archive");//APk file type
intent2.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f) );
startActivity(Intent.createChooser(intent2, "Share via"));
}
break;
Many outdated, over-complicated and weird answers here. The reason is that the documentation is inadequate and the simple solution is to just use basicConfig()
and set it as follows:
logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', format='{asctime}.{msecs:0<3.0f} {name} {threadName} {levelname}: {message}', style='{')
The trick here was that you have to also set the datefmt
argument, as the default messes it up and is not what is (currently) shown in the how-to python docs. So rather look here.
An alternative and possibly cleaner way, would have been to override the default_msec_format
variable with:
formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'
However, that did not work for unknown reasons.
PS. I am using Python 3.8.
A couple things
(a) you cant have both background-color and background, background will always win. in the example below, i combined them through shorthand, but this will produce the color only as a fallback method when the image does not show.
(b) no-scroll does not work, i don't believe it is a valid property of a background-image. try something like fixed:
.button:after {
content: "";
width: 30px;
height: 30px;
background:red url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") no-repeat -30px -50px fixed;
top: 10px;
right: 5px;
position: absolute;
display: inline-block;
}
I updated your jsFiddle to this and it showed the image.
Before sorting the given array multiply each element by -1
then use Arrays.sort(arr) then again multiply each element by -1
for(int i=0;i<arr.length;i++)
arr[i]=-arr[i];
Arrays.sort(arr);
for(int i=0;i<arr.length;i++)
arr[i]=-arr[i];
Restarting the SQL Server will clear up the log space used by your database. If this however is not an option, you can try the following:
* Issue a CHECKPOINT command to free up log space in the log file.
* Check the available log space with DBCC SQLPERF('logspace'). If only a small
percentage of your log file is actually been used, you can try a DBCC SHRINKFILE
command. This can however possibly introduce corruption in your database.
* If you have another drive with space available you can try to add a file there in
order to get enough space to attempt to resolve the issue.
Hope this will help you in finding your solution.
In Bootstrap 3.2.0 the "on" event has to be on the document and you have to empty the modal :
$(document).on("hidden.bs.modal", function (e) {
$(e.target).removeData("bs.modal").find(".modal-content").empty();
});
In Bootstrap 3.1.0 the "on" event can be on the body :
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
It is mostly used for importing symbols from / exporting symbols to a shared library (DLL). Both Visual C++ and GCC compilers support __declspec(dllimport)
and __declspec(dllexport)
. Other uses (some Microsoft-only) are documented in the MSDN.
In case it is not working in your default region, try providing a region close to you. This worked for me:
PS C:\Users\shrig> aws configure
AWS Access Key ID [****************C]:**strong text**
AWS Secret Access Key [****************WD]:
Default region name [us-east1]: ap-south-1
Default output format [text]:
Check a cronjob
function cronjob_exists($command){
$cronjob_exists=false;
exec('crontab -l', $crontab);
if(isset($crontab)&&is_array($crontab)){
$crontab = array_flip($crontab);
if(isset($crontab[$command])){
$cronjob_exists=true;
}
}
return $cronjob_exists;
}
Append a cronjob
function append_cronjob($command){
if(is_string($command)&&!empty($command)&&cronjob_exists($command)===FALSE){
//add job to crontab
exec('echo -e "`crontab -l`\n'.$command.'" | crontab -', $output);
}
return $output;
}
Remove a crontab
exec('crontab -r', $crontab);
Example
exec('crontab -r', $crontab);
append_cronjob('* * * * * curl -s http://localhost/cron/test1.php');
append_cronjob('* * * * * curl -s http://localhost/cron/test2.php');
append_cronjob('* * * * * curl -s http://localhost/cron/test3.php');
For installing
gem install gemname -v versionnumber
For uninstall
gem uninstall gemname -v versionnumber
There is no need to use angular http, you can get with js native functions
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
// on the first then you will return blob from response_x000D_
return await fetch(url).then(r => r.blob())_x000D_
.then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
_x000D_
return new File([blob], fileName+'.'+ blob.type.split('/')[1]) ;_x000D_
});_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
// with file reader you will transform the file in a data url file;_x000D_
var reader = new FileReader();_x000D_
reader.readAsDataURL(file);_x000D_
reader.onloadend = () => {_x000D_
_x000D_
// just putting the data url to img element_x000D_
document.querySelector('#image').src = reader.result ;_x000D_
}_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
another workaround:
var myarray = [];
$("#test").click(function() {
myarray[index]=$("#drop").val();
alert(myarray);
});
i wanted to add all checked checkbox to array. so example, if .each is used:
var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
if (this.checked) {
var p=$('.pp').eq(idx).val();
vpp[incr]=(p);
incr++;
}
});
//do what ever with vpp array;
If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.
This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-sm-3">Under me should be a DIV</div>_x000D_
<div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
<div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
</div>_x000D_
</div>
_x000D_
This one more version - this will help in generic
Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer
Sub Create()
Dim strFilePath As String
Dim strFileName As String
'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value
strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value
Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName
End Sub
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
Dim Q As String
Dim sOutputFileNamewithPath As String
Q = Chr$(34)
Dim sXML As String
'sXML = sXML & "<rows>"
' ''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
Dim iCount As Integer
iRow = iDataStartRow
iCount = 1
While Cells(iRow, 1) > ""
'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
For iCOl = 1 To iColCount - 1
If (iStartCol = iCOl) Then
sXML = sXML & "<" & strSubTag & ">"
End If
If (iEndCol = iCOl) Then
sXML = sXML & "</" & strSubTag & ">"
End If
If (iStartCol2 = iCOl) Then
sXML = sXML & "<" & strSubTag2 & ">"
End If
If (iEndCol2 = iCOl) Then
sXML = sXML & "</" & strSubTag2 & ">"
End If
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
sXML = sXML & Trim$(Cells(iRow, iCOl))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
Next
'sXML = sXML & "</row>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
''Write the entire file to sText
Open sOutputFileNamewithPath For Output As #nDestFile
Print #nDestFile, sXML
iRow = iRow + 1
sXML = ""
iCount = iCount + 1
Wend
'sXML = sXML & "</rows>"
Close
End Sub
To get the list of multiple records use following command
select field1,field2,field3, count(*)
from table_name
group by field1,field2,field3
having count(*) > 1
If you're working with ES6 You can use a set:
function arrayHas( array, element ) {
const s = new Set(array);
return s.has(element)
}
This should be more performant than just about any other method
Use the square bracket syntax:
if (!empty($row["title"])) {
$catList[$row["datasource_id"]] = $row["title"];
}
$row["datasource_id"]
is the key for where the value of $row["title"]
is stored in.
A simple way of looking at HTTP 301 vs. 302 redirects is:
Suppose you have a bookmark to "http://sample.com/sample". You use a browser to go there.
A 302 redirect to a different URL at this point would mean that you should keep your bookmark to "http://sample.com/sample". This is because the destination URL may change in the future.
A 301 redirect to a different URL would mean that your bookmark should change to point to the new URL as it is a permanent redirect.
If you use webpack, you can just use the node.js assertion library. Although they claim that it's "not intended to be a general purpose assertion library", it seems to be more than OK for ad hoc assertions, and it seems no competitor exists in the Node space anyway (Chai is designed for unit testing).
const assert = require('assert');
...
assert(jqXHR.status == 201, "create response should be 201");
You need to use webpack or browserify to be able to use this, so obviously this is only useful if those are already in your workflow.
If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.
MembershipUser u = Membership.GetUser(LoginUser.UserName);
Although both answers are technically correct, I want to introduce a different syntax choice for this answer. This imho makes it easier to read what's going on with injection, differentiate between etc.
File One
// Create the module that deals with controllers
angular.module('myApp.controllers', []);
File Two
// Here we get the module we created in file one
angular.module('myApp.controllers')
// We are adding a function called Ctrl1
// to the module we got in the line above
.controller('Ctrl1', Ctrl1);
// Inject my dependencies
Ctrl1.$inject = ['$scope', '$http'];
// Now create our controller function with all necessary logic
function Ctrl1($scope, $http) {
// Logic here
}
File Three
// Here we get the module we created in file one
angular.module('myApp.controllers')
// We are adding a function called Ctrl2
// to the module we got in the line above
.controller('Ctrl2', Ctrl2);
// Inject my dependencies
Ctrl2.$inject = ['$scope', '$http'];
// Now create our controller function with all necessary logic
function Ctrl2($scope, $http) {
// Logic here
}
I found a bug on Mahoor13 answer, it's not working in loop so I've fixed it with this correction:
HTML:
<input type="email" id="eid" name="email_field" oninput="check(this)">
Javascript:
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!");
}
else {
input.setCustomValidity("");
}
}
It will perfectly running in loop.
Use transform: rotate(90deg)
:
#container_2 {_x000D_
border: 1px solid;_x000D_
padding: .5em;_x000D_
width: 5em;_x000D_
height: 5em;_x000D_
transition: .3s all; /* rotate gradually instead of instantly */_x000D_
}_x000D_
_x000D_
#container_2:hover {_x000D_
-webkit-transform: rotate(90deg); /* to support Safari and Android browser */_x000D_
-ms-transform: rotate(90deg); /* to support IE 9 */_x000D_
transform: rotate(90deg);_x000D_
}
_x000D_
<div id="container_2">This box should be rotated 90° on hover.</div>
_x000D_
Click "Run code snippet", then hover over the box to see the effect of the transform.
Realistically, no other prefixed entries are needed. See Can I use CSS3 Transforms?
This approach uses:
inspect
moduleaccount_id
and def_id
variables.This way looks the most Pythonic to me.
import inspect
query = inspect.cleandoc(f'''
SELECT action.descr as "action",
role.id as role_id,
role.descr as role
FROM
public.role_action_def,
public.role,
public.record_def,
public.action
WHERE role.id = role_action_def.role_id AND
record_def.id = role_action_def.def_id AND
action.id = role_action_def.action_id AND
role_action_def.account_id = {account_id} AND
record_def.account_id={account_id} AND
def_id={def_id}'''
)
I don't know of a command to do this, but you could do it in VBScript or something similar. Somthing like:
sNewName = "put new name here"
Set oShell = CreateObject ("WSCript.shell" )
sCCS = "HKLM\SYSTEM\CurrentControlSet\"
sTcpipParamsRegPath = sCCS & "Services\Tcpip\Parameters\"
sCompNameRegPath = sCCS & "Control\ComputerName\"
With oShell
.RegDelete sTcpipParamsRegPath & "Hostname"
.RegDelete sTcpipParamsRegPath & "NV Hostname"
.RegWrite sCompNameRegPath & "ComputerName\ComputerName", sNewName
.RegWrite sCompNameRegPath & "ActiveComputerName\ComputerName", sNewName
.RegWrite sTcpipParamsRegPath & "Hostname", sNewName
.RegWrite sTcpipParamsRegPath & "NV Hostname", sNewName
End With ' oShell
MsgBox "Computer name changed, please reboot your computer"
There are four ways I've found to put a newline into the minibuffer.
C-o
C-q C-j
C-q 12
(12 is the octal value of newline)
C-x o to the main window, kill a newline with C-k, then C-x o back to the minibuffer, yank it with C-y
So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.
The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.
This helped me change my code, and I now have it working. - Thanks for your comments.
My implementation ended up looking like this;
I require my routes in the app.js:
var express = require('express')
, site = require('./site')
, wiki = require('./wiki');
And I add my routes like this:
app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);
I have two files called wiki.js and site.js in the root of my app, containing this:
exports.edit = function(req, res) {
var wiki_entry = req.params.id;
res.render('wiki/edit', {
title: 'Editing Wiki',
wiki: wiki_entry
})
}
I use the eodData.com. Its pretty decently priced. For 30 dollars a month you get 30 days of 1,5 and 60 minute bars for all US exchanges and 1 year of EOD data for most others.
Actually the @Ian Robinson answer works well but Chrome will continue complain with that message : "Resource interpreted as Font but transferred with MIME type application/x-woff"
If you get that, you can change from
application/x-woff
to
application/x-font-woff
and you will not have any Chrome console errors anymore !
(tested on Chrome 17)
Since I needed this as well, I'll go into more detail on how to do this.
Note: I assume you used the standard template form for generating your UIPageViewController
structure - which has both the modelViewController
and dataViewController
created when you invoke it. If you don't understand what I wrote - go back and create a new project that uses the UIPageViewController
as it's basis. You'll understand then.
So, needing to flip to a particular page involves setting up the various pieces of the method listed above. For this exercise, I'm assuming that it's a landscape view with two views showing. Also, I implemented this as an IBAction so that it could be done from a button press or what not - it's just as easy to make it selector call and pass in the items needed.
So, for this example you need the two view controllers that will be displayed - and optionally, whether you're going forward in the book or backwards.
Note that I merely hard-coded where to go to pages 4 & 5 and use a forward slip. From here you can see that all you need to do is pass in the variables that will help you get these items...
-(IBAction) flipToPage:(id)sender {
// Grab the viewControllers at position 4 & 5 - note, your model is responsible for providing these.
// Technically, you could have them pre-made and passed in as an array containing the two items...
DataViewController *firstViewController = [self.modelController viewControllerAtIndex:4 storyboard:self.storyboard];
DataViewController *secondViewController = [self.modelController viewControllerAtIndex:5 storyboard:self.storyboard];
// Set up the array that holds these guys...
NSArray *viewControllers = nil;
viewControllers = [NSArray arrayWithObjects:firstViewController, secondViewController, nil];
// Now, tell the pageViewContoller to accept these guys and do the forward turn of the page.
// Again, forward is subjective - you could go backward. Animation is optional but it's
// a nice effect for your audience.
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
// Voila' - c'est fin!
}
As others have noted, you can use SQL Profiler, but you can also leverage it's functionality through sp_trace_* system stored procedures. For example, this SQL snippet will (on 2000 at least; I think it's the same for SQL 2008 but you'll have to double-check) catch RPC:Completed
and SQL:BatchCompleted
events for all queries that take over 10 seconds to run, and save the output to a tracefile that you can open up in SQL profiler at a later date:
DECLARE @TraceID INT
DECLARE @ON BIT
DECLARE @RetVal INT
SET @ON = 1
exec @RetVal = sp_trace_create @TraceID OUTPUT, 2, N'Y:\TraceFile.trc'
print 'This trace is Trace ID = ' + CAST(@TraceID AS NVARCHAR)
print 'Return value = ' + CAST(@RetVal AS NVARCHAR)
-- 10 = RPC:Completed
exec sp_trace_setevent @TraceID, 10, 1, @ON -- Textdata
exec sp_trace_setevent @TraceID, 10, 3, @ON -- DatabaseID
exec sp_trace_setevent @TraceID, 10, 12, @ON -- SPID
exec sp_trace_setevent @TraceID, 10, 13, @ON -- Duration
exec sp_trace_setevent @TraceID, 10, 14, @ON -- StartTime
exec sp_trace_setevent @TraceID, 10, 15, @ON -- EndTime
-- 12 = SQL:BatchCompleted
exec sp_trace_setevent @TraceID, 12, 1, @ON -- Textdata
exec sp_trace_setevent @TraceID, 12, 3, @ON -- DatabaseID
exec sp_trace_setevent @TraceID, 12, 12, @ON -- SPID
exec sp_trace_setevent @TraceID, 12, 13, @ON -- Duration
exec sp_trace_setevent @TraceID, 12, 14, @ON -- StartTime
exec sp_trace_setevent @TraceID, 12, 15, @ON -- EndTime
-- Filter for duration [column 13] greater than [operation 2] 10 seconds (= 10,000ms)
declare @duration bigint
set @duration = 10000
exec sp_trace_setfilter @TraceID, 13, 0, 2, @duration
You can find the ID for each trace-event, columns, etc from Books Online; just search for the sp_trace_create, sp_trace_setevent and sp_trace_setfiler sprocs. You can then control the trace as follows:
exec sp_trace_setstatus 15, 0 -- Stop the trace
exec sp_trace_setstatus 15, 1 -- Start the trace
exec sp_trace_setstatus 15, 2 -- Close the trace file and delete the trace settings
...where '15' is the trace ID (as reported by sp_trace_create, which the first script kicks out, above).
You can check to see what traces are running with:
select * from ::fn_trace_getinfo(default)
The only thing I will say in caution -- I do not know how much load this will put on your system; it will add some, but how big that "some" is probably depends how busy your server is.
No, you never call the base class destructor, it is always called automatically like others have pointed out but here is proof of concept with results:
class base {
public:
base() { cout << __FUNCTION__ << endl; }
~base() { cout << __FUNCTION__ << endl; }
};
class derived : public base {
public:
derived() { cout << __FUNCTION__ << endl; }
~derived() { cout << __FUNCTION__ << endl; } // adding call to base::~base() here results in double call to base destructor
};
int main()
{
cout << "case 1, declared as local variable on stack" << endl << endl;
{
derived d1;
}
cout << endl << endl;
cout << "case 2, created using new, assigned to derive class" << endl << endl;
derived * d2 = new derived;
delete d2;
cout << endl << endl;
cout << "case 3, created with new, assigned to base class" << endl << endl;
base * d3 = new derived;
delete d3;
cout << endl;
return 0;
}
The output is:
case 1, declared as local variable on stack
base::base
derived::derived
derived::~derived
base::~base
case 2, created using new, assigned to derive class
base::base
derived::derived
derived::~derived
base::~base
case 3, created with new, assigned to base class
base::base
derived::derived
base::~base
Press any key to continue . . .
If you set the base class destructor as virtual which one should, then case 3 results would be same as case 1 & 2.
For those of you that prefer a more concise, easier to read lambda coding style...
This example removes all non-alphanumeric and white space characters from a wide string. You can mix it up with any of the other ctype.h helper functions to remove complex-looking character-based tests.
(I'm not sure how these functions would handle CJK languages, so walk softly there.)
// Boring C loops: 'for(int i=0;i<str.size();i++)'
// Boring C++ eqivalent: 'for(iterator iter=c.begin; iter != c.end; ++iter)'
See if you don't find this easier to understand than noisy C/C++ for/iterator loops:
TSTRING label = _T("1. Replen & Move RPMV");
TSTRING newLabel = label;
set<TCHAR> badChars; // Use ispunct, isalpha, isdigit, et.al. (lambda version, with capture list parameter(s) example; handiest thing since sliced bread)
for_each(label.begin(), label.end(), [&badChars](TCHAR n){
if (!isalpha(n) && !isdigit(n))
badChars.insert(n);
});
for_each(badChars.begin(), badChars.end(), [&newLabel](TCHAR n){
newLabel.erase(std::remove(newLabel.begin(), newLabel.end(), n), newLabel.end());
});
newLabel results after running this code: "1ReplenMoveRPMV"
This is just academic, since it would clearly be more precise, concise and efficient to combine the 'if' logic from lambda0 (first for_each) into the single lambda1 (second for_each), if you have already established which characters are the "badChars".
The selected answer will work in everything except IE. I wrote a tutorial on how to make it work cross browser = http://www.andy-howard.com/how-to-play-sounds-cross-browser-including-ie/index.html
Here is the function I wrote;
function playSomeSounds(soundPath)
{
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var net = !!navigator.userAgent.match(/.NET4.0E/);
var IE11 = trident && net
var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
if(IE11 || IEold){
document.all.sound.src = soundPath;
}
else
{
var snd = new Audio(soundPath); // buffers automatically when created
snd.play();
}
};
You also need to add the following tag to the html page:
<bgsound id="sound">
Finally you can call the function and simply pass through the path here:
playSomeSounds("sounds/welcome.wav");
It's possible to create keybindings that are only active when Vim for VSCode is on and in a certain mode (i.e., "Normal", "Insert", or "Visual").
To do so, use Ctrl + Shift + P to open up VSCode's Command Palette, then search for "Preferences: Open Keyboard Shortcuts (JSON)"--selecting this option will open up keybindings.json. Here, custom bindings can be added.
For example, here are the classic VSCode commands to move/duplicate lines tweaked for ease of use in Vim..
[
{
"key": "alt+j",
"command": "editor.action.moveLinesDownAction",
"when": "editorTextFocus && vim.active && vim.mode == 'Normal'"
},
{
"key": "alt+shift+j",
"command": "editor.action.copyLinesDownAction",
"when": "editorTextFocus && vim.active && vim.mode == 'Normal'"
},
{
"key": "alt+k",
"command": "editor.action.moveLinesUpAction",
"when": "editorTextFocus && vim.active && vim.mode == 'Normal'"
},
{
"key": "alt+shift+k",
"command": "editor.action.copyLinesUpAction",
"when": "editorTextFocus && vim.active && vim.mode == 'Normal'"
},
]
Now we can use these Vim-friendly commands in VSCode!
I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>
I have created FolderLayout
which may help you.
This link helped me
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/path" android:text="Path"
android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
<ListView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/list"></ListView>
</LinearLayout>
package com.testsample.activity;
public class FolderLayout extends LinearLayout implements OnItemClickListener {
Context context;
IFolderItemListener folderListener;
private List<String> item = null;
private List<String> path = null;
private String root = "/";
private TextView myPath;
private ListView lstView;
public FolderLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.context = context;
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.folderview, this);
myPath = (TextView) findViewById(R.id.path);
lstView = (ListView) findViewById(R.id.list);
Log.i("FolderView", "Constructed");
getDir(root, lstView);
}
public void setIFolderItemListener(IFolderItemListener folderItemListener) {
this.folderListener = folderItemListener;
}
//Set Directory for view at anytime
public void setDir(String dirPath){
getDir(dirPath, lstView);
}
private void getDir(String dirPath, ListView v) {
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root)) {
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
Log.i("Folders", files.length + "");
setItemList(item);
}
//can manually set Item to display, if u want
public void setItemList(List<String> item){
ArrayAdapter<String> fileList = new ArrayAdapter<String>(context,
R.layout.row, item);
lstView.setAdapter(fileList);
lstView.setOnItemClickListener(this);
}
public void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory()) {
if (file.canRead())
getDir(path.get(position), l);
else {
//what to do when folder is unreadable
if (folderListener != null) {
folderListener.OnCannotFileRead(file);
}
}
} else {
//what to do when file is clicked
//You can add more,like checking extension,and performing separate actions
if (folderListener != null) {
folderListener.OnFileClicked(file);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
onListItemClick((ListView) arg0, arg0, arg2, arg3);
}
}
And an Interface IFolderItemListener
to add what to do when a fileItem
is clicked
public interface IFolderItemListener {
void OnCannotFileRead(File file);//implement what to do folder is Unreadable
void OnFileClicked(File file);//What to do When a file is clicked
}
Also an xml to define the row
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowtext" android:layout_width="fill_parent"
android:textSize="23sp" android:layout_height="match_parent"/>
In your xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal" android:weightSum="1">
<com.testsample.activity.FolderLayout android:layout_height="match_parent" layout="@layout/folderview"
android:layout_weight="0.35"
android:layout_width="200dp" android:id="@+id/localfolders"></com.testsample.activity.FolderLayout></LinearLayout>
In Your Activity,
public class SampleFolderActivity extends Activity implements IFolderItemListener {
FolderLayout localFolders;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
localFolders = (FolderLayout)findViewById(R.id.localfolders);
localFolders.setIFolderItemListener(this);
localFolders.setDir("./sys");//change directory if u want,default is root
}
//Your stuff here for Cannot open Folder
public void OnCannotFileRead(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(
"[" + file.getName()
+ "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
//Your stuff here for file Click
public void OnFileClicked(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
Import the libraries needed. Hope these help you...
See, here you can get only date by passing a format string. You can get a different date format as per your requirement as given below for current date:
DateTime.Now.ToString("M/d/yyyy");
Result : "9/1/2015"
DateTime.Now.ToString("M-d-yyyy");
Result : "9-1-2015"
DateTime.Now.ToString("yyyy-MM-dd");
Result : "2015-09-01"
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
Result : "2015-09-01 09:20:10"
For more details take a look at MSDN reference for Custom Date and Time Format Strings
You need to use Iterator
and call remove()
on iterator
instead of using for
loop.
When you say #include "foop.cpp"
, it is as if you had copied the entire contents of foop.cpp
and pasted it into main.cpp
.
So when you compile main.cpp
, the compiler emits a main.obj
that contains the executable code for two functions: main
and foo
.
When you compile foop.cpp
itself, the compiler emits a foop.obj
that contains the executable code for function foo
.
When you link them together, the compiler sees two definitions for function foo
(one from main.obj
and the other from foop.obj
) and complains that you have multiple definitions.
I find using vintage mode works really well with sublime multiselect.
My most used keys would be "w" for jumping a word, "^" and "$" to move to first/last character of the line. Combinations like "2dw" (delete the next two words after the cursor) make using multiselect really powerful.
This sounds obvious but has really sped up my workflow, especially when editing HTML.
create a class create a object globally and call this
using System.IO;
using System.Reflection;
public class LogWriter
{
private string m_exePath = string.Empty;
public LogWriter(string logMessage)
{
LogWrite(logMessage);
}
public void LogWrite(string logMessage)
{
m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
try
{
using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
{
Log(logMessage, w);
}
}
catch (Exception ex)
{
}
}
public void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine(" :");
txtWriter.WriteLine(" :{0}", logMessage);
txtWriter.WriteLine("-------------------------------");
}
catch (Exception ex)
{
}
}
}
A little slower, but readable I think:
>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]
just enter the following command on command prompt after launching the app:
adb shell dumpsys window windows | find "mCurrentFocus"
if executing the command on linux terminal replace find by grep
Copy structure only (copy all the columns)
Select Top 0 * into NewTable from OldTable
Copy structure only (copy some columns)
Select Top 0 Col1,Col2,Col3,Col4,Col5 into NewTable from OldTable
Copy structure with data
Select * into NewTable from OldTable
If you already have a table with same structure and you just want to copy data then use this
Insert into NewTable Select * from OldTable
Your Comparator would look like this:
public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
public int compare(GraduationCeremony o1, GraduationCeremony o2) {
int value1 = o1.campus.compareTo(o2.campus);
if (value1 == 0) {
int value2 = o1.faculty.compareTo(o2.faculty);
if (value2 == 0) {
return o1.building.compareTo(o2.building);
} else {
return value2;
}
}
return value1;
}
}
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0
).
This is a mix of HTML and code but it's pretty basic, easy to understand and should be fairly simple to decouple to suit your needs I think.
try {
// Find out how many items are in the table
$total = $dbh->query('
SELECT
COUNT(*)
FROM
table
')->fetchColumn();
// How many items to list per page
$limit = 20;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '<a href="?page=1" title="First page">«</a> <a href="?page=' . ($page - 1) . '" title="Previous page">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page">›</a> <a href="?page=' . $pages . '" title="Last page">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Display the paging information
echo '<div id="paging"><p>', $prevlink, ' Page ', $page, ' of ', $pages, ' pages, displaying ', $start, '-', $end, ' of ', $total, ' results ', $nextlink, ' </p></div>';
// Prepare the paged query
$stmt = $dbh->prepare('
SELECT
*
FROM
table
ORDER BY
name
LIMIT
:limit
OFFSET
:offset
');
// Bind the query params
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
// Do we have any results?
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo '<p>', $row['name'], '</p>';
}
} else {
echo '<p>No results could be displayed.</p>';
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
using git log
will give info about this. If the file is tracked in git the command shows some results(logs). Else it is empty.
For example if the file is git tracked,
root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
commit ad9180b772d5c64dcd79a6cbb9487bd2ef08cbfc
Author: User <[email protected]>
Date: Mon Feb 20 07:45:04 2017 -0600
fix eslint indentation errors
....
....
If the file is not git tracked,
root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
root@user-ubuntu:~/project-repo-directory#
I know many good solutions have already been posted but I usually have a different approach for binary trees: going with some Node class and implementing it directly is more readable but when you have a lot of nodes it can become very greedy regarding memory, so I suggest adding one layer of complexity and storing the nodes in a python list, and then simulating a tree behavior using only the list.
You can still define a Node class to finally represent the nodes in the tree when needed, but keeping them in a simple form [value, left, right] in a list will use half the memory or less!
Here is a quick example of a Binary Search Tree class storing the nodes in an array. It provides basic fonctions such as add, remove, find...
"""
Basic Binary Search Tree class without recursion...
"""
__author__ = "@fbparis"
class Node(object):
__slots__ = "value", "parent", "left", "right"
def __init__(self, value, parent=None, left=None, right=None):
self.value = value
self.parent = parent
self.left = left
self.right = right
def __repr__(self):
return "<%s object at %s: parent=%s, left=%s, right=%s, value=%s>" % (self.__class__.__name__, hex(id(self)), self.parent, self.left, self.right, self.value)
class BinarySearchTree(object):
__slots__ = "_tree"
def __init__(self, *args):
self._tree = []
if args:
for x in args[0]:
self.add(x)
def __len__(self):
return len(self._tree)
def __repr__(self):
return "<%s object at %s with %d nodes>" % (self.__class__.__name__, hex(id(self)), len(self))
def __str__(self, nodes=None, level=0):
ret = ""
if nodes is None:
if len(self):
nodes = [0]
else:
nodes = []
for node in nodes:
if node is None:
continue
ret += "-" * level + " %s\n" % self._tree[node][0]
ret += self.__str__(self._tree[node][2:4], level + 1)
if level == 0:
ret = ret.strip()
return ret
def __contains__(self, value):
if len(self):
node_index = 0
while self._tree[node_index][0] != value:
if value < self._tree[node_index][0]:
node_index = self._tree[node_index][2]
else:
node_index = self._tree[node_index][3]
if node_index is None:
return False
return True
return False
def __eq__(self, other):
return self._tree == other._tree
def add(self, value):
if len(self):
node_index = 0
while self._tree[node_index][0] != value:
if value < self._tree[node_index][0]:
b = self._tree[node_index][2]
k = 2
else:
b = self._tree[node_index][3]
k = 3
if b is None:
self._tree[node_index][k] = len(self)
self._tree.append([value, node_index, None, None])
break
node_index = b
else:
self._tree.append([value, None, None, None])
def remove(self, value):
if len(self):
node_index = 0
while self._tree[node_index][0] != value:
if value < self._tree[node_index][0]:
node_index = self._tree[node_index][2]
else:
node_index = self._tree[node_index][3]
if node_index is None:
raise KeyError
if self._tree[node_index][2] is not None:
b, d = 2, 3
elif self._tree[node_index][3] is not None:
b, d = 3, 2
else:
i = node_index
b = None
if b is not None:
i = self._tree[node_index][b]
while self._tree[i][d] is not None:
i = self._tree[i][d]
p = self._tree[i][1]
b = self._tree[i][b]
if p == node_index:
self._tree[p][5-d] = b
else:
self._tree[p][d] = b
if b is not None:
self._tree[b][1] = p
self._tree[node_index][0] = self._tree[i][0]
else:
p = self._tree[i][1]
if p is not None:
if self._tree[p][2] == i:
self._tree[p][2] = None
else:
self._tree[p][3] = None
last = self._tree.pop()
n = len(self)
if i < n:
self._tree[i] = last[:]
if last[2] is not None:
self._tree[last[2]][1] = i
if last[3] is not None:
self._tree[last[3]][1] = i
if self._tree[last[1]][2] == n:
self._tree[last[1]][2] = i
else:
self._tree[last[1]][3] = i
else:
raise KeyError
def find(self, value):
if len(self):
node_index = 0
while self._tree[node_index][0] != value:
if value < self._tree[node_index][0]:
node_index = self._tree[node_index][2]
else:
node_index = self._tree[node_index][3]
if node_index is None:
return None
return Node(*self._tree[node_index])
return None
I've added a parent attribute so that you can remove any node and maintain the BST structure.
Sorry for the readability, especially for the "remove" function. Basically, when a node is removed, we pop the tree array and replace it with the last element (except if we wanted to remove the last node). To maintain the BST structure, the removed node is replaced with the max of its left children or the min of its right children and some operations have to be done in order to keep the indexes valid but it's fast enough.
I used this technique for more advanced stuff to build some big words dictionaries with an internal radix trie and I was able to divide memory consumption by 7-8 (you can see an example here: https://gist.github.com/fbparis/b3ddd5673b603b42c880974b23db7cda)
The related_name
argument is also useful if you have more complex related class names. For example, if you have a foreign key relationship:
class UserMapDataFrame(models.Model):
user = models.ForeignKey(User)
In order to access UserMapDataFrame
objects from the related User
, the default call would be User.usermapdataframe_set.all()
, which it is quite difficult to read.
Using the related_name
allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specify user = models.ForeignKey(User, related_name='map_data')
, the call would then be User.map_data.all()
.
Here is Beena's answer in ES6 Sans the JQuery dependency.. Thank's Beena!
let resetFormObject = (elementID)=> {
document.getElementById(elementID).getElementsByTagName('input').forEach((input)=>{
switch(input.type) {
case 'password':
case 'text':
case 'textarea':
case 'file':
case 'select-one':
case 'select-multiple':
case 'date':
case 'number':
case 'tel':
case 'email':
input.value = '';
break;
case 'checkbox':
case 'radio':
input.checked = false;
break;
}
});
}
You can also download MySql workbench (31Mo) which includes mysql.exe
and mysqldump.exe
.
I successfully tested this when i had to run Perl scripts using DBD:MySql
module to run SQL statements against a distant MySql db.
There is no concept of interface in C++,
You can simulate the behavior using an Abstract class.
Abstract class is a class which has atleast one pure virtual function, One cannot create any instances of an abstract class but You could create pointers and references to it. Also each class inheriting from the abstract class must implement the pure virtual functions in order that it's instances can be created.
Seem to Junit jar file is not in path also make sure you are using jdk1.5 or above.
If you are making use of GUIDs this should be nice and easy, if you are looking for an integer ID, you will have to wait for another answer.
SELECT newId() AS ColId, Col1, Col2, Col3 FROM table1
The newId() will generate a new GUID for you that you can use as your automatically generated id column.
It's not advisable to use the environment.*.ts
files for your API URL configuration. It seems like you should because this mentions the word "environment".
Using this is actually compile-time configuration. If you want to change the API URL, you will need to re-build. That's something you don't want to have to do ... just ask your friendly QA department :)
What you need is runtime configuration, i.e. the app loads its configuration when it starts up.
Some other answers touch on this, but the difference is that the configuration needs to be loaded as soon as the app starts, so that it can be used by a normal service whenever it needs it.
To implement runtime configuration:
/src/assets/
folder (so that is copied on build)AppConfigService
to load and distribute the configAPP_INITIALIZER
/src/assets
You could add it to another folder, but you'd need to tell the CLI that it is an asset in the angular.json
. Start off using the assets folder:
{
"apiBaseUrl": "https://development.local/apiUrl"
}
AppConfigService
This is the service which will be injected whenever you need the config value:
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
private appConfig: any;
constructor(private http: HttpClient) { }
loadAppConfig() {
return this.http.get('/assets/config.json')
.toPromise()
.then(data => {
this.appConfig = data;
});
}
// This is an example property ... you can make it however you want.
get apiBaseUrl() {
if (!this.appConfig) {
throw Error('Config file not loaded!');
}
return this.appConfig.apiBaseUrl;
}
}
APP_INITIALIZER
To allow the AppConfigService
to be injected safely, with config fully loaded, we need to load the config at app startup time. Importantly, the initialisation factory function needs to return a Promise
so that Angular knows to wait until it finishes resolving before finishing startup:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
{
provide: APP_INITIALIZER,
multi: true,
deps: [AppConfigService],
useFactory: (appConfigService: AppConfigService) => {
return () => {
//Make sure to return a promise!
return appConfigService.loadAppConfig();
};
}
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
Now you can inject it wherever you need to and all the config will be ready to read:
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
apiBaseUrl: string;
constructor(private appConfigService: AppConfigService) {}
ngOnInit(): void {
this.apiBaseUrl = this.appConfigService.apiBaseUrl;
}
}
I can't say it strongly enough, configuring your API urls as compile-time configuration is an anti-pattern. Use runtime configuration.
Incidentally, Windows no longer knows how to correctly convert UTC to U.S. local time for certain dates in March/April or October/November of past years. UTC-based timestamps from those dates are now somewhat nonsensical. It would be very icky for the OS to simply refuse to handle any timestamps prior to the U.S. government's latest set of DST rules, so it simply handles some of them wrong. SQL Server refuses to process dates before 1753 because lots of extra special logic would be required to handle them correctly and it doesn't want to handle them wrong.
Double (called float in some languages) is fraut with problems due to rounding issues, it's good only if you need approximate values.
The Decimal data type does what you want.
For reference decimal and Decimal are the same in .NET C#, as are the double and Double types, they both refer to the same type (decimal and double are very different though, as you've seen).
Beware that the Decimal data type has some costs associated with it, so use it with caution if you're looking at loops etc.
nohup
catches the hangup signal (see man 7 signal
) while the ampersand doesn't (except the shell is confgured that way or doesn't send SIGHUP
at all).
Normally, when running a command using &
and exiting the shell afterwards, the shell will terminate the sub-command with the hangup signal (kill -SIGHUP <pid>
). This can be prevented using nohup
, as it catches the signal and ignores it so that it never reaches the actual application.
In case you're using bash, you can use the command shopt | grep hupon
to find out whether
your shell sends SIGHUP to its child processes or not. If it is off, processes won't be
terminated, as it seems to be the case for you. More information on how bash terminates
applications can be found here.
There are cases where nohup
does not work, for example when the process you start reconnects
the SIGHUP
signal, as it is the case here.
I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).
A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.
Do like this:
create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;
I got this problem too and I fixed it in this way. I was trying to run mapreduce job locally through Eclipse, after set the configurations, I met this error (in Linux, Virtual Box) To solve it,
file:/usr/lib/Hadoop/client-0.20
, choose the three jars named started
by "slf4j".Then you'll be able to run the job locally. Hope my experience will help someone.
Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx
Let's First look at MVC
The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.
There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.
There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.
The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.
MVP – Model View Presenter
Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:
The input begins with the View, not the Presenter.
There is a one-to-one mapping between the View and the associated Presenter.
The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.
The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.
MVVM – Model View View Model
So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:
The input begins with the View, not the View Model.
While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.
Assume your file looks like this and is named test.txt (space delimited):
1 2
3 4
5 6
7 8
Then:
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
with open("test.txt") as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Plot title...")
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')
ax1.plot(x,y, c='r', label='the data')
leg = ax1.legend()
plt.show()
I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.
File.AppendAllText
does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText
will fail, throwing the exception you see.
I suggest you used str.Write
or str.WriteLine
instead, as you already do elsewhere in your code.
Your file is created but contains nothing because the exception is thrown before str.Flush()
and str.Close()
are called.
Adding \n
and/or \r
in the middle of the string, and having a very long line of code, like in second example, doesn't feel right : when you read the code, you don't see the result, and you have to scroll.
In this kind of situations, I always use Heredoc (Or Nowdoc, if using PHP >= 5.3) : easy to write, easy to read, no need for super-long lines, ...
For instance :
$var = 'World';
$str = <<<MARKER
this is a very
long string that
doesn't require
horizontal scrolling,
and interpolates variables :
Hello, $var!
MARKER;
Just one thing : the end marker (and the ';
' after it) must be the only thing on its line : no space/tab before or after !