Not using nmap... but this is an alternative...
arp -n|grep -i B0:D3:93|awk '{print $1}'
Try Winhttrack
...offline browser utility.
It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.
WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
Don't use tellg
to determine the exact size of the file. The length determined by tellg
will be larger than the number of characters can be read from the file.
From stackoverflow question tellg() function give wrong size of file? tellg
does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It's not even guaranteed that you can convert the type to an integral type.). For Windows (and most non-Unix systems), in text mode, there is no direct and immediate mapping between what tellg returns and the number of bytes you must read to get to that position.
If it is important to know exactly how many bytes you can read, the only way of reliably doing so is by reading. You should be able to do this with something like:
#include <fstream>
#include <limits>
ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear(); // Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );
Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:
my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);
Make an images folder inside src(/src/images) And keep your image in it. Then import this image in your component(use your relative path). Like below-
import imageSrc from './images/image-name.jpg';
And then in your component.
<img title="my-img" src={imageSrc} alt="my-img" />
Another way is to keep images in public folder and import them using relative path. For this make an image folder in public folder and keep your image in it. And then in your component use it like below.
<img title="my-img" src='/images/my-image.jpg' alt="my-img" />
Both method work but first one is recommended because its cleaner way and images are handled by webpack during build time.
event.target
is of type EventTarget
which doesn't always have a value. If it's a DOM element you need to cast it to the correct type:
handleChange(event) {
this.setState({value: (event.target as HTMLInputElement).value});
}
This will infer the "correct" type for the state variable as well though being explicit is probably better
Alternatively you could use:
if ($('#navigation a').is(".active")) {
$(this).parent().addClass("active");
}
http://www.rgagnon.com/javadetails/java-0198.html
import javax.swing.text.PlainDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
public class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
Then
import java.awt.*;
import javax.swing.*;
public class DemoJTextFieldWithLimit extends JApplet{
JTextField textfield1;
JLabel label1;
public void init() {
getContentPane().setLayout(new FlowLayout());
//
label1 = new JLabel("max 10 chars");
textfield1 = new JTextField(15);
getContentPane().add(label1);
getContentPane().add(textfield1);
textfield1.setDocument
(new JTextFieldLimit(10));
}
}
(first result from google)
If you really want to avoid touching this code, you can use Powermockito (PowerMock for Mockito).
With this, amongst many other things, you can mock the construction of new objects in a very easy way.
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("E:/TextFieldForm.pdf"));
document.open();
PdfPTable table = new PdfPTable(2);
table.getDefaultCell().setPadding(5f); // Code 1
table.setHorizontalAlignment(Element.ALIGN_LEFT);
PdfPCell cell;
// Code 2, add name TextField
table.addCell("Name");
TextField nameField = new TextField(writer,
new Rectangle(0,0,200,10), "nameField");
nameField.setBackgroundColor(Color.WHITE);
nameField.setBorderColor(Color.BLACK);
nameField.setBorderWidth(1);
nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
nameField.setText("");
nameField.setAlignment(Element.ALIGN_LEFT);
nameField.setOptions(TextField.REQUIRED);
cell = new PdfPCell();
cell.setMinimumHeight(10);
cell.setCellEvent(new FieldCell(nameField.getTextField(),
200, writer));
table.addCell(cell);
// force upper case javascript
writer.addJavaScript(
"var nameField = this.getField('nameField');" +
"nameField.setAction('Keystroke'," +
"'forceUpperCase()');" +
"" +
"function forceUpperCase(){" +
"if(!event.willCommit)event.change = " +
"event.change.toUpperCase();" +
"}");
// Code 3, add empty row
table.addCell("");
table.addCell("");
// Code 4, add age TextField
table.addCell("Age");
TextField ageComb = new TextField(writer, new Rectangle(0,
0, 30, 10), "ageField");
ageComb.setBorderColor(Color.BLACK);
ageComb.setBorderWidth(1);
ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
ageComb.setText("12");
ageComb.setAlignment(Element.ALIGN_RIGHT);
ageComb.setMaxCharacterLength(2);
ageComb.setOptions(TextField.COMB |
TextField.DO_NOT_SCROLL);
cell = new PdfPCell();
cell.setMinimumHeight(10);
cell.setCellEvent(new FieldCell(ageComb.getTextField(),
30, writer));
table.addCell(cell);
// validate age javascript
writer.addJavaScript(
"var ageField = this.getField('ageField');" +
"ageField.setAction('Validate','checkAge()');" +
"function checkAge(){" +
"if(event.value < 12){" +
"app.alert('Warning! Applicant\\'s age can not" +
" be younger than 12.');" +
"event.value = 12;" +
"}}");
// add empty row
table.addCell("");
table.addCell("");
// Code 5, add age TextField
table.addCell("Comment");
TextField comment = new TextField(writer,
new Rectangle(0, 0,200, 100), "commentField");
comment.setBorderColor(Color.BLACK);
comment.setBorderWidth(1);
comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
comment.setText("");
comment.setOptions(TextField.MULTILINE |
TextField.DO_NOT_SCROLL);
cell = new PdfPCell();
cell.setMinimumHeight(100);
cell.setCellEvent(new FieldCell(comment.getTextField(),
200, writer));
table.addCell(cell);
// check comment characters length javascript
writer.addJavaScript(
"var commentField = " +
"this.getField('commentField');" +
"commentField" +
".setAction('Keystroke','checkLength()');" +
"function checkLength(){" +
"if(!event.willCommit && " +
"event.value.length > 100){" +
"app.alert('Warning! Comment can not " +
"be more than 100 characters.');" +
"event.change = '';" +
"}}");
// add empty row
table.addCell("");
table.addCell("");
// Code 6, add submit button
PushbuttonField submitBtn = new PushbuttonField(writer,
new Rectangle(0, 0, 35, 15),"submitPOST");
submitBtn.setBackgroundColor(Color.GRAY);
submitBtn.
setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
submitBtn.setText("POST");
submitBtn.setOptions(PushbuttonField.
VISIBLE_BUT_DOES_NOT_PRINT);
PdfFormField submitField = submitBtn.getField();
submitField.setAction(PdfAction
.createSubmitForm("",null, PdfAction.SUBMIT_HTML_FORMAT));
cell = new PdfPCell();
cell.setMinimumHeight(15);
cell.setCellEvent(new FieldCell(submitField, 35, writer));
table.addCell(cell);
// Code 7, add reset button
PushbuttonField resetBtn = new PushbuttonField(writer,
new Rectangle(0, 0, 35, 15), "reset");
resetBtn.setBackgroundColor(Color.GRAY);
resetBtn.setBorderStyle(
PdfBorderDictionary.STYLE_BEVELED);
resetBtn.setText("RESET");
resetBtn
.setOptions(
PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
PdfFormField resetField = resetBtn.getField();
resetField.setAction(PdfAction.createResetForm(null, 0));
cell = new PdfPCell();
cell.setMinimumHeight(15);
cell.setCellEvent(new FieldCell(resetField, 35, writer));
table.addCell(cell);
document.add(table);
document.close();
}
class FieldCell implements PdfPCellEvent{
PdfFormField formField;
PdfWriter writer;
int width;
public FieldCell(PdfFormField formField, int width,
PdfWriter writer){
this.formField = formField;
this.width = width;
this.writer = writer;
}
public void cellLayout(PdfPCell cell, Rectangle rect,
PdfContentByte[] canvas){
try{
// delete cell border
PdfContentByte cb = canvas[PdfPTable
.LINECANVAS];
cb.reset();
formField.setWidget(
new Rectangle(rect.left(),
rect.bottom(),
rect.left()+width,
rect.top()),
PdfAnnotation
.HIGHLIGHT_NONE);
writer.addAnnotation(formField);
}catch(Exception e){
System.out.println(e);
}
}
}
Below command worked for me docker build -t docker-whale -f Dockerfile.txt .
Have you tried this?
Out = subprocess.Popen('/usr/local/bin/script hostname = actual_server_name -p LONGLIST'.split(), shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Edited per the apt comment from @J.F.Sebastian
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
You can use style display:none with tr to hide and it will work with all browsers.
In general, you either have to specify $(OBJDIR)
on the left hand side of all the rules that place files in $(OBJDIR)
, or you can run make from $(OBJDIR)
.
VPATH
is for sources, not for objects.
Take a look at these two links for more explanation, and a "clever" workaround.
In theory, according to RFC 4329, application/javascript
.
The reason it is supposed to be application
is not anything to do with whether the type is readable or executable. It's because there are custom charset-determination mechanisms laid down by the language/type itself, rather than just the generic charset
parameter. A subtype of text
should be capable of being transcoded by a proxy to another charset, changing the charset parameter. This is not true of JavaScript because:
a. the RFC says user-agents should be doing BOM-sniffing on the script to determine type (I'm not sure if any browsers actually do this though);
b. browsers use other information—the including page's encoding and in some browsers the script charset
attribute—to determine the charset. So any proxy that tried to transcode the resource would break its users. (Of course in reality no-one ever uses transcoding proxies anyway, but that was the intent.)
Therefore the exact bytes of the file must be preserved exactly, which makes it a binary application
type and not technically character-based text
.
For the same reason, application/xml
is officially preferred over text/xml
: XML has its own in-band charset signalling mechanisms. And everyone ignores application
for XML, too.
text/javascript
and text/xml
may not be the official Right Thing, but there are what everyone uses today for compatibility reasons, and the reasons why they're not the right thing are practically speaking completely unimportant.
ReferenceLoopHandling.Error
(default) will error if a reference loop is encountered. This is why you get an exception.ReferenceLoopHandling.Serialize
is useful if objects are nested but not indefinitely.ReferenceLoopHandling.Ignore
will not serialize an object if it is a child object of itself.Example:
JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});
Should you have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid a StackOverflowException.
Example:
JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented,
new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
Pick what makes sense for the object you are serializing.
Reference http://james.newtonking.com/json/help/
You just have to define the property below inside the activity element in your AndroidManifest.xml
file. It will restrict your orientation to portrait.
android:screenOrientation="portrait"
Example:
<activity
android:name="com.example.demo_spinner.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
</activity>
if you want this to apply to the whole app define the property below inside the application tag like so:
<application>
android:screenOrientation="sensorPortrait"
</application>
Additionaly, as per Eduard Luca's comment below, you can also use screenOrientation="sensorPortrait"
if you want to enable rotation by 180 degrees.
What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles
By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.
You should try changing the value of -Xmx
and -Xms
.
In addition to anyListOf
above, you can always specify generics explicitly using this syntax:
when(mock.process(Matchers.<List<Bar>>any(List.class)));
Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:
when(mock.process(Matchers.any()));
Remember that neither any()
nor anyList()
will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class)
was changed to mean "any instanceof
Foo", but any()
still means "any value including null
".
NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers
. Older versions of Mockito will need to keep using org.mockito.Matchers
as above.
They can be different on word-addressable machines (e.g., Cray PVP systems).
Most computers today are byte-addressable machines, where each address refers to a byte of memory. There, all data pointers are usually the same size, namely the size of a machine address.
On word-adressable machines, each machine address refers instead to a word larger than a byte. On these, a (char *) or (void *) pointer to a byte of memory has to contain both a word address plus a byte offset within the addresed word.
http://docs.cray.com/books/004-2179-001/html-004-2179-001/rvc5mrwh.html
You can add the method below to your class for providing a default implementation of RestTemplate:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
FYI
In the new language Kotlin, you can use "String Templates" in your source code directly, no 3rd party library or template engine need to do the variable replacement.
It is a feature of the language itself.
See: https://kotlinlang.org/docs/reference/basic-types.html#string-templates
To convert tuples to list
(Commas were missing between the tuples in the given question, it was added to prevent error message)
Method 1:
level1 = (
(1,1,1,1,1,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,0,0,0,0,1),
(1,1,1,1,1,1))
level1 = [list(row) for row in level1]
print(level1)
Method 2:
level1 = map(list,level1)
print(list(level1))
Method 1 took --- 0.0019991397857666016 seconds ---
Method 2 took --- 0.0010001659393310547 seconds ---
Correction to top query above, to allow to run from any database
SELECT COUNT(COLUMN_NAME) FROM [*database*].INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table'
You might also have a use case where you want to delete a block of text and replace it .
Like this
Hello World
Hello World
You can visual block select before "W" and hit Shift+i - Type "Cool" - Hit ESC and then delete "World" by visual block selection .
Alternatively, the cooler way to do it is to just visual block select "World" in both lines. Type c for change
. Now you are in the insert
mode. Insert the stuff you want and hit ESC. Both gets reflected with lesser keystrokes.
Hello Cool
Hello Cool
This will have some overhead, but technically it does answer your question:
echo abc `#Put your comment here` \
def `#Another chance for a comment` \
xyz, etc.
And for pipelines specifically, there is a clean solution with no overhead:
echo abc | # Normal comment OK here
tr a-z A-Z | # Another normal comment OK here
sort | # The pipelines are automatically continued
uniq # Final comment
See Stack Overflow question How to Put Line Comment for a Multi-line Command.
I think an option for your purposes is git log --online --decorate
. This lets you know the checked commit, and the top commits for each branch that you have in your story line. By doing this, you have a nice view on the structure of your repo and the commits associated to a specific branch. I think reading this might help.
I faced similar issue in Eclipse when two consoles were opened when I started the Server program first and then the Client program. I used to stop the program in the single console thinking that it had closed the server, but it had only closed the client and not the server. I found running Java processes in my Task manager. This problem was solved by closing both Server and Client programs from their individual consoles(Eclipse shows console of latest active program). So when I started the Server program again, the port was again open to be captured.
Query plans can be obtained from an Extended Events session via the query_post_execution_showplan
event. Here's a sample XEvent session:
/*
Generated via "Query Detail Tracking" template.
*/
CREATE EVENT SESSION [GetExecutionPlan] ON SERVER
ADD EVENT sqlserver.query_post_execution_showplan(
ACTION(package0.event_sequence,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)),
/* Remove any of the following events (or include additional events) as desired. */
ADD EVENT sqlserver.error_reported(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.module_end(SET collect_statement=(1)
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.rpc_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sp_statement_completed(SET collect_object_name=(1)
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sql_batch_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sql_statement_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0))))
ADD TARGET package0.ring_buffer
WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=ON,STARTUP_STATE=OFF)
GO
After you create the session, (in SSMS) go to the Object Explorer and delve down into Management | Extended Events | Sessions. Right-click the "GetExecutionPlan" session and start it. Right-click it again and select "Watch Live Data".
Next, open a new query window and run one or more queries. Here's one for AdventureWorks:
USE AdventureWorks;
GO
SELECT p.Name AS ProductName,
NonDiscountSales = (OrderQty * UnitPrice),
Discounts = ((OrderQty * UnitPrice) * UnitPriceDiscount)
FROM Production.Product AS p
INNER JOIN Sales.SalesOrderDetail AS sod
ON p.ProductID = sod.ProductID
ORDER BY ProductName DESC;
GO
After a moment or two, you should see some results in the "GetExecutionPlan: Live Data" tab. Click one of the query_post_execution_showplan events in the grid, and then click the "Query Plan" tab below the grid. It should look similar to this:
EDIT: The XEvent code and the screen shot were generated from SQL/SSMS 2012 w/ SP2. If you're using SQL 2008/R2, you might be able to tweak the script to make it run. But that version doesn't have a GUI, so you'd have to extract the showplan XML, save it as a *.sqlplan file and open it in SSMS. That's cumbersome. XEvents didn't exist in SQL 2005 or earlier. So, if you're not on SQL 2012 or later, I'd strongly suggest one of the other answers posted here.
Hi i also come across same problem, i try many options ,but finally the most easy way is,click of down arrow present inside ProjectExplorer-> customize View->filter-> unchecked close project.
And will able to see all closed projects.
In lieu of Javascript, a shorter PHP-based solution could be:
<input type="date" name="date1" max=
<?php
echo date('Y-m-d');
?>
>
How to use autoexpect to pipe a password into a command:
These steps are illustrated with an Ubuntu 12.10 desktop. The exact commands for your distribution may be slightly different.
This is dangerous because you risk exposing whatever password you use to anyone who can read the autoexpect script file.
DO NOT expose your root password or power user passwords by piping them through expect like this. Root kits WILL find this in an instant and your box is owned.
EXPECT spawns a process, reads text that comes in then sends text predefined in the script file.
Make sure you have expect
and autoexpect
installed:
sudo apt-get install expect
sudo apt-get install expect-dev
Read up on it:
man expect
man autoexpect
Go to your home directory:
cd /home/el
User el
cannot chown a file to root and must enter a password:
touch testfile.txt
sudo chown root:root testfile.txt
[enter password to authorize the changing of the owner]
This is the password entry we want to automate. Restart the terminal to ensure that sudo asks us for the password again. Go to /home/el again and do this:
touch myfile.txt
autoexpect -f my_test_expect.exp sudo chown root:root myfile.txt
[enter password which authorizes the chown to root]
autoexpect done, file is my_test_expect.exp
You have created my_test_expect.exp
file. Your super secret password is stored plaintext in this file. This should make you VERY uncomfortable. Mitigate some discomfort by restricting permissions and ownership as much as possible:
sudo chown el my_test_expect.exp //make el the owner.
sudo chmod 700 my_test_expect.exp //make file only readable by el.
You see these sorts of commands at the bottom of my_test_expect.exp
:
set timeout -1
spawn sudo chown root:root myfile.txt
match_max 100000
expect -exact "\[sudo\] password for el: "
send -- "YourPasswordStoredInPlaintext\r"
expect eof
You will need to verify that the above expect commands are appropriate. If the autoexpect script is being overly sensitive or not sensitive enough then it will hang. In this case it's acceptable because the expect is waiting for text that will always arrive.
Run the expect script as user el:
expect my_test_expect.exp
spawn sudo chown root:root myfile.txt
[sudo] password for el:
The password contained in my_test_expect.exp was piped into a chown to root by user el. To see if the password was accepted, look at myfile.txt
:
ls -l
-rw-r--r-- 1 root root 0 Dec 2 14:48 myfile.txt
It worked because it is root, and el never entered a password. If you expose your root, sudo, or power user password with this script, then acquiring root on your box will be easy. Such is the penalty for a security system that lets everybody in no questions asked.
As in:
In [3]: os.path.exists('/d/temp')
Out[3]: True
Probably toss in a os.path.isdir(...)
to be sure.
In your compare
method, o1
and o2
are already elements in the movieItems
list. So, you should do something like this:
Collections.sort(movieItems, new Comparator<Movie>() {
public int compare(Movie m1, Movie m2) {
return m1.getDate().compareTo(m2.getDate());
}
});
How about select cast(cast my_datetime_field as date) as datetime)
? This results in the same date, with the time set to 00:00, but avoids any conversion to text and also avoids any explicit numeric rounding.
Destroy any pre-existing tooltip so we can repopulate with new tooltip content
$(element).tooltip("destroy");
$(element).tooltip({
title: message
});
Most basic example (live example here):
CSS:
#wrapper {
width: 500px;
margin: 0 auto;
}
HTML:
<body>
<div id="wrapper">
Piece of text inside a 500px width div centered on the page
</div>
</body>
How the principle works:
Create your wrapper and assign it a certain width. Then apply an automatic horizontal margin to it by using margin: 0 auto;
or margin-left: auto; margin-right: auto;
. The automatic margins make sure your element is centered.
One solution is to put them inside <center>
, like this:
<center>
<a href="http//www.google.com">Search</a>
<a href="Contact Us">Contact Us</a>
</center>
I've also created a jsfiddle for you: https://jsfiddle.net/9acgLf8e/
Try running this as a TSQL Script
SELECT 1
RETURN
SELECT 2
SELECT 3
The return ends the execution.
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.
Are you sure you want to do this? In essence, you're duplicating the data that is in the three original columns. From that point on, you'll need to make sure that the data in the combined field matches the data in the first three columns. This is more overhead for your application, and other processes that update the system will need to understand the relationship.
If you need the data, why not select in when you need it? The SQL for selecting what would be in that field would be:
SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;
This way, if the data in the fields changes, you don't have to update your combined field.
You could do it with a directive and mod_rewrite on Apache:
<Location /buyCrap.php>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</Location>
You could make the Location smarter over time using regular expressions if you want.
Index access (mentioned here) is the practical difference. If you need to access the successor or predecessor, you need SortedList. SortedDictionary cannot do that so you are fairly limited with how you can use the sorting (first / foreach).
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).
According to Android Sqlite get last insert row id there is another query:
SELECT rowid from your_table_name order by ROWID DESC limit 1
try this
SELECT
Orders.OrderNumber,
LineItems.Quantity,
LineItems.Description
FROM Orders
INNER JOIN (
SELECT
Orders.OrderNumber,
Max(LineItem.LineItemID) AS LineItemID
FROM Orders
INNER JOIN LineItems
ON Orders.OrderNumber = LineItems.OrderNumber
GROUP BY Orders.OrderNumber
) AS Items ON Orders.OrderNumber = Items.OrderNumber
INNER JOIN LineItems
ON Items.LineItemID = LineItems.LineItemID
SELECT *
FROM trees
WHERE trees.`title` COLLATE UTF8_GENERAL_CI LIKE '%elm%'
Actually, if you add COLLATE UTF8_GENERAL_CI
to your column's definition, you can just omit all these tricks: it will work automatically.
ALTER TABLE trees
MODIFY COLUMN title VARCHAR(…) CHARACTER
SET UTF8 COLLATE UTF8_GENERAL_CI.
This will also rebuild any indexes on this column so that they could be used for the queries without leading '%'
Your example Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"])
already contains "foo=bar" string as its body.
But if you really want string with custom format. You can do this:
Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: [:], encoding: .Custom({
(convertible, params) in
var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
}))
Note: parameters
should not be nil
UPDATE (Alamofire 4.0, Swift 3.0):
In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncoding
protocol.
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
Dynamic HTML element functionThe code in here with a little bit of modification and simplification:
<input disabled maxlength="3" size="3" value="10" id="counter">
<textarea onkeyup="textCounter(this,'counter',10);" id="message">
</textarea>
<script>
function textCounter(field,field2,maxlimit)
{
var countfield = document.getElementById(field2);
if ( field.value.length > maxlimit ) {
field.value = field.value.substring( 0, maxlimit );
return false;
} else {
countfield.value = maxlimit - field.value.length;
}
}
</script>
Hope this helps!
tip:
When merging the codes with your page, make sure the HTML elements(textarea
, input
) are loaded first before the scripts (Javascript functions)
If the number of commits that have not been pushed out is a single-digit number, which it often is, the easiest way is:
$ git checkout
git responds by telling you that you are "ahead N commits" relative your origin. So now just keep that number in mind when viewing logs. If you're "ahead by 3 commits", the top 3 commits in the history are still private.
Execute following commands step by step :
sudo npm uninstall -g angular-cli @angular/cli
sudo npm cache clean
npm install npm@latest -g
sudo npm install -g @angular/cli
npm rebuild node-sass --force
you can use JsonConvert.SerializeObject()
JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method
Interestingly enough, importing os.path will import all of os. try the following in the interactive prompt:
import os.path
dir(os)
The result will be the same as if you just imported os. This is because os.path will refer to a different module based on which operating system you have, so python will import os to determine which module to load for path.
With some modules, saying import foo
will not expose foo.bar
, so I guess it really depends the design of the specific module.
In general, just importing the explicit modules you need should be marginally faster. On my machine:
import os.path
: 7.54285810068e-06
seconds
import os
: 9.21904878972e-06
seconds
These times are close enough to be fairly negligible. Your program may need to use other modules from os
either now or at a later time, so usually it makes sense just to sacrifice the two microseconds and use import os
to avoid this error at a later time. I usually side with just importing os as a whole, but can see why some would prefer import os.path
to technically be more efficient and convey to readers of the code that that is the only part of the os
module that will need to be used. It essentially boils down to a style question in my mind.
You probably mean Notification.Builder.setLargeIcon(Bitmap)
, right? :)
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);
This is a great method of converting resource images into Android Bitmap
s.
The exception is thrown if
InvocationTargetException - if the underlying method throws an exception.
So if the method, that has been invoked with reflection API, throws an exception (runtime exception for example), the reflection API will wrap the exception into an InvocationTargetException
.
the request.rawurl will gives the content of current page it gives the exact path that you required
use HttpContext.Current.Request.RawUrl
This give you the date like in a social network : ["today","yesterday","dayoftheweek",etc..]
void main() {
DateTime now = new DateTime(2018,6,26);
print(date(now));
}
String date(DateTime tm) {
DateTime today = new DateTime.now();
Duration oneDay = new Duration(days: 1);
Duration twoDay = new Duration(days: 2);
Duration oneWeek = new Duration(days: 7);
String month;
switch (tm.month) {
case 1:
month = "january";
break;
case 2:
month = "february";
break;
case 3:
month = "march";
break;
case 4:
month = "april";
break;
case 5:
month = "may";
break;
case 6:
month = "june";
break;
case 7:
month = "july";
break;
case 8:
month = "august";
break;
case 9:
month = "september";
break;
case 10:
month = "october";
break;
case 11:
month = "november";
break;
case 12:
month = "december";
break;
}
Duration difference = today.difference(tm);
if (difference.compareTo(oneDay) < 1) {
return "today";
} else if (difference.compareTo(twoDay) < 1) {
return "yesterday";
} else if (difference.compareTo(oneWeek) < 1) {
switch (tm.weekday) {
case 1:
return "monday";
case 2:
return "tuesday";
case 3:
return "wednesday";
case 4:
return "thursday";
case 5:
return "friday";
case 6:
return "saturday";
case 7:
return "sunday";
}
} else if (tm.year == today.year) {
return '${tm.day} $month';
} else {
return '${tm.day} $month ${tm.year}';
}
}
I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:
String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";
The first is evaluated at compile-time. The second is evaluated at run-time.
So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.
If the characters are constant, this is fine:
String s = "" + 'a' + 'b' + 'c';
If however they aren't, consider this:
String concat(char... chars) {
if (chars.length == 0) {
return "";
}
StringBuilder s = new StringBuilder(chars.length);
for (char c : chars) {
s.append(c);
}
return s.toString();
}
as an appropriate solution.
However some might be tempted to optimise:
String s = "Name: '" + name + "'"; // String name;
into this:
String s = new StringBuilder().append("Name: ").append(name).append("'").toString();
While this is well-intentioned, the bottom line is DON'T.
Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.
For low-level optimisation the compiler is better at optimising code than you are.
Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.
Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.
Now google chrome has introduce new feature. By Using this feature You can edit you code in chrome browse. (Permanent change on code location)
For that Press F12 --> Source Tab -- (right side) --> File System - in that please select your location of code. and then chrome browser will ask you permission and after that code will be sink with green color. and you can modify your code and it will also reflect on you code location (It means it will Permanent change)
Thanks
Starting with arcseldon's answer, I found that the team name was needed in the URL like so:
npm install --save "git+https://myteamname@[email protected]/myteamname/myprivate.git"
And note that the API key is only available for the team, not individual users.
The solution of Jack Giffin is great but doesn't work for arrays with numbers bigger than 2^32. Below is a refactored, fast version to filter an array based on Jack's solution but it works for 64-bit arrays.
const Math_clz32 = Math.clz32 || ((log, LN2) => x => 31 - log(x >>> 0) / LN2 | 0)(Math.log, Math.LN2);
const filterArrayByAnotherArray = (searchArray, filterArray) => {
searchArray.sort((a,b) => a > b);
filterArray.sort((a,b) => a > b);
let searchArrayLen = searchArray.length, filterArrayLen = filterArray.length;
let progressiveLinearComplexity = ((searchArrayLen<<1) + filterArrayLen)>>>0
let binarySearchComplexity = (searchArrayLen * (32-Math_clz32(filterArrayLen-1)))>>>0;
let i = 0;
if (progressiveLinearComplexity < binarySearchComplexity) {
return searchArray.filter(currentValue => {
while (filterArray[i] < currentValue) i=i+1|0;
return filterArray[i] !== currentValue;
});
}
else return searchArray.filter(e => binarySearch(filterArray, e) === null);
}
const binarySearch = (sortedArray, elToFind) => {
let lowIndex = 0;
let highIndex = sortedArray.length - 1;
while (lowIndex <= highIndex) {
let midIndex = Math.floor((lowIndex + highIndex) / 2);
if (sortedArray[midIndex] == elToFind) return midIndex;
else if (sortedArray[midIndex] < elToFind) lowIndex = midIndex + 1;
else highIndex = midIndex - 1;
} return null;
}
In my experience, I've had to leverage the event's currentTarget:
$("#dingus").click( function (event) {
if ($(event.currentTarget).is(':checked')) {
//checkbox is checked
}
});
The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to pip._internal
precisely in order to make it clear to users that programmatic use of pip is not allowed.
Use sys.executable
to ensure that you will call the same pip
associated with the current runtime.
import subprocess
import sys
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
I had to go look for ojdbc compatible with version on oracle that was installed this fixed my problem, my bad was thinking one ojdbc would work for all
On Windows:
tl;dr: Try opening the file again.
Our system was suffering this problem, and it definitely wasn't a permissions issue, since the program itself would be able to open the database as writable from many threads most of the time, but occasionally (only on Windows, not on OSX), a thread would get these errors even though all the other threads in the program were having no difficulties.
We eventually discovered that the threads that were failing were only those that were trying to open the database immediately after another thread had closed it (within 3 ms). We speculated that the problem was due to the fact that Windows (or the sqlite implementation under windows) doesn't always immediately clean up up file resources upon closing of a file. We got around this by running a test write query against the db upon opening (e.g., creating then dropping a table with a silly name). If the create/drop failed, we waited for 50 ms and tried again, repeating until we succeeded or 5 seconds elapsed.
It worked; apparently there just needed to be enough time for the resources to flush out to disk.
The spec only describes one way of marking comments:
An explicit comment is marked by a “#” indicator.
That's all. There are no block comments.
You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)
Once the user have choose a image you can read the file-path of the chosen image and place it into your html.
Example:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
I'd use SimpleXMLElement.
<?php
$xml = new SimpleXMLElement('<xml/>');
for ($i = 1; $i <= 8; ++$i) {
$track = $xml->addChild('track');
$track->addChild('path', "song$i.mp3");
$track->addChild('title', "Track $i - Track Title");
}
Header('Content-type: text/xml');
print($xml->asXML());
I found a method using fseek and ftell and a thread with this question with answers that it can't be done in just C in another way.
You could use a portability library like NSPR (the library that powers Firefox).
Yes you can create cookies that can only be read on the server-side. These are called "HTTP Only" -cookies, as explained in other answers already
No, there is no way (I know of) to create "cookies" that can be read only on the client-side. Cookies are meant to facilitate client-server communication.
BUT, if you want something LIKE "client-only-cookies" there is a simple answer: Use "Local Storage".
Local Storage is actually syntactically simpler to use than cookies. A good simple summary of cookies vs. local storage can be found at:
A point: You might use cookies created in JavaScript to store GUI-related things you only need on the client-side. BUT the cookie is sent to the server for EVERY request made, it becomes part of the http-request headers thus making the request contain more data and thus slower to send.
If your page has 50 resources like images and css-files and scripts then the cookie is (typically) sent with each request. More on this in Does every web request send the browser cookies?
Local storage does not have those data-transfer related disadvantages, it sends no data. It is great.
i think i am having a bit of confusion here. :) But seems no one else have ..
Are you asking which one to use in this scenario? If Yes then And is the correct answer.
If you are asking about how the operators are working, then
In php both AND, && and OR, || will work in the same way. If you are new in programming and php is one of your first languages them i suggest using AND and OR, because it increases readability and reduces confusion when you check back. But if you are familiar with any other languages already then you might already have familiarized the && and || operators.
I had a similar issue (Asp.Net Core 2.x) that was caused by trying to run a 32-bit asp.net core app in IIS on a 64-bit windows server. The root cause was that the web.config that is auto-generated (if your project does not explicitly include one, which asp.net core projects do not by default) does not contain the full path to the dotnet executable. When you install the hosting bundle on a 64 bit machine it will install the 64 and 32 bit versions of dotnet, but the path will resolve by default to 64 bit and your 32 bit asp.net core app will fail to load. In your browser you may see a 502.5 error and if you look the server event log you might see error code 0x80004005. If you try to run dotnet.exe from a command prompt to load your asp.net core application dll on that server you may see an error like "BadImageFormatException" or "attempt was made to load a program with an incorrect format". The fix that worked for me was to add a web.config to my project (and deployment) and in that web.config set the full path to the 32-bit version of dotnet.exe.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="C:\Program Files (x86)\dotnet\dotnet.exe" arguments=".\My32BitAspNetCoreApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</location>
</configuration>
The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.
You can load it using var fs = require('fs');
fs.readFile('./content.json', (err, data) => {
if (err)
console.log(err);
else {
var json = JSON.parse(data);
//your code using json object
}
})
var json = JSON.parse(fs.readFileSync('./content.json').toString());
Instead of constantly generating project metadata via import->maven command, you can generate your project metadata once and the place it in your git repository along with the rest of your source code. After than, using import->git command will import a proper maven-enabled project, assuming you have maven tools installed.
Make sure to place into the source control system all files in project dir that start with '.' such as .classpath and .project along with the entire contents of the .settings directory.
I am not sure if you can grab that IP from code that runs on the local machine.
You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:
request.getRemoteAddr()
Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.
Use a webservice like AWS and others
import java.net.*;
import java.io.*;
URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
Everybody comments in such a complicated manner.
If you want to remove the last commit from your branch, the simplest way to do it is:
git reset --hard HEAD~1
Now to actually push that change to get rid of your last commit, you have to
git push --force
And that's it. This will remove your last commit.
T findOne(ID id)
(name in the old API) / Optional<T> findById(ID id)
(name in the new API) relies on EntityManager.find()
that performs an entity eager loading.
T getOne(ID id)
relies on EntityManager.getReference()
that performs an entity lazy loading. So to ensure the effective loading of the entity, invoking a method on it is required.
findOne()/findById()
is really more clear and simple to use than getOne()
.
So in the very most of cases, favor findOne()/findById()
over getOne()
.
From at least, the 2.0
version, Spring-Data-Jpa
modified findOne()
.
Previously, it was defined in the CrudRepository
interface as :
T findOne(ID primaryKey);
Now, the single findOne()
method that you will find in CrudRepository
is which one defined in the QueryByExampleExecutor
interface as :
<S extends T> Optional<S> findOne(Example<S> example);
That is implemented finally by SimpleJpaRepository
, the default implementation of the CrudRepository
interface.
This method is a query by example search and you don't want to that as replacement.
In fact, the method with the same behavior is still there in the new API but the method name has changed.
It was renamed from findOne()
to findById()
in the CrudRepository
interface :
Optional<T> findById(ID id);
Now it returns an Optional
. Which is not so bad to prevent NullPointerException
.
So, the actual choice is now between Optional<T> findById(ID id)
and T getOne(ID id)
.
1) The Optional<T> findById(ID id)
javadoc states that it :
Retrieves an entity by its id.
As we look into the implementation, we can see that it relies on EntityManager.find()
to do the retrieval :
public Optional<T> findById(ID id) {
Assert.notNull(id, ID_MUST_NOT_BE_NULL);
Class<T> domainType = getDomainClass();
if (metadata == null) {
return Optional.ofNullable(em.find(domainType, id));
}
LockModeType type = metadata.getLockModeType();
Map<String, Object> hints = getQueryHints().withFetchGraphs(em).asMap();
return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints));
}
And here em.find()
is an EntityManager
method declared as :
public <T> T find(Class<T> entityClass, Object primaryKey,
Map<String, Object> properties);
Its javadoc states :
Find by primary key, using the specified properties
So, retrieving a loaded entity seems expected.
2) While the T getOne(ID id)
javadoc states (emphasis is mine) :
Returns a reference to the entity with the given identifier.
In fact, the reference terminology is really board and JPA API doesn't specify any getOne()
method.
So the best thing to do to understand what the Spring wrapper does is looking into the implementation :
@Override
public T getOne(ID id) {
Assert.notNull(id, ID_MUST_NOT_BE_NULL);
return em.getReference(getDomainClass(), id);
}
Here em.getReference()
is an EntityManager
method declared as :
public <T> T getReference(Class<T> entityClass,
Object primaryKey);
And fortunately, the EntityManager
javadoc defined better its intention (emphasis is mine) :
Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.
So, invoking getOne()
may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.
It means that if we invoke getOne()
and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable.
For example if the proxy object is serialized, you could get a null
reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException
is thrown.
So in this kind of situation, the throw of EntityNotFoundException
that is the main reason to use getOne()
to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.
In any case, to ensure its loading you have to manipulate the entity while the session is opened. You can do it by invoking any method on the entity.
Or a better alternative use findById(ID id)
instead of.
To finish, two questions for Spring-Data-JPA developers:
why not having a clearer documentation for getOne()
? Entity lazy loading is really not a detail.
why do you need to introduce getOne()
to wrap EM.getReference()
?
Why not simply stick to the wrapped method :getReference()
?
This EM method is really very particular while getOne()
conveys a so simple processing.
The :last-child
selector should do it, but it's not supported in any version of IE.
I'm afraid you have no choice but to use a class.
Using TSQL/MSSQL
This query will get you: table name, column name, data type, data type length, and allowable nulls
SELECT TABLE_NAME,COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'your_table_name'
The only thing that needs to be changed is your_table_name.
List<String> mockedList = mock(List.class);
List<String> l = new ArrayList();
l.add("someElement");
mockedList.addAll(l);
ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());
List<String> capturedArgument = argumentCaptor.<List<String>>getValue();
assertThat(capturedArgument, hasItem("someElement"));
Use [^\p{L}\p{Nd}]+
- this matches all (Unicode) characters that are neither letters nor (decimal) digits.
In Java:
String resultString = subjectString.replaceAll("[^\\p{L}\\p{Nd}]+", "");
Edit:
I changed \p{N}
to \p{Nd}
because the former also matches some number symbols like ¼
; the latter doesn't. See it on regex101.com.
On Windows, you can use Run with one of the below commands.
For 32-Bit:
"C:\Program Files (x86)\Git\cmd\start-ssh-agent.cmd"
For-64 Bit:
"C:\Program Files\Git\cmd\start-ssh-agent.cmd"
var a = 15;
var b = -214;
a = b | !(b = a);
This works great.
Similar to @max-malik's answer, but without using jQuery, you can also do this using document.createTreeWalker:
button.addEventListener('click', e => {_x000D_
const treeWalker = document.createTreeWalker(document.body);_x000D_
while (treeWalker.nextNode()) {_x000D_
const node = treeWalker.currentNode;_x000D_
node.textContent = node.textContent.replace(/@/g, '$');_x000D_
}_x000D_
})
_x000D_
<div>This is an @ that we are @ replacing.</div>_x000D_
<div>This is another @ that we are replacing.</div>_x000D_
<div>_x000D_
<span>This is an @ in a span in @ div.</span>_x000D_
</div>_x000D_
<br>_x000D_
<input id="button" type="button" value="Replace @ with $" />
_x000D_
PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.
Example PHP file:
#!/usr/bin/env php
<?php
echo("Hello World!\n")
?>
How to run it:
$ chmod 755 hello.php # do this only once
$ ./hello.php
It took me months of googling to find a solution for this issue. You don't need to install a virtual environment running a 32-bit version of Windows to run a program with a 16-bit installer on 64-bit Windows. If the program itself is 32-bit, and just the installer is 16-bit, here's your answer.
There are ways to modify a 16-bit installation program to make it 32-bit so it will install on 64-bit Windows 7. I found the solution on this site:
http://www.reactos.org/forum/viewtopic.php?f=22&t=10988
In my case, the installation program was InstallShield 5.X. The issue was that the setup.exe program used by InstallShield 5.X is 16-bit. First I extracted the installation program contents (changed the extension from .exe to .zip, opened it and extracted). I then replaced the original 16-bit setup.exe, located in the disk1 folder, with InstallShield's 32-bit version of setup.exe (download this file from the site referenced in the above link). Then I just ran the new 32-bit setup.exe in disk1 to start the installation and my program installed and runs perfectly on 64-bit Windows.
You can also repackage this modified installation, so it can be distributed as an installation program, using a free program like Inno Setup 5.
import sys
import time
a = 0
for x in range (0,3):
a = a + 1
b = ("Loading" + "." * a)
# \r prints a carriage return first, so `b` is printed on top of the previous line.
sys.stdout.write('\r'+b)
time.sleep(0.5)
print (a)
Note that you might have to run sys.stdout.flush()
right after sys.stdout.write('\r'+b)
depending on which console you are doing the printing to have the results printed when requested without any buffering.
Thanks to Aaron for pointing out that it's about locating the views, I misunderstood that.
[UPDATE] I just created a project that sends the user to an Area per default without messing with any of the code or lookup paths:
In global.asax, register as usual:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = ""} // Parameter defaults,
);
}
in Application_Start()
, make sure to use the following order;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
in you area registration, use
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"ShopArea_default",
"{controller}/{action}/{id}",
new { action = "Index", id = "", controller = "MyRoute" },
new { controller = "MyRoute" }
);
}
An example can be found at http://www.emphess.net/2010/01/31/areas-routes-and-defaults-in-mvc-2-rc/
I really hope that this is what you were asking for...
////
I don't think that writing a pseudo ViewEngine
is the best solution in this case. (Lacking reputation, I can't comment). The WebFormsViewEngine
is Area aware and contains AreaViewLocationFormats
which is defined per default as
AreaViewLocationFormats = new[] {
"~/Areas/{2}/Views/{1}/{0}.aspx",
"~/Areas/{2}/Views/{1}/{0}.ascx",
"~/Areas/{2}/Views/Shared/{0}.aspx",
"~/Areas/{2}/Views/Shared/{0}.ascx",
};
I believe you don't adhere to this convention. You posted
public ActionResult ActionY()
{
return View("~/Areas/AreaZ/views/ActionY.aspx");
}
as a working hack, but that should be
return View("~/Areas/AreaZ/views/ControllerX/ActionY.aspx");
IF you don't want to follow the convention, however, you might want to take a short path by either deriving from the WebFormViewEngine
(that is done in MvcContrib, for example) where you can set the lookup paths in the constructor, or -a little hacky- by specifying your convention like this on Application_Start
:
((VirtualPathProviderViewEngine)ViewEngines.Engines[0]).AreaViewLocationFormats = ...;
This should be performed with a little more care, of course, but I think it shows the idea. These fields are public
in VirtualPathProviderViewEngine
in MVC 2 RC.
Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.
OR
y + ̆ = y̆ which actually is
y + ̆ = y̆
Since you can stack them one atop the other you can produce the following:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
which actually is:
y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
The same goes for putting stuff underneath:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
that in fact is:
y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆
In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.
To produce a list of combining diacritical marks you can use the following script (since links keep on dying)
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +" "+"&#"+i+";");}
_x000D_
Also check em out
Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾
Ricardo's answer is correct, however: sometimes you may find yourself in a situation where the container simply doesn't resize as desired as the browser window changes size, thus not allowing highcharts to resize itself.
This always works:
chart.setSize(width, height, doAnimation =
true);
in your actual resize function to set the height and width
dynamicallyreflow: false
in the highcharts-options and of course set height
and width
explicitly on creation. As we'll be doing our own resize event handling there's no need Highcharts hooks in another one.To see in TB:
# parted /dev/sda unit TB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'
To see in GB:
# parted /dev/sda unit GB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'
To see in MB:
# parted /dev/sda unit MB print free | grep 'Free Space' | tail -n1 | awk '{print $3}'
To see in bytes:
# parted /dev/sda unit B print free | grep 'Free Space' | tail -n1 | awk '{print $3}'
To see in %:
# parted /dev/sda unit '%' print free | grep 'Free Space' | tail -n1 | awk '{print $3}'
To see in sectors:
# parted /dev/sda unit s print free | grep 'Free Space' | tail -n1 | awk '{print $3}'
Change /dev/sda
to whatever device you are trying to find the information about. If you are using the result in any calculations, make sure to trim the trailing characters.
public class CustomCollection : List<Object>
{
public Object this[int index]
{
// ...
}
}
its pretty easy if u just want to redirect to a url without any status codes or anything like that u can simple say
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/')
def redirect_to_link():
# return redirect method, NOTE: replace google.com with the link u want
return redirect('https://google.com')
You may be closer than you think — SHOW TABLES already behaves a lot like SELECT:
$pdo = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
foreach ($pdo->query("SHOW TABLES") as $row) {
print "Table $row[Tables_in_$dbname]\n";
}
Maybe.
Temporary tables prefixed with one # (#example) are kept on a per session basis. So if your code calls the stored procedure again while another call is running (for example background threads) then the create call will fail because it's already there.
If you're really worried use a table variable instead
DECLARE @MyTempTable TABLE
(
someField int,
someFieldMore nvarchar(50)
)
This will be specific to the "instance" of that stored procedure call.
I just wrote a simple script to collect the dependencies in ./node_modules. It fulfills my requirement at the moment. This may help some others, I post it here.
var fs = require("fs");
function main() {
fs.readdir("./node_modules", function (err, dirs) {
if (err) {
console.log(err);
return;
}
dirs.forEach(function(dir){
if (dir.indexOf(".") !== 0) {
var packageJsonFile = "./node_modules/" + dir + "/package.json";
if (fs.existsSync(packageJsonFile)) {
fs.readFile(packageJsonFile, function (err, data) {
if (err) {
console.log(err);
}
else {
var json = JSON.parse(data);
console.log('"'+json.name+'": "' + json.version + '",');
}
});
}
}
});
});
}
main();
In my case, the above script outputs:
"colors": "0.6.0-1",
"commander": "1.0.5",
"htmlparser": "1.7.6",
"optimist": "0.3.5",
"progress": "0.1.0",
"request": "2.11.4",
"soupselect": "0.2.0", // Remember: remove the comma character in the last line.
Now, you can copy&paste them. Have fun!
I don't think you need to change the MaxPermSize to 1024m. This works for me:
-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms256m
-Xmx1024m
-XX:PermSize=64m
-XX:MaxPermSize=128m
I like to do something similar to this (though it is still very similar to using a cursor)
[code]
-- Table variable to hold list of things that need looping
DECLARE @holdStuff TABLE (
id INT IDENTITY(1,1) ,
isIterated BIT DEFAULT 0 ,
someInt INT ,
someBool BIT ,
otherStuff VARCHAR(200)
)
-- Populate your @holdStuff with... stuff
INSERT INTO @holdStuff (
someInt ,
someBool ,
otherStuff
)
SELECT
1 , -- someInt - int
1 , -- someBool - bit
'I like turtles' -- otherStuff - varchar(200)
UNION ALL
SELECT
42 , -- someInt - int
0 , -- someBool - bit
'something profound' -- otherStuff - varchar(200)
-- Loop tracking variables
DECLARE @tableCount INT
SET @tableCount = (SELECT COUNT(1) FROM [@holdStuff])
DECLARE @loopCount INT
SET @loopCount = 1
-- While loop variables
DECLARE @id INT
DECLARE @someInt INT
DECLARE @someBool BIT
DECLARE @otherStuff VARCHAR(200)
-- Loop through item in @holdStuff
WHILE (@loopCount <= @tableCount)
BEGIN
-- Increment the loopCount variable
SET @loopCount = @loopCount + 1
-- Grab the top unprocessed record
SELECT TOP 1
@id = id ,
@someInt = someInt ,
@someBool = someBool ,
@otherStuff = otherStuff
FROM @holdStuff
WHERE isIterated = 0
-- Update the grabbed record to be iterated
UPDATE @holdAccounts
SET isIterated = 1
WHERE id = @id
-- Execute your stored procedure
EXEC someRandomSp @someInt, @someBool, @otherStuff
END
[/code]
Note that you don't need the identity or the isIterated column on your temp/variable table, i just prefer to do it this way so i don't have to delete the top record from the collection as i iterate through the loop.
Not sure if this is the best way, but it works.
if (cartDiv == null) {
cartDiv = "<div id='unique_id'></div>"; // document.createElement('div');
document.body.appendChild(cartDiv);
}
As the main question:
Anybody know why this is not allowed?
is still not answered, I did a quick search and found a relatively new addition from a MySQL developer at MySQL Bugs:
[17 Mar 2017 15:11] Ståle Deraas
Posted by developer:
This is indeed a valid feature request, and at first glance it might seem trivial to add. But TEXT/BLOBS values are not stored directly in the record buffer used for reading/updating tables. So it is a bit more complex to assign default values for them.
This is no definite answer, but at least a starting point for the why question.
In the mean time, I'll just code around it and either make the column nullable or explicitly assign a (default ''
) value for each insert
from the application code...
def trim(x):
if x.dtype == object:
x = x.str.split(' ').str[0]
return(x)
df = df.apply(trim)
Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.
Simply create an input element and trigger the click.
var input = document.createElement('input');
input.type = 'file';
input.click();
This is the most basic, pop a select-a-file dialog, but its no use for anything without handling the selected file...
Adding an onchange
event to the newly created input would allow us to do stuff once the user has selected the file.
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
var file = e.target.files[0];
}
input.click();
At the moment we have the file variable storing various information :
file.name // the file's name including extension
file.size // the size in bytes
file.type // file type ex. 'application/pdf'
Great!
In order to get to the actual content of the file, for various reasons. place an image, load into canvas, create a window with Base64 data url, etc. we would need to use the FileReader
API
We would create an instance of the FileReader, and load our user selected file reference to it.
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
// getting a hold of the file reference
var file = e.target.files[0];
// setting up the reader
var reader = new FileReader();
reader.readAsText(file,'UTF-8');
// here we tell the reader what to do when it's done reading...
reader.onload = readerEvent => {
var content = readerEvent.target.result; // this is the content!
console.log( content );
}
}
input.click();
Trying pasting the above code into your devtool's console window, it should produce a select-a-file dialog, after selecting the file, the console should now print the contents of the file.
Let's try to create a file select dialog to change stackoverflows background image to something more spicy...
var input = document.createElement('input');
input.type = 'file';
input.onchange = e => {
// getting a hold of the file reference
var file = e.target.files[0];
// setting up the reader
var reader = new FileReader();
reader.readAsDataURL(file); // this is reading as data url
// here we tell the reader what to do when it's done reading...
reader.onload = readerEvent => {
var content = readerEvent.target.result; // this is the content!
document.querySelector('#content').style.backgroundImage = 'url('+ content +')';
}
}
input.click();
open devtools, and paste the above code into console window, this should pop a select-a-file dialog, upon selecting an image, stackoverflows content box background should change to the image selected.
Cheers!
I've updated polkovnikov.ph solution to React 16 / ES6 with enhancements like touch handling and snapping to a grid which is what I need for a game. Snapping to a grid alleviates the performance issues.
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
class Draggable extends React.Component {
constructor(props) {
super(props);
this.state = {
relX: 0,
relY: 0,
x: props.x,
y: props.y
};
this.gridX = props.gridX || 1;
this.gridY = props.gridY || 1;
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
this.onTouchStart = this.onTouchStart.bind(this);
this.onTouchMove = this.onTouchMove.bind(this);
this.onTouchEnd = this.onTouchEnd.bind(this);
}
static propTypes = {
onMove: PropTypes.func,
onStop: PropTypes.func,
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
gridX: PropTypes.number,
gridY: PropTypes.number
};
onStart(e) {
const ref = ReactDOM.findDOMNode(this.handle);
const body = document.body;
const box = ref.getBoundingClientRect();
this.setState({
relX: e.pageX - (box.left + body.scrollLeft - body.clientLeft),
relY: e.pageY - (box.top + body.scrollTop - body.clientTop)
});
}
onMove(e) {
const x = Math.trunc((e.pageX - this.state.relX) / this.gridX) * this.gridX;
const y = Math.trunc((e.pageY - this.state.relY) / this.gridY) * this.gridY;
if (x !== this.state.x || y !== this.state.y) {
this.setState({
x,
y
});
this.props.onMove && this.props.onMove(this.state.x, this.state.y);
}
}
onMouseDown(e) {
if (e.button !== 0) return;
this.onStart(e);
document.addEventListener('mousemove', this.onMouseMove);
document.addEventListener('mouseup', this.onMouseUp);
e.preventDefault();
}
onMouseUp(e) {
document.removeEventListener('mousemove', this.onMouseMove);
document.removeEventListener('mouseup', this.onMouseUp);
this.props.onStop && this.props.onStop(this.state.x, this.state.y);
e.preventDefault();
}
onMouseMove(e) {
this.onMove(e);
e.preventDefault();
}
onTouchStart(e) {
this.onStart(e.touches[0]);
document.addEventListener('touchmove', this.onTouchMove, {passive: false});
document.addEventListener('touchend', this.onTouchEnd, {passive: false});
e.preventDefault();
}
onTouchMove(e) {
this.onMove(e.touches[0]);
e.preventDefault();
}
onTouchEnd(e) {
document.removeEventListener('touchmove', this.onTouchMove);
document.removeEventListener('touchend', this.onTouchEnd);
this.props.onStop && this.props.onStop(this.state.x, this.state.y);
e.preventDefault();
}
render() {
return <div
onMouseDown={this.onMouseDown}
onTouchStart={this.onTouchStart}
style={{
position: 'absolute',
left: this.state.x,
top: this.state.y,
touchAction: 'none'
}}
ref={(div) => { this.handle = div; }}
>
{this.props.children}
</div>;
}
}
export default Draggable;
mipadi's answer didn't quite work for me, I needed to do this :
git checkout --ours path/to/file.bin
or, to keep the version being merged in:
git checkout --theirs path/to/file.bin
then
git add path/to/file.bin
And then I was able to do "git mergetool" again and continue onto the next conflict.
If you're running tests with dotnet test
, you may find that Console.Error.WriteLine
produces output. This is how I've worked around the issue with NUnit tests, which also seem to have all Debug, Trace and stdout output suppressed.
This check is compatible with both Python 2.x and Python 3.x.
import six
isinstance(obj, six.class_types)
This is basically a wrapper function that performs the same check as in andrea_crotti answer.
Example:
>>> import datetime
>>> isinstance(datetime.date, six.class_types)
>>> True
>>> isinstance(datetime.date.min, six.class_types)
>>> False
Anchors will need to be a different display type than their default to take a height.
display:inline-block;
or display:block;
.
Also check on line-height
which might be interesting with this.
I prefer foxy's answer because we should never use javascript when existing css properties are made for the job.
Don't forget to add display: block ;
in .menuItem
, so height and width are taken into account.
edit : for better script/look&feel decoupling, if you ever need to change style through jQuery I'd define an additional css class and use $(...).addClass("myclass")
and $(...).removeClass("myclass")
instead of this:
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
you could try the following using short circuiting:
style={{
textDecoration: completed && 'line-through'
}}
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
key bit of information from the link:
Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.
The other solutions might be more best practice, but thought it would be worth sharing.
Might be useful to some : check for
pointer-events: none;
In the CSS. It prevents clicks from being caught by JS. I think it's relevant because the CSS might be the last place you'd look into in this kind of situation.
You can convert your .ui files to an executable python file using the below command..
pyuic4 -x form1.ui > form1.py
Now you can straightaway execute the python file as
python3(whatever version) form1.py
You can import this file and you can use it.
You may use friendship when different classes (not inheriting one from the other) are using private or protected members of the other class.
Typical use cases of friend functions are operations that are conducted between two different classes accessing private or protected members of both.
from http://www.cplusplus.com/doc/tutorial/inheritance/ .
You can see this example where non-member method accesses the private members of a class. This method has to be declared in this very class as a friend of the class.
// friend functions
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle (int x, int y) : width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);
};
Rectangle duplicate (const Rectangle& param)
{
Rectangle res;
res.width = param.width*2;
res.height = param.height*2;
return res;
}
int main () {
Rectangle foo;
Rectangle bar (2,3);
foo = duplicate (bar);
cout << foo.area() << '\n';
return 0;
}
List is an interface. You need a specific class in the end so either try
List l = new ArrayList();
or
List l = new LinkedList();
Whichever suit your needs.
o = open('outfile','w')
print('hello world', file=o)
o.close()
I was looking for something like I did in Perl
my $printname = "outfile"
open($ph, '>', $printname)
or die "Could not open file '$printname' $!";
print $ph "hello world\n";
Try this
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
// $(".tab").addClass("active"); // instead of this do the below
$(this).addClass("active");
});
});
when you are using $(".tab").addClass("active");
, it targets all the elements with class name .tab
. Instead when you use this
it looks for the element which has an event, in your case the element which is clicked.
Hope this helps you.
I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o.
You can try to recompile computation.c with the '-m64' flag of gcc(1)
If you want simple SQL for Oracle (e.g. have XE with no XmlGen) go for a simple 2-step:
select ('(SELECT ''' || table_name || ''' as Tablename,COUNT(*) FROM "' || table_name || '") UNION') from USER_TABLES;
Copy the entire result and replace the last UNION with a semi-colon (';'). Then as the 2nd step execute the resulting SQL.
Do you perhaps have one too many here?
describe "when name is too long" do
before { @user.name = "a" * 51 }
it { should_not be_valid }
end
end
Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.
The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:
function foo(doBar)
{
function bar()
{
console.log( 'bar' );
}
function baz()
{
console.log( 'baz' );
}
window.baz = baz;
if ( doBar ) bar();
}
In this example, the baz function will be available for use after the foo
function has been run, as it's overridden window.baz
. The bar function will not be available to any context other than scopes contained within the foo
function.
as a different example:
function Fizz(qux)
{
this.buzz = function(){
console.log( qux );
};
}
The Fizz
function is designed as a constructor so that, when run, it assigns a buzz
function to the newly created object.
Alternatively, if you want to specify expected parameters in action signature, but pass them as arbitrary GET
arguments. Use filters, for example:
Create a route without parameters:
$Route::get('/history', ['uses'=>'ExampleController@history']);
Specify action with two parameters and attach the filter:
class ExampleController extends BaseController
{
public function __construct($browser)
{
$this->beforeFilter('filterDates', array(
'only' => array('history')
));
}
public function history($fromDate, $toDate)
{
/* ... */
}
}
Filter that translates GET
into action's arguments :
Route::filter('filterDates', function($route, Request $request) {
$notSpecified = '_';
$fromDate = $request->get('fromDate', $notSpecified);
$toDate = $request->get('toDate', $notSpecified);
$route->setParameter('fromDate', $fromDate);
$route->setParameter('toDate', $toDate);
});
Expanding on noob's answer:
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(numberOfItemsPerRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow))
return CGSize(width: size, height: size)
}
This allows for any spacing between the cells. It assumes an Int
member variable called numberOfItemsPerRow
and also that all the cells are square and the same size. As noted in jhilgert00's answer we must also react to orientation changes, but now by using viewWillTransitionToSize
as willRotateToInterfaceOrientation
is depreciated.
The original generation scheme for UUIDs was to concatenate the UUID version with the MAC address of the computer that is generating the UUID, and with the number of 100-nanosecond intervals since the adoption of the Gregorian calendar in the West. By representing a single point in space (the computer) and time (the number of intervals), the chance of a collision in values is effectively nil.
Add this to pom.xml
(inside the project
tag)
<build>
<sourceDirectory>src/main/java</sourceDirectory>
</build>
src/main/java
is the source folder you want to set. If you already have this line in your pom.xml
file, check if it's correct.
I had the same error at first and i was really annoyed.
you just need to have ./
before the path to the template
res.render('./index/index');
Hope it works, worked for me.
Some of the above solutions did not work for me. The .fig
attribute was not found when I tried that and I was unable to use .savefig()
directly. However, what did work was:
sns_plot.figure.savefig("output.png")
I am a newer Python user, so I do not know if this is due to an update. I wanted to mention it in case anybody else runs into the same issues as I did.
To find an ancestor of a given type from code, you can use:
[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
while (true)
{
d = VisualTreeHelper.GetParent(d);
if (d == null)
return null;
var t = d as T;
if (t != null)
return t;
}
}
This implementation uses iteration instead of recursion which can be slightly faster.
If you're using C# 7, this can be made slightly shorter:
[CanBeNull]
public static T FindAncestor<T>(DependencyObject d) where T : DependencyObject
{
while (true)
{
d = VisualTreeHelper.GetParent(d);
if (d == null)
return null;
if (d is T t)
return t;
}
}
Alternate approach : without installation of Redistributable package.
Check out in some github for the relevant dll, some people upload the reference dll for their application dependency.
you can download and use them in your project , I have used and run them successfully.
example : https://github.com/Emotiv/community-sdk/find/master
Old question ... nonetheless, just add a checkbox somewhere in the sheet. Checking or unchecking it will refresh the cell formulae.
It is similar to a question called letter combinations of a phone number,
here is my solution.
It works for an arbitrary number of digits, so long as the result doesn't exceed the memory limit.
import java.util.HashMap;
public class Solution {
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> res = new ArrayList<String>();
ArrayList<String> preres = new ArrayList<String>();
res.add("");
for(int i = 0; i < digits.length(); i++) {
String letters = map.get(digits.charAt(i));
if (letters.length() == 0)
continue;
for(String str : res) {
for(int j = 0; j < letters.length(); j++)
preres.add(str + letters.charAt(j));
}
res = preres;
preres = new ArrayList<String>();
}
return res;
}
static final HashMap<Character,String> map = new HashMap<Character,String>(){{
put('1', "");
put('2',"abc");
put('3',"def");
put('4',"ghi");
put('5',"jkl");
put('6',"mno");
put('7',"pqrs");
put('8',"tuv");
put('9',"wxyz");
put('0', "");
}} ;
}
I'm not sure how 12-digit international numbers affect the design.
Edit: International numbers will also be handled
Both types are of course associations, and not really mapped strictly to language elements like that. The difference is in the purpose, context, and how the system is modeled.
As a practical example, compare two different types of systems with similar entities:
A car registration system that primarily keep track of cars, and their owners, etc. Here we are not interested in the engine as a separate entity, but we may still have engine related attributes, like power, and type of fuel. Here the Engine may be a composite part of the car entity.
A car service shop management system that manages car parts, servicing cars, and replace parts, maybe complete engines. Here we may even have engines stocked and need to keep track of them and other parts separately and independent of the cars. Here the Engine may be an aggregated part of the car entity.
How you implement this in your language is of minor concern since at that level things like readability is much more important.
For Font Awesome 5(webfont with css) and Laravel mixin add package for font awesome 5
npm i --save @fortawesome/fontawesome-free
And import font awesome scss in app.scss or your custom scss file
@import '~@fortawesome/fontawesome-free/scss/brands';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
compile your assets npm run dev
or npm run production
and include your compiled css into layout
Set -Dspring.profiles.active=local
under program arguments.
Use the function cast() to convert from timestamp to date
select to_char(cast(sysdate as date),'DD-MM-YYYY') from dual;
For more info of function cast oracle11g http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions016.htm#SQLRF51256
I really hate to put long HTML inside of the attribute, here is my solution, clear and simple (replace ? with whatever you want):
<a class="btn-lg popover-dismiss" data-placement="bottom" data-toggle="popover" title="Help">
<h2>Some title</h2>
Some text
</a>
then
var help = $('.popover-dismiss');
help.attr('data-content', help.html()).text(' ? ').popover({trigger: 'hover', html: true});
One of the way I do it is by creating a 'Global' class with the constant values and do a static import in the classes that need access to the constant.
(1) UPDATE 2019: ES7 Version
class Singleton {
static instance;
constructor() {
if (instance) {
return instance;
}
this.instance = this;
}
foo() {
// ...
}
}
console.log(new Singleton() === new Singleton());
(2) ES6 Version
class Singleton {
constructor() {
const instance = this.constructor.instance;
if (instance) {
return instance;
}
this.constructor.instance = this;
}
foo() {
// ...
}
}
console.log(new Singleton() === new Singleton());
Best solution found: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern
function MySingletonClass () {
if (arguments.callee._singletonInstance) {
return arguments.callee._singletonInstance;
}
arguments.callee._singletonInstance = this;
this.Foo = function () {
// ...
};
}
var a = new MySingletonClass();
var b = MySingletonClass();
console.log( a === b ); // prints: true
For those who want the strict version:
(function (global) {
"use strict";
var MySingletonClass = function () {
if (MySingletonClass.prototype._singletonInstance) {
return MySingletonClass.prototype._singletonInstance;
}
MySingletonClass.prototype._singletonInstance = this;
this.Foo = function() {
// ...
};
};
var a = new MySingletonClass();
var b = MySingletonClass();
global.result = a === b;
} (window));
console.log(result);
yes it is possible using @import and providing the path of css file e.g.
@import url("mycssfile.css");
or
@import "mycssfile.css";
Depending on what you want to accomplish within the loop, iterate over one of these instead:
countries.keySet()
countries.entrySet()
countries.values()
If you don't want to keep track of moving your fonts around:
# Adding Webfonts to the Asset Pipeline
config.assets.precompile << Proc.new { |path|
if path =~ /\.(eot|svg|ttf|woff)\z/
true
end
}
Append Length
A 64-bit representation of b (the length of the message before the padding bits were added) is appended to the result of the previous step. In the unlikely event that b is greater than 2^64, then only the low-order 64 bits of b are used.
See more here.
I didn't mean to answer my own question but I just thought about running a sitemap generator. First one I found http://www.xml-sitemaps.com has a nice text output. Perfect for my needs.
Windows 7 location is: C:\Users\All Users\MySQL\MySQL Server 5.5\my.ini
For XP may be: C:\Documents and Settings\All Users\MySQL\MySQL Server 5.5\my.ini
At the tops of these files are comments defining where my.cnf
can be found.
I strongly disagree with most answers previously mentioned.
Short answer:
Omit the "in" class and add it using jQuery to fade it in.
See this jsfiddle for an example that fades in alert after 3 seconds http://jsfiddle.net/QAz2U/3/
Long answer:
Although it is true bootstrap doesn't natively support fading in alerts, most answers here use the jQuery fade function, which uses JavaScript to animate (fade) the element. The big advantage of this is cross browser compatibility. The downside is performance (see also: jQuery to call CSS3 fade animation?).
Bootstrap uses CSS3 transitions, which have way better performance. Which is important for mobile devices:
Bootstraps CSS to fade the alert:
.fade {
opacity: 0;
-webkit-transition: opacity 0.15s linear;
-moz-transition: opacity 0.15s linear;
-o-transition: opacity 0.15s linear;
transition: opacity 0.15s linear;
}
.fade.in {
opacity: 1;
}
Why do I think this performance is so important? People using old browsers and hardware will potentially get a choppy transitions with jQuery.fade(). The same goes for old hardware with modern browsers. Using CSS3 transitions people using modern browsers will get a smooth animation even with older hardware, and people using older browsers that don't support CSS transitions will just instantly see the element pop in, which I think is a better user experience than choppy animations.
I came here looking for the same answer as the above: to fade in a bootstrap alert. After some digging in the code and CSS of Bootstrap the answer is rather straightforward. Don't add the "in" class to your alert. And add this using jQuery when you want to fade in your alert.
HTML (notice there is NO in class!)
<div id="myAlert" class="alert success fade" data-alert="alert">
<!-- rest of alert code goes here -->
</div>
Javascript:
function showAlert(){
$("#myAlert").addClass("in")
}
Calling the function above function adds the "in" class and fades in the alert using CSS3 transitions :-)
Also see this jsfiddle for an example using a timeout (thanks John Lehmann!): http://jsfiddle.net/QAz2U/3/
You need to call repaint()
and revalidate()
. The former tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by removeAll()
); the latter tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause children of the panel to repaint, but may not cause the panel itself to do so (see this for the list of repaint triggers).
On a more general note: rather than reusing the original panel, I'd recommend building a new panel and swapping them at the parent.
This might not be an ethical and preferred solution but it helps in environments where you can't access the console to kill the job using yarn application command.
Steps are
Go to application master page of spark job. Click on the jobs section. Click on the active job's active stage. You will see "kill" button right next to the active stage.
This works if the succeeding stages are dependent on the currently running stage. Though it marks job as " Killed By User"
Since security.disable option is banned from usage there is still a way to achieve it from pure config without touching any class flies (for me it creates convenience with environments manipulation and possibility to activate it with ENV variable) if you use Boot
spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
$(".jq_fileUploader").change(function () {
var fileSize = this.files[0];
var sizeInMb = fileSize.size/1024;
var sizeLimit= 1024*10;
if (sizeInMb > sizeLimit) {
}
else {
}
});
Coming from emacs I've found that I like ctrl +
keys to do stuff, and in vim I've found that both [ctrl + C]
and [alt + backspace]
will enter Normal mode from insert mode. You might try and see if any of those works out for you.
In my case your docker service might be stopped
Command to start docker service:
$ sudo systemctl start docker
Command to verify if it start:
$ sudo docker run hello-world
Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT
i.e 204 No Content as in place of HttpStatus.OK
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
Any value of T will be ignored for 204, but not for 404
public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$
if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
} else {
LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
}
}
Using Ubuntu 12.04 it appears to work fine for me:
jon@minerva:~$ sudo apt-get install python-psycopg2
[sudo] password for jon:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
python-psycopg2-doc
The following NEW packages will be installed
python-psycopg2
0 upgraded, 1 newly installed, 0 to remove and 334 not upgraded.
Need to get 153 kB of archives.
What error are you getting exactly? - double check you've spelt psycopg right - that's quite often a gotcha... and it never hurts to run an apt-get update
to make sure your repo. is up to date.
adb backup
didn't work for me, so here's what I did (Xiaomi Redmi Note 4X, Android 6.0):
1. Go to Settings > Additional Settings > Backup & reset > Local backups.
2. Tap 'Back up' on the bottom of the screen.
3. Uncheck 'System' and 'Apps' checkmarks.
4. Tap detail disclosure button on the right of the 'Apps' cell to navigate to app selection screen.
5. Select the desired app and tap OK.
6. After the backup was completed, the actual file need to be located somehow. Mine could be found at /MIUI/backup/AllBackup/_FOLDER_NAMED_AFTER_BACKUP_CREATION_DATE_.
7. Then I followed the steps from this answer by RonTLV to actually convert the backup file (.bak in my case) to tar (duplicating from the original answer):
"
a) Go here and download: https://sourceforge.net/projects/adbextractor/
b) Extract the downloaded file and navigate to folder where you extracted.
c) run this with your own file names: java -jar abe.jar unpack c:\Intel\xxx.ab c:\Intel\xxx.tar
"
See here http://www.w3.org/TR/css3-color/#rgba-color
It is not possible, most probably because 0xFFFFFFFF is greater than the maximum value for 32bit integers
I had a similar issue when trying to access a service (old ASMX service). The call would work when accessing via an IP however when calling with an alias I would get the remote name could not be resolved.
Added the following to the config and it resolved the issue:
<system.net>
<defaultProxy enabled="true">
</defaultProxy>
</system.net>
If you want to get the navigationBar
height only, it's simple:
extension UIViewController{
var navigationBarHeight: CGFloat {
return self.navigationController?.navigationBar.frame.height ?? 0.0
}
}
However, if you need the height of top notch of iPhone you don't need to get the navigationBar
height and add to it the statusBar
height, you can simply call safeAreaInsets
that's why exist.
self.view.safeAreaInsets.top
For convenience, one may include tgmath.h
library for the type generate macros. It creates the same function name as the double version for all type of variable. For example, For example, it defines a sqrt()
macro that expands to the sqrtf()
, sqrt()
, or sqrtl()
function, depending on the type of argument provided.
So one don't need to remember the corresponding function name for different type of variables!
#include <stdio.h>
#include <tgmath.h>//for the type generate macros.
#include <complex.h>//for easier declare complex variables and complex unit I
int main(void)
{
double complex z1=1./4.*M_PI+1./4.*M_PI*I;//M_PI is just pi=3.1415...
double complex z2, z3, z4, z5;
z2=exp(z1);
z3=sin(z1);
z4=sqrt(z1);
z5=log(z1);
printf("exp(z1)=%lf + %lf I\n", creal(z2),cimag(z2));
printf("sin(z1)=%lf + %lf I\n", creal(z3),cimag(z3));
printf("sqrt(z1)=%lf + %lf I\n", creal(z4),cimag(z4));
printf("log(z1)=%lf + %lf I\n", creal(z5),cimag(z5));
return 0;
}
Yes. Only comments and the end tag for the html element are allowed after the end tag for the body.
Browsers may perform error recovery, but you should never depend on that.
var host = req.headers['host'];
The headers are stored in a JavaScript object, with the header strings as object keys.
Likewise, the user-agent header could be obtained with
var userAgent = req.headers['user-agent'];
In my view, "Explicit is always better than implicit." Because at some point, you may got confused with this increments statement y+ = x++ + ++y
. A good programmer always makes his or her code more readable.
When I want to see a snapshot of a table(s), and/or view (in a read-only way)
The ~/Library/Developer/Xcode/iOS DeviceSupport
folder is basically only needed to symbolicate crash logs.
You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.
I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.
Don't use a button as a link. Instead, use a link styled as a button.
<Link to="/signup" className="btn btn-primary">Sign up</Link>
Alternatively you could update brew
by installing it again. (Think I did this as El Capitan changed something)
Note: this is a heavy handed approach that will remove all applications installed via brew!
Try to install brew a fresh and it will tell how to uninstall.
At original time of writing to uninstall:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Edit: As of 2020 to uninstall:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
In addition to the posts above:
Application.Current.DispatcherUnhandledException
will not catch exceptions that are thrown from a thread other than the main thread. You have to catch those exceptions on the same thread they are thrown. But if you want to Handle them on your global exception handler you can pass it to the main thread:
System.Threading.Thread t = new System.Threading.Thread(() =>
{
try
{
...
//this exception will not be catched by
//Application.DispatcherUnhandledException
throw new Exception("huh..");
...
}
catch (Exception ex)
{
//But we can handle it in the throwing thread
//and pass it to the main thread wehre Application.
//DispatcherUnhandledException can handle it
System.Windows.Application.Current.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action<Exception>((exc) =>
{
throw new Exception("Exception from another Thread", exc);
}), ex);
}
});
In Rails 4, you can reference an image located in assets/images/
in your .SCSS
files easily like this:
.some-div {
background-image: url(image-path('pretty-background-image.jpg'));
}
When you launch the application in development mode (localhost:3000
), you should see something like:
background-image: url("/assets/pretty-background-image.jpg");
In production mode, your assets will have the cache helper numbers:
background-image: url("/assets/pretty-background-image-8b313354987c309e3cd76eabdb376c1e.jpg");
Addition:
When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()
[1])
In this case, use an additional cast to binary:
SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;
Otherwise, the SELECT
statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
Or use the menu: Tools->Preferences->Database->NLS and change language and territory.
You can use the username variable: %USERNAME%
The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:
<c:if test="true">
<li>user</li>
</c:if>
and then the c:if tag would be executed.
You can do this simply with a function. For example:
def script():
# program code here...
restart = raw_input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
script()
if restart == "n" or restart == "no":
print "Script terminating. Goodbye."
script()
Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname()
. More on this here.
Yes. Right-click on code and you see a menu pop up; there "Source", "Generate Getters and Setters" and next to it you can see the shortcut, which is Alt+Shift+S and R on my system.
Similarly you can navigate to other submenus in that main menu, by typing the appropriate shortcut you go straight the submenu instead of main context menu, and can then either pick from menu or type another letter to pick from the list.
Follow these steps to this problem for all versions of your laravel like laravel 5.5
Step: 1
Rename file .env.example
to .env
Step: 2
Go to your Command prompt/terminal and change path to project directory. Generate key for your application. This is unique for every application so don't make copy paste.
Just run the following command. Key will automatically save to your .env file
php artisan key:generate
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem()
function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type
on the buttons back to submit
and handling the event server-side - this is known as unobtrusive JavaScript.
This occurred for me when persisting an entity in which the existing record in the database had a NULL value for the field annotated with @Version (for optimistic locking). Updating the NULL value to 0 in the database corrected this.
Have you got access to SSH?
You can use this command in shell to backup an entire database:
mysqldump -u [username] -p[password] [databasename] > [filename.sql]
This is actually one command followed by the >
operator, which says, "take the output of the previous command and store it in this file."
Note: The lack of a space between -p and the mysql password is not a typo. However, if you leave the -p
flag present, but the actual password blank then you will be prompted for your password. Sometimes this is recommended to keep passwords out of your bash history.
Implementation of a PDF file in your HTML web-page is very easy.
<embed src="file_name.pdf" width="800px" height="2100px" />
Make sure to change the width and height for your needs. Good luck!
Try WebClient.DownloadFileAsync()
. You can call CancelAsync()
by timer with your own timeout.
After calculation of the boundries you can check the distance between upper left and down right corner; then you can understand the zoom level by testing the distance (if distance is too far zoom level would be low) then you can select wheter using setbound method or setZoom..
I faced the same problem. I checked and tried to set AllowTcpForwarding Yes but it was missing in my sshd_config so no help.I didn't change sshd_config or my.cnf. Make sure the ssh hostname is NOT the same with the mysql hostname(use localhost).
In workbench, choose + to add new connection and set the following:
Test connection. It should be successful then hit OK.Viola!
Bootstrap 4 is coming! The utility classes made familiar in Bootstrap 3.x
are now break-point enabled. The default breakpoints are: xs
, sm
, md
, lg
and xl
, so these text alignment classes look something like .text-[breakpoint]-[alignnment]
.
<div class="text-sm-left"></div> //or
<div class="text-md-center"></div> //or
<div class="text-xl-right"></div>
Important: As of writing this, Bootstrap 4 is only in Alpha 2. These classes and how they're used are subject to change without notice.
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
To summarize and explain visually how it works. Code construction is as follows:
par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)
explanation:
par(mar = c(low, left, top, right)) - margins of the graph area.
title("text" - title text
adj = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
line = positive values move title text up, negative - down)
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
For your first array example use,
a = numpy.arange(5)
To initialize big_array, use
big_array = numpy.zeros((10,4))
This assumes you want to initialize with zeros, which is pretty typical, but there are many other ways to initialize an array in numpy.
Edit:
If you don't know the size of big_array in advance, it's generally best to first build a Python list using append, and when you have everything collected in the list, convert this list to a numpy array using numpy.array(mylist)
. The reason for this is that lists are meant to grow very efficiently and quickly, whereas numpy.concatenate would be very inefficient since numpy arrays don't change size easily. But once everything is collected in a list, and you know the final array size, a numpy array can be efficiently constructed.
This will match all URLs
...including sub-domains and those new top-level domain name extensions such as .museum, .academy, .foundation etc. which can have up to 63 characters (not just .com, .net, .info etc.)
(([\w]+:)?//)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?
Because today maximum length of the available top-level domain name extension is 13 characters such as .international, you can change the number 63 in expression to 13 to prevent someone misusing it.
as javascript
var urlreg=/(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/;_x000D_
_x000D_
$('textarea').on('input',function(){_x000D_
var url = $(this).val();_x000D_
$(this).toggleClass('invalid', urlreg.test(url) == false)_x000D_
});_x000D_
_x000D_
$('textarea').trigger('input');
_x000D_
textarea{color:green;}_x000D_
.invalid{color:red;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>http://www.google.com</textarea>_x000D_
<textarea>http//www.google.com</textarea>_x000D_
<textarea>googlecom</textarea>_x000D_
<textarea>https://www.google.com</textarea>
_x000D_
Wikipedia Article: List of all internet top-level domains
I specifically wanted to use the same function that I was using for arrays for a single object, and wanted to keep it simple. This worked for me:
var mapped = [item].map(myMapFunction).pop();
Well i am trying to open a .vbs within a batch file without having to click open but the answer to this question is ...
SET APPDATA=%CD%
start (your file here without the brackets with a .vbs if it is a vbd file)
There are awk
built-in variables.
NR
- It gives the total number of records processed.
FNR
- It gives the total number of records for each input file.
You can include a legend template in the chart options:
//legendTemplate takes a template as a string, you can populate the template with values from your dataset
var options = {
legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<li>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'
}
//don't forget to pass options in when creating new Chart
var lineChart = new Chart(element).Line(data, options);
//then you just need to generate the legend
var legend = lineChart.generateLegend();
//and append it to your page somewhere
$('#chart').append(legend);
You'll also need to add some basic css to get it looking ok.
$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];
Try this code.
I use this short format for github repositories:
yarn add github_user/repository_name#commit_hash
If I understand your question correctly, it appears you want to know the following:
How do I check if my
String
array containsusercode
, theString
that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
You may access the authenticated user via the Auth facade:
use Illuminate\Support\Facades\Auth;
// Get the currently authenticated user...
$user = Auth::user();
// Get the currently authenticated user's ID...
$id = Auth::id();
There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.
This being said, there are some things that you can indeed do:
You can place images within cells using IMAGE(URL)
, but they cannot be linked to Apps Script functions.
You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))
You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.