See http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.
Custom colors
HSSF:
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");
//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background
HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);
cell.setCellStyle(style);
//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();
//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)
cell.setCellValue("Modified Palette");
//creating a custom palette for the workbook
HSSFPalette palette = wb.getCustomPalette();
//replacing the standard red with freebsd.org red
palette.setColorAtIndex(HSSFColor.RED.index,
(byte) 153, //RGB red (0-255)
(byte) 0, //RGB green
(byte) 0 //RGB blue
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);
//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();
XSSF:
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");
XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
style1.setFillPattern(CellStyle.SOLID_FOREGROUND);
Simply put this block of xml in your activity layout file:
<RelativeLayout
android:id="@+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
</RelativeLayout>
And when you finish loading, call this one line:
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
The result (and it spins too):
In jQuery I mostly use:
$("#element").trigger("change");
Difference between @Component, @Repository, @Controller & @Service annotations
@Component – generic and can be used across application.
@Service – annotate classes at service layer level.
@Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
@Repository – annotate classes at persistence layer, which will act as database repository.
@Controller
= @Component ( Internal Annotation ) + Presentation layer Features
@Service
= @Component ( Internal Annotation ) + Service layer Features
@Component
= Actual Components ( Beans )
@Repository
= @Component ( Internal Annotation ) + Data Layer Features ( use for handling the Domain Beans )
Delete package-lock.json file and then try to install
The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.
I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?
I would be severly annoyed by such a pointless extra return
statement at the end of a void
function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.
You could use the window’s name window.name
to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.
Yes, it is intended. Here you can read detailed explanation. It is possible to override this behavior by setting SO_REUSEADDR option on a socket. For example:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
I was looking at this post to find the answer but... I think everyone on this post was facing the same scenario as me: scrollToPosition()
was fully ignored, for an evident reason.
What I was using?
recyclerView.scrollToPosition(items.size());
... what WORKED?
recyclerView.scrollToPosition(items.size() - 1);
Please check this:
* {margin: 0; padding: 0;}
html, body { width: 100%; height: 100%;}
Or try new method Viewport height :
html, body { width: 100vw; height: 100vh;}
Viewport: If your using viewport means whatever size screen content will come full height fo the screen.
It's quite easy to roll back just a specific migration.
Since the command php artisan migrate:rollback
, undo the last database migration,
and the order of the migrations execution is stored in the batch
field in the migrations
table.
You can edit the batch value of the migration that you want to rollback and set it as the higher. Then you can rollback that migration with a simple:
php artisan migrate:rollback
After editing the same migration you can execute it again with a simple
php artisan migrate
NOTICE: if two or more migrations have the same higher value, they will be all rolled back at the same time.
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
What about scipy.interpolate.splrep (with degree 1 and no smoothing):
>> tck = scipy.interpolate.splrep([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], k=1, s=0)
>> scipy.interpolate.splev(6, tck)
34.0
It seems to do what you want, since 34 = 25 + (25 - 16).
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
find . -type f -empty -exec rm -f {} \;
You can use any of the following options based on the requirements.
Scanner
classimport java.util.Scanner;
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
BufferedReader
and InputStreamReader
classesimport java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);
DataInputStream
classimport java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
The readLine
method from the DataInputStream
class has been deprecated. To get String value, you should use the previous solution with BufferedReader
Console
classimport java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
Apparently, this method does not work well in some IDEs.
I encounter the same problem. I inited a bean object in static block like below:
static {
try{
mqttConfiguration = SpringBootBeanUtils.<MqttConfiguration>getBean(MqttConfiguration.class);
}catch (Throwable e){
System.out.println(e);
}
}
Just because the process the my bean obejct inition caused a NPE, I get trouble into it. So I think you should check you static code block carefully.
I'm not a regex guru by any means. But try:
<[A-Z0-9][A-Z0-9]+>
< start of word
[A-Z0-9] one character
[A-Z0-9]+ and one or more of them
> end of word
I won't try for the bonus points of the whole upper case sentence. hehe
onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"
Change 1000 to the number of milliseconds you want to delay.
If you don't want to SELECT SLEEP(1);
, you can also DO SLEEP(1);
It's useful for those situations in procedures where you don't want to see output.
e.g.
SELECT ...
DO SLEEP(5);
SELECT ...
As mentioned by Klap "android.R.layout.simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS"
All the layouts are located in: sdk\platforms\android-xx\data\res\layout
To view the XML of layout :
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select "Open declaration in layout/simple_list_item_1.xml". It'll direct you to the contents of the XML.
Android Studio: Project Window -> External Libraries -> Android X Platform -> res -> layout, and here you will see a list of available layouts.
This seems like an XML problem. Open the XML document containing your Web-View. Delete the padding code at the top.
Then in the layout , add
android:layout_width="fill_parent"
android:layout_height="fill_parent"
In the Web-View, add
android:layout_width="fill_parent"
android:layout_height="fill_parent"
This makes the Web-View fit the device screen.
Mac OS X uses large amounts of C++ inside some libraries, but it isn't exposed as they're afraid of the ABI breaking.
Based on comment of @alessandro-pezzato.
Run multiples commands by using &
between the commands.
Example:
$ sleep 3 & sleep 5 & sleep 2 &
It's will execute the commands in background.
Queue
is an interface in java, you could not do that.
try:
Queue<Integer> Q = new LinkedList<Integer>();
Pass a ref
if you want to change what the object is:
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);
void DoSomething(ref TestRef t)
{
t = new TestRef();
t.Something = "Not just a changed t, but a completely different TestRef object";
}
After calling DoSomething, t
does not refer to the original new TestRef
, but refers to a completely different object.
This may be useful too if you want to change the value of an immutable object, e.g. a string
. You cannot change the value of a string
once it has been created. But by using a ref
, you could create a function that changes the string for another one that has a different value.
It is not a good idea to use ref
unless it is needed. Using ref
gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.
Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref
keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. int
), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:
int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10
void Change(ref int x)
{
x = 5;
}
void WillNotChange(int x)
{
x = 10;
}
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
this will open the file with the default windows program (notepad if you haven't changed it);
Process.Start(@"c:\myfile.txt")
we just can show same label div on hovering like this
<style>
#b {
display: none;
}
#content:hover~#b{
display: block;
}
</style>
a very common try_files line which can be applied on your condition is
location / {
try_files $uri $uri/ /test/index.html;
}
you probably understand the first part, location /
matches all locations, unless it's matched by a more specific location, like location /test
for example
The second part ( the try_files
) means when you receive a URI that's matched by this block try $uri
first, for example http://example.com/images/image.jpg
nginx will try to check if there's a file inside /images
called image.jpg
if found it will serve it first.
Second condition is $uri/
which means if you didn't find the first condition $uri
try the URI as a directory, for example http://example.com/images/
, ngixn will first check if a file called images
exists then it wont find it, then goes to second check $uri/
and see if there's a directory called images
exists then it will try serving it.
Side note: if you don't have autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.
EDIT: I forgot to mention that if you have
index
defined, nginx will try to check if the index exists inside this folder before trying directory listing.
Third condition /test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html
inside the folder test
and serve it if it exists.
If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
location @error {
}
You can call it with try_files
like this
try_files $uri $uri/ @error;
TIP: If you only have 1 condition you want to serve, like for example inside folder images
you only want to either serve the image or go to 404 error, you can write a line like this
location /images {
try_files $uri =404;
}
which means either serve the file or serve a 404 error, you can't use only $uri
by it self without =404
because you need to have a fallback option.
You can also choose which ever error code you want, like for example:
location /images {
try_files $uri =403;
}
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..
Preferences --> EditorEditor --> Inspections --> Android Lint --> uncheck item Using System app permissio
You can try with the following:
new_string = your_string.split(',').pop().trim();
This is how it works:
split(',')
creates an array made of the different parts of your_string
(e.g. if the string is "'SELECT___100E___7',24"
, the array would be ["'SELECT___100E___7'", "24"]
).
pop()
gets the last element of the array(in the example, it would be "24"
).
This would already be enough, but in case there might be some spaces (not in the case of the OP, but more in general), we could have:
trim()
that would remove the spaces around the string (in case it would be " 24 "
, it would become simply "24"
)It's a simple solution and surely easier than a regexp.
You can do this by using raw string method by simply adding character 'r' without quotes before the string.
# to print '{I am inside braces}'
print(r'{I am inside braces}')
In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to "Console (/SUBSYSTEM:CONSOLE)" under Configuration Properties.
Some comments:
Jet/ACE files are organized in data pages, which means there is a certain amount of slack space when your record boundaries are not aligned with your data pages.
Row-level locking will greatly reduce the number of possible records, since it forces one record per data page.
In Jet 4, the data page size was increased to 4KBs (from 2KBs in Jet 3.x). As Jet 4 was the first Jet version to support Unicode, this meant that you could store 1GB of double-byte data (i.e., 1,000,000,000 double-byte characters), and with Unicode compression turned on, 2GBs of data. So, the number of records is going to be affected by whether or not you have Unicode compression on.
Since we don't know how much room in a Jet/ACE file is taken up by headers and other metadata, nor precisely how much room index storage takes, the theoretical calculation is always going to be under what is practical.
To get the most efficient possible storage, you'd want to use code to create your database rather than the Access UI, because Access creates certain properties that pure Jet does not need. This is not to say there are a lot of these, as properties set to the Access defaults are usually not set at all (the property is created only when you change it from the default value -- this can be seen by cycling through a field's properties collection, i.e., many of the properties listed for a field in the Access table designer are not there in the properties collection because they haven't been set), but you might want to limit yourself to Jet-specific data types (hyperlink fields are Access-only, for instance).
I just wasted an hour mucking around with this using Rnd() to populate 4 fields defined as type byte, with composite PK on the four fields, and it took forever to append enough records to get up to any significant portion of 2GBs. At over 2 million records, the file was under 80MBs. I finally quit after reaching just 700K 7 MILLION records and the file compacted to 184MBs. The amount of time it would take to get up near 2GBs is just more than I'm willing to invest!
You can double click directly on the .cs file representing your form in the Solution Explorer :
This will open Form1.cs [Design]
, which contains the drag&drop controls.
If you are directly in the code behind (The file named Form1.cs
, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.
From the design view, you can switch back to the Code Behind by pressing F7.
if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:
set.seed(10)
x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]
cor(x)
Error in cor(x) : 'x' must be numeric
but
cor(x[sapply(x, is.numeric)])
V1 V2 V3 V4 V5 V6 V7
V1 1.00000000 0.3025766 -0.22473884 -0.72468776 0.18890578 0.14466161 0.05325308
V2 0.30257657 1.0000000 -0.27871430 -0.29075170 0.16095258 0.10538468 -0.15008158
V3 -0.22473884 -0.2787143 1.00000000 -0.22644156 0.07276013 -0.35725182 -0.05859479
V4 -0.72468776 -0.2907517 -0.22644156 1.00000000 -0.19305921 0.16948333 -0.01025698
V5 0.18890578 0.1609526 0.07276013 -0.19305921 1.00000000 0.07339531 -0.31837954
V6 0.14466161 0.1053847 -0.35725182 0.16948333 0.07339531 1.00000000 0.02514081
V7 0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954 0.02514081 1.00000000
V8 0.44705527 0.1698571 0.39970105 -0.42461411 0.63951574 0.23065830 -0.28967977
V9 0.21006372 -0.4418132 -0.18623823 -0.25272860 0.15921890 0.36182579 -0.18437981
V10 0.02326108 0.4618036 -0.25205899 -0.05117037 0.02408278 0.47630138 -0.38592733
V8 V9 V10
V1 0.447055266 0.210063724 0.02326108
V2 0.169857120 -0.441813231 0.46180357
V3 0.399701054 -0.186238233 -0.25205899
V4 -0.424614107 -0.252728595 -0.05117037
V5 0.639515737 0.159218895 0.02408278
V6 0.230658298 0.361825786 0.47630138
V7 -0.289679766 -0.184379813 -0.38592733
V8 1.000000000 0.001023392 0.11436143
V9 0.001023392 1.000000000 0.15301699
V10 0.114361431 0.153016985 1.00000000
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.
https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable
A lambda
is an anonymous function:
>>> f = lambda: 'foo'
>>> print f()
foo
It is often used in functions such as sorted()
that take a callable as a parameter (often the key
keyword parameter). You could provide an existing function instead of a lambda
there too, as long as it is a callable object.
Take the sorted()
function as an example. It'll return the given iterable in sorted order:
>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']
but that sorts uppercased words before words that are lowercased. Using the key
keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:
>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']
We had to create a separate function for that, we could not inline the def lowercased()
line into the sorted()
expression:
>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
File "<stdin>", line 1
sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
^
SyntaxError: invalid syntax
A lambda
on the other hand, can be specified directly, inline in the sorted()
expression:
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']
Lambdas are limited to one expression only, the result of which is the return value.
There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.
Use local-web-server npm package.
https://www.npmjs.com/package/local-web-server
$ npm install -g local-web-server
$ cd <your-app-folder>
$ ws
Also, you can run
$ ws -p 8181
-p defines the port you want to use
After that, just go to your browser and access http:localhost:8181/
Try:
List<String> textFiles(String directory) {
List<String> textFiles = new ArrayList<String>();
File dir = new File(directory);
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.add(file.getName());
}
}
return textFiles;
}
You want to do a case insensitive search in which case:
if (file.getName().toLowerCase().endsWith((".txt"))) {
If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.
You can use a simple approach...
$('YourDataTableID').dataTable()._fnAjaxUpdate();
It will refresh the data by making an ajax request with the same parameters. Very simple.
Here is a monkeyrunner script that sends touch and drags to an application. I have been using this to test that my application can handle rapid repetitive swipe gestures.
# This is a monkeyrunner jython script that opens a connection to an Android
# device and continually sends a stream of swipe and touch gestures.
#
# See http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html
#
# usage: monkeyrunner swipe_monkey.py
#
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
# Connects to the current device
device = MonkeyRunner.waitForConnection()
# A swipe left from (x1, y) to (x2, y) in 2 steps
y = 400
x1 = 100
x2 = 300
start = (x1, y)
end = (x2, y)
duration = 0.2
steps = 2
pause = 0.2
for i in range(1, 250):
# Every so often inject a touch to spice things up!
if i % 9 == 0:
device.touch(x2, y, 'DOWN_AND_UP')
MonkeyRunner.sleep(pause)
# Swipe right
device.drag(start, end, duration, steps)
MonkeyRunner.sleep(pause)
# Swipe left
device.drag(end, start, duration, steps)
MonkeyRunner.sleep(pause)
The following helps in any case (no matter if you're using IIS, Cassini or whatever):
Why does this work? When web.config is changed, the web server (IIS, Cassini, etc.) does a recycle, but in this case (for whatever reason), the process keeps the same, so you keep attached to it with the debugger (Visual Studio).
It actually works now from bower.
bower install material-design-icons --save
It downloads 37.1 KBs. Then it extracts and installs. You will see a folder called material-design-icons in bower_components folder. The total size is around 299KBs
Activity.java:
public RecyclerView.LayoutManager mLayoutManager;
Parcelable state;
mLayoutManager = new LinearLayoutManager(this);
// Inside `onCreate()` lifecycle method, put the below code :
if(state != null) {
mLayoutManager.onRestoreInstanceState(state);
}
@Override
protected void onResume() {
super.onResume();
if (state != null) {
mLayoutManager.onRestoreInstanceState(state);
}
}
@Override
protected void onPause() {
super.onPause();
state = mLayoutManager.onSaveInstanceState();
}
Why I'm using OnSaveInstanceState()
in onPause()
means, While switch to another activity onPause would be called.It will save that scroll position and restore the position when we coming back from another activity.
# Preface: File is json with contents: {'name': 'Android', 'status': 'ERROR'}
import boto3
import io
s3 = boto3.resource('s3')
obj = s3.Object('my-bucket', 'key-to-file.json')
data = io.BytesIO()
obj.download_fileobj(data)
# object is now a bytes string, Converting it to a dict:
new_dict = json.loads(data.getvalue().decode("utf-8"))
print(new_dict['status'])
# Should print "Error"
You can try this:
for file in *.jpg;
do
mv $file $somestring_${file:((-7))}
done
You can see "parameter expansion" in man bash
to understand the above better.
a MySQL-only solution would be something like this:
SELECT IF (UNIX_TIMESTAMP(`field`) > UNIX_TIMESTAMP(), `field`,'GO AHEAD') as `yourdate`
FROM `table`
So I take it if the user enters 2
, you want the output to be something like:
!!
!!
!!
!!
Correct?
To get that, you would need something like:
rows = 4
times_to_repeat = int(raw_input("How many times to repeat per row? ")
for i in range(rows):
print "!" * times_to_repeat
That would result in:
How many times to repeat per row?
>> 4
!!!!
!!!!
!!!!
!!!!
I have not tested this, but it should run error free.
5.0//2
results in 2.0
, and not 2
because the return type of the return value from //
operator follows python coercion (type casting) rules.
Python promotes conversion of lower datatype (integer) to higher data type (float) to avoid data loss.
Why not give something like this a try: tar cvf scala.tar `find src -name *.scala`
This was done using Toad for Oracle 12.8.0.49
ALTER TABLE SCHEMA.TABLENAME
MODIFY (COLUMNNAME NEWDATATYPE(LENGTH)) ;
For example,
ALTER TABLE PAYROLL.EMPLOYEES
MODIFY (JOBTITLE VARCHAR2(12)) ;
JavaFX is part of OpenJDK
The JavaFX project itself is open source and is part of the OpenJDK project.
Update Dec 2019
For current information on how to use Open Source JavaFX, visit https://openjfx.io. This includes instructions on using JavaFX as a modular library accessed from an existing JDK (such as an Open JDK installation).
The open source code repository for JavaFX is at https://github.com/openjdk/jfx.
At the source location linked, you can find license files for open JavaFX (currently this license matches the license for OpenJDK: GPL+classpath exception).
The wiki for the project is located at: https://wiki.openjdk.java.net/display/OpenJFX/Main
If you want a quick start to using open JavaFX, the Belsoft Liberica JDK distributions provide pre-built binaries of OpenJDK that (currently) include open JavaFX for a variety of platforms.
For distribution as self-contained applications, Java 14, is scheduled to implement JEP 343: Packaging Tool, which "Supports native packaging formats to give end users a natural installation experience. These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.", for deployment of OpenJFX based applications with native installers and no additional platform dependencies (such as a pre-installed JDK).
Older information which may become outdated over time
Building JavaFX from the OpenJDK repository
You can build an open version of OpenJDK (including JavaFX) completely from source which has no dependencies on the Oracle JDK or closed source code.
Update: Using a JavaFX distribution pre-built from OpenJDK sources
As noted in comments to this question and in another answer, the Debian Linux distributions offer a JavaFX binary distibution based upon OpenJDK:
Install via:
sudo apt-get install openjfx
(currently this only works for Java 8 as far as I know).
Differences between Open JDK and Oracle JDK with respect to JavaFX
The following information was provided for Java 8. As of Java 9, VP6 encoding is deprecated for JavaFX and the Oracle WebStart/Browser embedded application deployment technology is also deprecated. So future versions of JavaFX, even if they are distributed by Oracle, will likely not include any technology which is not open source.
Oracle JDK includes some software which is not usable from the OpenJDK. There are two main components which relate to JavaFX.
This means that an open version of JavaFX cannot play VP6 FLV files. This is not a big loss as it is difficult to find VP6 encoders or media encoded in VP6.
Other more common video formats, such as H.264 will playback fine with an open version of JavaFX (as long as you have the appropriate codecs pre-installed on the target machine).
The lack of WebStart/Browser Embedded deployment technology is really something to do with OpenJDK itself rather than JavaFX specifically. This technology can be used to deploy non-JavaFX applications.
It would be great if the OpenSource community developed a deployment technology for Java (and other software) which completely replaced WebStart and Browser Embedded deployment methods, allowing a nice light-weight, low impact user experience for application distribution. I believe there have been some projects started to serve such a goal, but they have not yet reached a high maturity and adoption level.
Personally, I feel that WebStart/Browser Embedded deployments are legacy technology and there are currently better ways to deploy many JavaFX applications (such as self-contained applications).
Update Dec, 2019:
An open source version of WebStart for JDK 11+ has been developed and is available at https://openwebstart.com.
Who needs to create Linux OpenJDK Distributions which include JavaFX
It is up to the people which create packages for Linux distributions based upon OpenJDK (e.g. Redhat, Ubuntu etc) to create RPMs for the JDK and JRE that include JavaFX. Those software distributors, then need to place the generated packages in their standard distribution code repositories (e.g. fedora/red hat network yum repositories). Currently this is not being done, but I would be quite surprised if Java 8 Linux packages did not include JavaFX when Java 8 is released in March 2014.
Update, Dec 2019:
Now that JavaFX has been separated from most binary JDK and JRE distributions (including Oracle's distribution) and is, instead, available as either a stand-alone SDK, set of jmods or as a library dependencies available from the central Maven repository (as outlined as https://openjfx.io), there is less of a need for standard Linux OpenJDK distributions to include JavaFX.
If you want a pre-built JDK which includes JavaFX, consider the Liberica JDK distributions, which are provided for a variety of platforms.
Advice on Deployment for Substantial Applications
I advise using Java's self-contained application deployment mode.
A description of this deployment mode is:
Application is installed on the local drive and runs as a standalone program using a private copy of Java and JavaFX runtimes. The application can be launched in the same way as other native applications for that operating system, for example using a desktop shortcut or menu entry.
You can build a self-contained application either from the Oracle JDK distribution or from an OpenJDK build which includes JavaFX. It currently easier to do so with an Oracle JDK.
As a version of Java is bundled with your application, you don't have to care about what version of Java may have been pre-installed on the machine, what capabilities it has and whether or not it is compatible with your program. Instead, you can test your application against an exact Java runtime version, and distribute that with your application. The user experience for deploying your application will be the same as installing a native application on their machine (e.g. a windows .exe or .msi installed, an OS X .dmg, a linux .rpm or .deb).
Note: The self-contained application feature was only available for Java 8 and 9, and not for Java 10-13. Java 14, via JEP 343: Packaging Tool, is scheduled to again provide support for this feature from OpenJDK distributions.
Update, April 2018: Information on Oracle's current policy towards future developments
In ggplot2 you can do smooths in a number of ways, for example:
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
geom_smooth(method = "gam", formula = y ~ poly(x, 2))
ggplot(mtcars, aes(wt, mpg)) + geom_point() +
geom_smooth(method = "loess", span = 0.3, se = FALSE)
!=
For example,
if ("apple" != "orange")
// true, the string "apple" is not equal to the string "orange"
Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1')
[not equal])
Make sure that You have created a correct package.You might get a chance to create folder instead of package
For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.
You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:
sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
abstract erubis activesupport mime-types mail text-hyphen text-format \
thor i18n rake bundler arel railties rails --prerelease --force
I was running into a similar issue where the whole ../lib/utils
directory couldn't be found when I tried executing Mocha via npm test
. I tried the mentioned solutions here with no luck. Ultimately I ended up uninstalling and reinstalling the Mocha package that was a dependency in the npm project I was working in and it worked after that. So if anyone's having this issue with an npm package installed as a dependency, try uninstalling and reinstalling the package if you haven't already!
As all have mentioned it is
request.getHeader("referer");
I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.
More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.
The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.
You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.
This method orderBy
does not change the input array,
you have to assign the result to your array :
var chars = this.state.characters;
chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'
this.setState({characters: chars})
List all containers
docker container ls
List all images
docker image ls
Stop container by container id
docker container stop <container_id>
Remove container by container id
docker container rm <container_id>
If don't want stop and remove, can force remove
docker container rm -f <container_id>
Remove image
docker image rm <image_id>
Done!
Since awk and perl are closely related...
Perl equivalents of @Dennis's awk solutions:
To print the second line:
perl -ne 'print if $. == 2' file
To print the second field:
perl -lane 'print $F[1]' file
To print the third field of the fifth line:
perl -lane 'print $F[2] if $. == 5' file
Perl equivalent of @Glenn's solution:
Print the j'th field of the i'th line
perl -lanse 'print $F[$j-1] if $. == $i' -- -i=5 -j=3 file
Perl equivalents of @Hai's solutions:
if you are looking for second columns that contains abc:
perl -lane 'print if $F[1] =~ /abc/' foo
... and if you want to print only a particular column:
perl -lane 'print $F[2] if $F[1] =~ /abc/' foo
... and for a particular line number:
perl -lane 'print $F[2] if $F[1] =~ /abc/ && $. == 5' foo
-l
removes newlines, and adds them back in when printing
-a
autosplits the input line into array @F
, using whitespace as the delimiter
-n
loop over each line of the input file
-e
execute the code within quotes
$F[1]
is the second element of the array, since Perl starts at 0
$.
is the line number
It would appear that as of now (April of 2017) that the following works:
public string LoggedInUser => User.Identity.Name;
At least while within a Controller
private Map<String, Integer> _map= new HashMap<String, Integer>();
Iterator<Map.Entry<String,Integer>> itr= _map.entrySet().iterator();
//please check
while(itr.hasNext())
{
System.out.println("key of : "+itr.next().getKey()+" value of Map"+itr.next().getValue());
}
You have to dispatch after the async request ends.
This would work:
export function bindComments(postId) {
return function(dispatch) {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
}
Here are some example to iterate over integer range and string:
#(initial,final but not included,gap)
for i in range(1,10,2):
print(i);
1,3,5,7,9
# (initial, final but not included)
# note: 4 not included
for i in range (1,4):
print(i);
1,2,3
#note: 5 not included
for i in range (5):
print (i);
0,1,2,3,4
# you can also iterate over strings
myList = ["ml","ai","dl"];
for i in myList:
print(i);
output: ml,ai,dl
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True
as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote()
to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).
shell=False
is always the default where you pass an argument array.
Now the safe solutions...
Change your own process's environment - the new environment will apply to python itself and all subprocesses.
os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)
Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.
myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)
Unix only: Execute env
to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.
command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)
Of course if var1
contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True
you must compose a command array that contain the splitted string:
command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']
If you want to keep your links to look like they are :active
class, you should define :visited
class same as :active
so if you have a links in .example
then you do something like this:
a.example:active, a.example:visited {
/* Put your active state style code here */ }
The Link visited Pseudo Class is used to select visited links as says the name.
If you want the view to be read only after granting the read permission you can use the ALGORITHM = TEMPTABLE in you view DDL definition.
I've been searching high and low for an end-to-end example of a complete maven-based ear-packaged application and finally stumbled upon this. The instructions say to select option 2 when running through the CLI but for your purposes, use option 1.
Also with option -T
from manual
Disable pseudo-tty allocation
I met the same issue while experimenting with my own Python library and what I've found out is that pip freeze
will show you the library as installed if your current directory contains lib.egg-info
folder. And pip uninstall <lib>
will give you the same error message.
egg-info
folderspip show <lib-name>
to see the details about the location of the library, so you can remove files manually.I have written a .bat file to copy and paste file to a temporary folder and make it zip and transfer into a smb mount point, Hope this would help,
@echo off
if not exist "C:\Temp Backup\" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP"
if not exist "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs" mkdir "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
xcopy /s/e/q "C:\Source" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
"C:\Program Files (x86)\WinRAR\WinRAR.exe" a "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\TELIUM"
"C:\Program Files (x86)\WinRAR\WinRAR.exe" a "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP\ZIP_Backup_Log_%date:~-4,4%_%date:~-10,2%_%date:~-7,2%.rar" "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\Logs"
NET USE \\IP\IPC$ /u:IP\username password
ROBOCOPY "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%\ZIP" "\\IP\Backup Folder" /z /MIR /unilog+:"C:\backup_log_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log"
NET USE \\172.20.10.103\IPC$ /D
RMDIR /S /Q "C:\Temp Backup_%date:~-4,4%%date:~-10,2%%date:~-7,2%"
This post may be a bit old, but I also had the same problem recently. The first solution proposed by John Stauffer is a good one, but I had some problems as I am working this spring. The spring's dependency-jars I use have some property files and xml-schemas declaration which share the same paths and names. Although these jars come from the same versions, the jar-with-dependencies maven-goal was overwriting theses file with the last file found.
In the end, the application was not able to start as the spring jars could not find the correct properties files. In this case the solution propose by Rop have solved my problem.
Also since then, the spring-boot project now exist. It has a very cool way to manage this problem by providing a maven goal which overload the package goal and provide its own class loader. See spring-boots Reference Guide
Create an xml file in res/values and copy the below code
<style name="BlackText">
<item name="android:textColor">#000000</item>
</style>
and the specify the style in activity in Manifest like below
android:theme="@style/BlackText"
// .blur is triggered when element loses focus
$('#target').blur(function() {
alert($(this).val());
});
// To trigger manually use:
$('#target').blur();
A sample way to get the date and time in this format "2018 Nov 01 16:18:22" use this
DateFormat dateFormat = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Date date = new Date();
dateFormat.format(date);
I spent the better part of a day fiddling with this problem. Turned out the RowBackground Property on the DataGrid - which I had set - was overriding all attempts to change it in . As soon as I deleted it, everything worked. (Same goes for Foreground set in DataGridTextColumn, by the way).
I got the same error and looked into activity. Where I found that I had two package lock files which was causing the error.
If using IIS 7 or IIS 7.5 you can use
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="CreateThing.aspx" />
</files>
</defaultDocument>
</system.webServer>
https://docs.microsoft.com/en-us/iis/configuration/system.webServer/defaultDocument/
Updated package.json:
"build": {
"appId": "com.my-website.my-app",
"productName": "MyApp",
"copyright": "Copyright © 2019 ${author}",
"mac": {
"icon": "./public/icons/mac/icon.icns", <---------- set Mac Icons
"category": "public.app-category.utilities"
},
"win": {
"icon": "./public/icons/png/256x256.png" <---------- set Win Icon
},
"files": [
"./build/**/*",
"./dist/**/*",
"./node_modules/**/*",
"./public/**/*", <---------- need for get access to icons
"*.js"
],
"directories": {
"buildResources": "public" <---------- folder where placed icons
}
},
After build application you can see icons. This solution don't show icons in developer mode.
I don't setup icons in new BrowserWindow()
.
This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.
More about csrf tokens here:
What is a CSRF token ? What is its importance and how does it work?
Checking it out in python3:
python -V
Python 3.6.5
Example1:
.
+-- parent.py
+-- start.py
+-- sub
+-- relative.py
- start.py
import sub.relative
- parent.py
print('Hello from parent.py')
- sub/relative.py
from .. import parent
If we run it like this(just to make sure PYTHONPATH is empty):
PYTHONPATH='' python3 start.py
Output:
Traceback (most recent call last):
File "start.py", line 1, in <module>
import sub.relative
File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
from .. import parent
ValueError: attempted relative import beyond top-level package
If we change import in sub/relative.py
- sub/relative.py
import parent
If we run it like this:
PYTHONPATH='' python3 start.py
Output:
Hello from parent.py
Example2:
.
+-- parent.py
+-- sub
+-- relative.py
+-- start.py
- parent.py
print('Hello from parent.py')
- sub/relative.py
print('Hello from relative.py')
- sub/start.py
import relative
from .. import parent
Run it like:
PYTHONPATH='' python3 sub/start.py
Output:
Hello from relative.py
Traceback (most recent call last):
File "sub/start.py", line 2, in <module>
from .. import parent
ValueError: attempted relative import beyond top-level package
If we change import in sub/start.py
:
- sub/start.py
import relative
import parent
Run it like:
PYTHONPATH='' python3 sub/start.py
Output:
Hello from relative.py
Traceback (most recent call last):
File "sub/start.py", line 3, in <module>
import parent
ModuleNotFoundError: No module named 'parent'
Run it like:
PYTHONPATH='.' python3 sub/start.py
Output:
Hello from relative.py
Hello from parent.py
Also it's better to use import from root folder, i.e.:
- sub/start.py
import sub.relative
import parent
Run it like:
PYTHONPATH='.' python3 sub/start.py
Output:
Hello from relative.py
Hello from parent.py
Here is my version:
def contains(small, big):
for i in xrange(len(big)-len(small)+1):
for j in xrange(len(small)):
if big[i+j] != small[j]:
break
else:
return i, i+len(small)
return False
It returns a tuple of (start, end+1) since I think that is more pythonic, as Andrew Jaffe points out in his comment. It does not slice any sublists so should be reasonably efficient.
One point of interest for newbies is that it uses the else clause on the for statement - this is not something I use very often but can be invaluable in situations like this.
This is identical to finding substrings in a string, so for large lists it may be more efficient to implement something like the Boyer-Moore algorithm.
<?php $sql = "SELECT * FROM guest_book";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$query = mysql_query("SELECT * FROM guest_book ORDER BY id");
$i=1;
while($row = mysql_fetch_assoc($query)){
?>
<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>" />
<?php $i++; }} ?>
<input type="submit" value="Delete" name="Delete" />
if($_REQUEST['Delete'] != '')
{
if(!empty($_REQUEST['checkboxstatus'])) {
$checked_values = $_REQUEST['checkboxstatus'];
foreach($checked_values as $val) {
$sqldel = "DELETE from guest_book WHERE id = '$val'";
mysql_query($sqldel);
}
}
}
Here is the best solution if you want some extra flexibility and don't want to change your model field. Just add this custom validator:
#Imports
from django.core.exceptions import ValidationError
class validate_range_or_null(object):
compare = lambda self, a, b, c: a > c or a < b
clean = lambda self, x: x
message = ('Ensure this value is between %(limit_min)s and %(limit_max)s (it is %(show_value)s).')
code = 'limit_value'
def __init__(self, limit_min, limit_max):
self.limit_min = limit_min
self.limit_max = limit_max
def __call__(self, value):
cleaned = self.clean(value)
params = {'limit_min': self.limit_min, 'limit_max': self.limit_max, 'show_value': cleaned}
if value: # make it optional, remove it to make required, or make required on the model
if self.compare(cleaned, self.limit_min, self.limit_max):
raise ValidationError(self.message, code=self.code, params=params)
And it can be used as such:
class YourModel(models.Model):
....
no_dependents = models.PositiveSmallIntegerField("How many dependants?", blank=True, null=True, default=0, validators=[validate_range_or_null(1,100)])
The two parameters are max and min, and it allows nulls. You can customize the validator if you like by getting rid of the marked if statement or change your field to be blank=False, null=False in the model. That will of course require a migration.
Note: I had to add the validator because Django does not validate the range on PositiveSmallIntegerField, instead it creates a smallint (in postgres) for this field and you get a DB error if the numeric specified is out of range.
Hope this helps :) More on Validators in Django.
PS. I based my answer on BaseValidator in django.core.validators, but everything is different except for the code.
I’ve created a new SOAP client for the Android platform, it is use a JAX-WS generated interfaces, but it is only a proof-of-concept yet.
If you are interested, please try the example and/or watch the source: http://wiki.javaforum.hu/display/ANDROIDSOAP/Home
Update: the version 0.0.4 is out with tutorial:
http://wiki.javaforum.hu/display/ANDROIDSOAP/2012/04/16/Version+0.0.4+released
http://wiki.javaforum.hu/display/ANDROIDSOAP/Step+by+step+tutorial
They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.
Source: official documentation.
This code also works.
$(".circle").hover(function() {$(this).hide(200).show(200);});
_x000D_
.circle{_x000D_
width:100px;_x000D_
height:100px;_x000D_
border-radius:50px;_x000D_
font-size:20px;_x000D_
color:black;_x000D_
line-height:100px;_x000D_
text-align:center;_x000D_
background:yellow_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>_x000D_
<div class="circle">hover me</div>
_x000D_
def fun(N):#prime test
if N>1 :
for _ in xrange(5):
Num=randint(1,N-1)
if pow(Num,N-1,N)!=1:
return False
return True
return False
True if the number is prime otherwise false
Make subl
available.
Put this in ~/.bash_profile
[[ -s ~/.bashrc ]] && source ~/.bashrc
Put this in ~/.bashrc
export EDITOR=subl
First a bit of info in epoch from man gmtime
The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When inter-
preted as an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
Time (UTC).
to understand how epoch should be.
>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)
just ensure the arg you are passing to time.gmtime()
is integer.
Either make an account on the Nuget.org website, then log in, browse to the package you want and click on the Download link on the left menu.
Or guess the URL. They have the following format:
https://www.nuget.org/api/v2/package/{packageID}/{packageVersion}
Then simply unzip the .nupkg file and extract the contents you need.
Need to merge the properties in object. For Example,
const boxStyle = {
width : "50px",
height : "50px"
};
const redBackground = {
...boxStyle,
background: "red",
};
const blueBackground = {
...boxStyle,
background: "blue",
}
<div style={redBackground}></div>
<div style={blueBackground}></div>
Simple one, just do like this..
ListViewItem lvi = new ListViewItem(pet.Name);
lvi.SubItems.Add(pet.Type);
lvi.SubItems.Add(pet.Age);
listView.Items.Add(lvi);
Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).
Without using a visual selection, gU<motion>
will make the characters in motion
uppercase, or use gu<motion>
for lowercase.
For more of these, see Section 3 in Vim's change.txt help file.
public static void Main(string[] args)
{
int[] numbers = new int[10];
Console.Write("index ");
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = i;
Console.Write(numbers[i] + " ");
}
Console.WriteLine("");
Console.WriteLine("");
Console.Write("value ");
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = numbers.Length - i;
Console.Write(numbers[i] + " ");
}
Console.ReadKey();
}
I had the same issue after installing the 64 bit Oracle client on Windows 7 64 bit. The solution that worked for me:
cd \oracle\product\11.2.0\client_64\BIN
c:\Windows\system32\regsvr32.exe OraOLEDB11.dll
Navigation properties are typically defined as virtual so that they can take advantage of certain Entity Framework functionality such as lazy loading.
If a navigation property can hold multiple entities (as in many-to-many or one-to-many relationships), its type must be a list in which entries can be added, deleted, and updated, such as ICollection.
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
The whole formula can be contained in a single expression:
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
print n, " is a leap year" if is_leap_year(n) else " is not a leap year"
Simple as Pie. Just make sure you fetch array size before actually performing the loop.
for(int i = 0, arraySize= mySparseArray.size(); i < arraySize; i++) {
Object obj = mySparseArray.get(/* int key = */ mySparseArray.keyAt(i));
}
Hope this helps.
I got this error on a report I copied from another project and changed the data source. I solved it by opening the properties of my dataset, going to the Parameters section, and literally just reselecting all the parameters in the right column, like I just clicked the dropdown and selected the same column. Then I hit preview, and it worked!
This will get you the generic link:
selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do')")).Click();
If you want to have it specify a parameter then you will have to test for each one:
...
int i = 1;
selenium.FindElement(By.XPath("xpath=//a[contains(@href,'listDetails.do?camp=" + i.ToString() + "')")).Click();
...
The above could utilize a for loop which navigates to and from each camp numbers' page, which could verify a static list of camps.
Please excuse if the code is not perfect, I have not tested myself.
Often this question is asked in the context of Ron de Bruin's RangeToHTML
function, which creates an HTML PublishObject
from an Excel.Range
, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody
. In doing so, this removes the default signature (the RangeToHTML
function has a helper function GetBoiler
which attempts to insert the default signature).
Unfortunately, the poorly-documented Application.CommandBars
method is not available via Outlook:
wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
It will raise a runtime 6158:
But we can still leverage the Word.Document
which is accessible via the MailItem.GetInspector
method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).
Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed
With OutMail
.To = "[email protected]"
.BCC = ""
.Subject = "Subject"
.Display
Dim wdDoc As Object '## Word.Document
Dim wdRange As Object '## Word.Range
Set wdDoc = OutMail.GetInspector.WordEditor
Set wdRange = wdDoc.Range(0, 0)
wdRange.InsertAfter vbCrLf & vbCrLf
'Copy the range in-place
rng.Copy
wdRange.Paste
End With
Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:
Another recommended exersice for understanding lists and indexes:
L = ['a', 'b', 'c']
for index, item in enumerate(L):
print index + '\n' + item
0
a
1
b
2
c
Properties -> FormBorderStyle -> FixedSingle
if you can not find your Properties tool. Go to View -> Properties Window
I'd suggest using a pseudo element in place of the overlay element. Because pseudo elements can't be added on enclosed img
elements, you would still need to wrap the img
element though.
LIVE EXAMPLE HERE -- EXAMPLE WITH TEXT
<div class="image">
<img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>
As for the CSS, set optional dimensions on the .image
element, and relatively position it. If you are aiming for a responsive image, just omit the dimensions and this will still work (example). It's just worth noting that the dimensions must be on the parent element as opposed to the img
element itself, see.
.image {
position: relative;
width: 400px;
height: 400px;
}
Give the child img
element a width of 100%
of the parent and add vertical-align:top
to fix the default baseline alignment issues.
.image img {
width: 100%;
vertical-align: top;
}
As for the pseudo element, set a content value and absolutely position it relative to the .image
element. A width/height of 100%
will ensure that this works with varying img
dimensions. If you want to transition the element, set an opacity of 0
and add the transition properties/values.
.image:after {
content: '\A';
position: absolute;
width: 100%; height:100%;
top:0; left:0;
background:rgba(0,0,0,0.6);
opacity: 0;
transition: all 1s;
-webkit-transition: all 1s;
}
Use an opacity of 1
when hovering over the pseudo element in order to facilitate the transition:
.image:hover:after {
opacity: 1;
}
For the simplest approach, just add the text as the pseudo element's content
value:
.image:after {
content: 'Here is some text..';
color: #fff;
/* Other styling.. */
}
That should work in most instances; however, if you have more than one img
element, you might not want the same text to appear on hover. You could therefore set the text in a data-*
attribute and therefore have unique text for every img
element.
.image:after {
content: attr(data-content);
color: #fff;
}
With a content
value of attr(data-content)
, the pseudo element adds the text from the .image
element's data-content
attribute:
<div data-content="Text added on hover" class="image">
<img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>
You can add some styling and do something like this:
In the above example, the :after
pseudo element serves as the black overlay, while the :before
pseudo element is the caption/text. Since the elements are independent of each other, you can use separate styling for more optimal positioning.
.image:after, .image:before {
position: absolute;
opacity: 0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
}
.image:after {
content: '\A';
width: 100%; height:100%;
top: 0; left:0;
background:rgba(0,0,0,0.6);
}
.image:before {
content: attr(data-content);
width: 100%;
color: #fff;
z-index: 1;
bottom: 0;
padding: 4px 10px;
text-align: center;
background: #f00;
box-sizing: border-box;
-moz-box-sizing:border-box;
}
.image:hover:after, .image:hover:before {
opacity: 1;
}
You can do:
setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));
At first line of the Jframe class constructor, that works fine for me
I haven't used Cassandra, but I have used MongoDB and think it's awesome.
If you're after simple setup, this is it: You simply untar MongoDB and run the mongod daemon and that's it ... it's running.
Obviously that's only a starter, but to get you started it's easy.
If you are using skaffold, use 'context:' to specify context location for each image dockerfile - context: ../../../
apiVersion: skaffold/v2beta4
kind: Config
metadata:
name: frontend
build:
artifacts:
- image: nginx-angular-ui
context: ../../../
sync:
# A local build will update dist and sync it to the container
manual:
- src: './dist/apps'
dest: '/usr/share/nginx/html'
docker:
dockerfile: ./tools/pipelines/dockerfile/nginx.dev.dockerfile
- image: webapi/image
context: ../../../../api/
docker:
dockerfile: ./dockerfile
deploy:
kubectl:
manifests:
- ./.k8s/*.yml
skaffold run -f ./skaffold.yaml
Make this in your test.ps1, at the first line
param(
[string]$a
)
Write-Host $a
Then you can call it with
./Test.ps1 "Here is your text"
The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
check the import statements since a module is not callable. In Python, everything (including functions, methods, modules, classes etc.) is an object.
The u in u'Some String'
means that your string is a Unicode string.
Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.
A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.
Q: sry no time code pls
A: Fine. try str('Some String')
or 'Some String'.encode('ascii', 'ignore')
. But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.
for me adding Intent.FLAG_ACTIVITY_CLEAR_TASK
solved the problem
Intent i = new Intent(SettingsActivity.this, StartPage.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
You will need to add the application.properties
file in your classpath.
If you are using Maven or Gradle, you can just put the file under src/main/resources
.
If you are not using Maven or any other build tools, put that under your src folder and you should be fine.
Then you can just add an entry server.port = xxxx
in the properties file.
Just nest another if clause in the else statement. But that doesn't make it look any prettier.
>>> x=5
>>> x if x>0 else ("zero" if x==0 else "invalid value")
5
>>> x = 0
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'zero'
>>> x = -1
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'invalid value'
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
Try this:
String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue();
System.out.println(a);
I wrote about this recently at http://snmaynard.com/2012/12/21/node-error-handling/. A new feature of node in version 0.8 is domains and allow you to combine all the forms of error handling into one easier manage form. You can read about them in my post.
You can also use something like Bugsnag to track your uncaught exceptions and be notified via email, chatroom or have a ticket created for an uncaught exception (I am the co-founder of Bugsnag).
Here is a way to calculate memory usage of currently running application:
public static long getUsedMemorySize() {
long freeSize = 0L;
long totalSize = 0L;
long usedSize = -1L;
try {
Runtime info = Runtime.getRuntime();
freeSize = info.freeMemory();
totalSize = info.totalMemory();
usedSize = totalSize - freeSize;
} catch (Exception e) {
e.printStackTrace();
}
return usedSize;
}
Actually this is not a duplicate question. And this how i solve my problem after several times :
int offset = DateTimeZone.forID("anytimezone").getOffset(new DateTime());
This is the way to get offset from desired timezone.
Let's return to our code, we were getting timestamp from a result set of query, and using it with timezone to create our datetime.
DateTime dt = new DateTime(rs.getTimestamp("anytimestampcolumn"),
DateTimeZone.forID("anytimezone"));
Now we will add our offset to the datetime, and get the timestamp from it.
dt = dt.plusMillis(offset);
Timestamp ts = new Timestamp(dt.getMillis());
May be this is not the actual way to get it, but it solves my case. I hope it helps anyone who is stuck here.
I made a mistake by adding a service
into imports
array instead of providers
array.
@NgModule({
imports: [
MyService // wrong here
],
providers: [
MyService // should add here
]
})
export class AppModule { }
Angular
says you need to add Injectables
into providers
array.
I think when you can follow the same or similar design patterns as a true OO language like Java/C#, you can pretty much call it an OO language. Some aspects are obviously different but you can still use very well established OO design pattersn.
I think you can always try the Ctrl + Shift + A to find the action/command you need.
Here you can try to press Ctrl + Shift + A and input «test» to find the command.
Also to note you can see your android dependencies, by going to your Android Studio Gradle view, and selecting the target "androidDependencies".
One more tip: I was having this issue, until I removed the v4 support lib from the libs folder in both the project and my related module/library project(s).
I have two functions:
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}
Then you can use setCaretToPos like this:
setCaretToPos(document.getElementById("YOURINPUT"), 4);
Live example with both a textarea
and an input
, showing use from jQuery:
function setSelectionRange(input, selectionStart, selectionEnd) {_x000D_
if (input.setSelectionRange) {_x000D_
input.focus();_x000D_
input.setSelectionRange(selectionStart, selectionEnd);_x000D_
} else if (input.createTextRange) {_x000D_
var range = input.createTextRange();_x000D_
range.collapse(true);_x000D_
range.moveEnd('character', selectionEnd);_x000D_
range.moveStart('character', selectionStart);_x000D_
range.select();_x000D_
}_x000D_
}_x000D_
_x000D_
function setCaretToPos(input, pos) {_x000D_
setSelectionRange(input, pos, pos);_x000D_
}_x000D_
_x000D_
$("#set-textarea").click(function() {_x000D_
setCaretToPos($("#the-textarea")[0], 10)_x000D_
});_x000D_
$("#set-input").click(function() {_x000D_
setCaretToPos($("#the-input")[0], 10);_x000D_
});
_x000D_
<textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
<br><input type="button" id="set-textarea" value="Set in textarea">_x000D_
<br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit">_x000D_
<br><input type="button" id="set-input" value="Set in input">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
_x000D_
As of 2016, tested and working on Chrome, Firefox, IE11, even IE8 (see that last here; Stack Snippets don't support IE8).
Powershell handles tasks like this fairly handily:
$productCode = (gwmi win32_product | `
? { $_.Name -Like "<PRODUCT NAME HERE>*" } | `
% { $_.IdentifyingNumber } | `
Select-Object -First 1)
You can then use it to get the uninstall information as well:
$wow = ""
$is32BitInstaller = $True # or $False
if($is32BitInstaller -and [System.Environment]::Is64BitOperatingSystem)
{
$wow = "\Wow6432Node"
}
$regPath = "HKEY_LOCAL_MACHINE\SOFTWARE$wow\Microsoft\Windows\CurrentVersion\Uninstall"
dir "HKLM:\SOFTWARE$wow\Microsoft\Windows\CurrentVersion\Uninstall" | `
? { $_.Name -Like "$regPath\$productCode" }
If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand &
and the element delimiter less-than and greater-than signs <
>
:
& becomes &
< becomes <
> becomes >
Inside of attribute values you must also escape the quote character you're using:
" becomes "
' becomes '
In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.
If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.
In general, you should not escape spaces as
.
is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert extra space without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.
1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p>
or <p title="HERE">...</p>
. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>
, <script>NOT-HERE</script>
, <style>NOT-HERE</style>
, or <p NOT-HERE="...">...</p>
.
In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.
If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.
With the help of ProgrammersBlock posts I came up with this. My needs were slightly different. I needed to take a string and return it as a LocalDate object. I was handed code that was using the older Calendar and SimpleDateFormat. I wanted to make it a little more current. This is what I came up with.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
void ExampleFormatDate() {
LocalDate formattedDate = null; //Declare LocalDate variable to receive the formatted date.
DateTimeFormatter dateTimeFormatter; //Declare date formatter
String rawDate = "2000-01-01"; //Test string that holds a date to format and parse.
dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
//formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
//First, the rawDate string is formatted according to DateTimeFormatter. Second, that formatted string is parsed into
//the LocalDate formattedDate object.
formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));
}
Hopefully this will help someone, if anyone sees a better way of doing this task please add your input.
You should also mind the references to other objects.
If the table was highly referenced by other tables than it’s probably also highly referenced by other objects such as views, stored procedures, functions and more.
I’d really recommend GUI tool such as ‘view dependencies’ dialog in SSMS or free tool like ApexSQL Search for this because searching for dependencies in other objects can be error prone if you want to do it only with SQL.
If SQL is the only option you could try doing it like this.
select O.name as [Object_Name], C.text as [Object_Definition]
from sys.syscomments C
inner join sys.all_objects O ON C.id = O.object_id
where C.text like '%table_name%'
You can use the CONCAT
with CURDATE()
to the entire time of the day and then filter by using the BETWEEN
in WHERE
condition:
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE (users.signup_date BETWEEN CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59'))
You can configure your build.gradle file for proguard implementation. It can be at module level or the project level.
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
The configuration shown is for debug level but you can write you own build flavors like shown below inside buildTypes:
myproductionbuild{
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
Better to have your debug with minifyEnabled false
and productionbuild and other builds as minifyEnabled true
.
Copy your proguard-rules.txt file in the root of your module or project folder like
$YOUR_PROJECT_DIR\YoutProject\yourmodule\proguard-rules.txt
You can change the name of your file as you want. After configuration use one of the three options available to generate your build as per the buildType
Go to gradle task in right panel and search for assembleRelease/assemble(#your_defined_buildtype)
under module tasks
Go to Build Variant in Left Panel and select the build from drop down
Go to project root directory in File Explorer and open cmd/terminal and run
Linux ./gradlew assembleRelease or assemble(#your_defined_buildtype)
Windows gradlew assembleRelease or assemble(#your_defined_buildtype)
You can find apk in your module/build directory.
More about the configuration and proguard files location is available at the link
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Running-ProGuard
When you need padding inside the JPanel
generally you add padding with the layout manager you are using. There are cases that you can just expand the border of the JPanel
.
Subprocess module is a good module to launch subprocesses. You can use it to call shell commands as this:
subprocess.call(["ls","-l"]);
#basic syntax
#subprocess.call(args, *)
You can see its documentation here.
If you have your script written in some .sh file or a long string, then you can use os.system module. It is fairly simple and easy to call:
import os
os.system("your command here")
# or
os.system('sh file.sh')
This command will run the script once, to completion, and block until it exits.
The BCP Utility can also be used in the form of a .bat file, but be cautious of escape sequences (ie quotes "" must be used in conjunction with ) and the appropriate tags.
.bat Example:
C:
bcp "\"YOUR_SERVER\".dbo.Proc" queryout C:\FilePath.txt -T -c -q
-- Add PAUSE here if you'd like to see the completed batch
-q MUST be used in the presence of quotations within the query itself.
BCP can also run Stored Procedures if necessary. Again, be cautious: Temporary Tables must be created prior to execution or else you should consider using Table Variables.
I am guessing that you are running the file using Run | Run File
(or shift-F6) rather than Run | Run Main Project
. The NetBeans 7.1 help file (F1 is your friend!) states for the Arguments parameter:
Add arguments to pass to the main class during application execution. Note that arguments cannot be passed to individual files.
I verified this with a little snippet of code:
public class Junk
{
public static void main(String[] args)
{
for (String s : args)
System.out.println("arg -> " + s);
}
}
I set Run -> Arguments to x y z
. When I ran the file by itself I got no output. When I ran the project the output was:
arg -> x
arg -> y
arg -> z
As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf()
.
Placeholders:
%s
String.%d
,%i
Integer number.%f
Floating point number.%o
Object hyperlink.e.g.
console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);
BTW, to see the output:
Ctrl + Shift + J
or F12
to open developer tool.Ctrl + Shift + K
or F12
to open developer tool.@Update - nodejs support
Seems nodejs don't support %f
, instead, could use %d
in nodejs.
With %d
number will be printed as floating number, not just integer.
"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value
{ * * "ProjectID" * * : {
"name": "ProjectID",
"value": "16,36,8,7",
"group": "Genel",
"editor": {
"type": "combobox",
"options": {
"url": "..\/jsonEntityVarServices\/?id=6&task=7",
"valueField": "value",
"textField": "text",
"multiple": "true"
}
},
"id": "14",
"entityVarID": "16",
"EVarMemID": "47"
}
}
Deleting Obj, retail and debug folder of the .NET project and re-building again worked for me.
Try this:
function someFunction(username, password) {
return new Promise((resolve, reject) => {
// Do something with the params username and password...
if ( /* everything turned out fine */ ) {
resolve("Stuff worked!");
} else {
reject(Error("It didn't work!"));
}
});
}
someFunction(username, password)
.then((result) => {
// Do something...
})
.catch((err) => {
// Handle the error...
});
If you're on Windows:
HANDLE h;
CHAR_INFO v3;
COORD v4;
SMALL_RECT v5;
CONSOLE_SCREEN_BUFFER_INFO v6;
if ((h = (HANDLE)GetStdHandle(0xFFFFFFF5), (unsigned int)GetConsoleScreenBufferInfo(h, &v6)))
{
v5.Right = v6.dwSize.X;
v5.Bottom = v6.dwSize.Y;
v3.Char.UnicodeChar = 32;
v4.Y = -v6.dwSize.Y;
v3.Attributes = v6.wAttributes;
v4.X = 0;
*(DWORD *)&v5.Left = 0;
ScrollConsoleScreenBufferW(h, &v5, 0, v4, &v3);
v6.dwCursorPosition = { 0 };
HANDLE v1 = GetStdHandle(0xFFFFFFF5);
SetConsoleCursorPosition(v1, v6.dwCursorPosition);
}
This is what the system("cls"); does without having to create a process to do it.
Use .prop()
instead and if we go with your code then compare like this:
Look at the example jsbin:
$("#news_list tr").click(function () {
var ele = $(this).find(':checkbox');
if ($(':checked').length) {
ele.prop('checked', false);
$(this).removeClass('admin_checked');
} else {
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
Changes:
input
to :checkbox
.the length
of the checked checkboxes
.In the accepted answer bobince got it right: validating only the scheme name, ://, and spaces and double quotes is usually enough. Here is how the validation can be implemented in JavaScript:
var url = 'http://www.google.com';
var valid = /^(ftp|http|https):\/\/[^ "]+$/.test(url);
// true
or
var r = /^(ftp|http|https):\/\/[^ "]+$/;
r.test('http://www.goo le.com');
// false
or
var url = 'http:www.google.com';
var r = new RegExp(/^(ftp|http|https):\/\/[^ "]+$/);
r.test(url);
// false
References for syntax:
contentType
option to false
is used for multipart/form-data
forms that pass files.
When one sets the contentType
option to false
, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Use jQuery's .serialize()
method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false
.
Try using new FormData
instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log()
.
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
the simplest way I found so far is from git official website. It just computed dependencies and downloaded all of the required libraries/tools
http://git-scm.com/book/en/Getting-Started-Installing-Git
The other major way is to install Git via MacPorts (http://www.macports.org). If you have MacPorts installed, install Git via
$ sudo port install git-core +svn +doc +bash_completion +gitweb
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
Conditional Forms
Simple
conditional-directive
text-if-true
endif
Moderately Complex
conditional-directive
text-if-true
else
text-if-false
endif
More Complex
conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif
Conditional Directives
If Equal Syntax
ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"
If Not Equal Syntax
ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"
If Defined Syntax
ifdef variable-name
If Not Defined Syntax
ifndef variable-name
foreach Function
foreach Function Syntax
$(foreach var, list, text)
foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.
Also you can try this line to get string value from app.config
file.
var strName= ConfigurationManager.AppSettings["stringName"];
Just in caser anyone ends here like me. In may case despite having enabled unsecure access to my google account, it refused to send the email throwing an SMTP ERROR: Password command failed: 534-5.7.14.
(Solution found at https://know.mailsbestfriend.com/smtp_error_password_command_failed_5345714-1194946499.shtml)
Steps:
log into your google account
Go to https://accounts.google.com/b/0/DisplayUnlockCaptcha and click continue to enable.
Setup your phpmailer as smtp with ssl:
$mail = new PHPMailer(true);
$mail->CharSet ="utf-8";
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // or 0 for no debuggin at all
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->SMTPAuth = true;
$mail->Username = 'yourgmailaccount';
$mail->Password = 'yourpassword';
And the other $mail object properties as needed.
Hope it helps someone!!
A graduate student from National Cheng Kung University in Taiwan did a research on this subject in 2004. He was able to achieve success rate of 89.79% in detecting nude pictures downloaded from the Internet. Here is the link to his thesis: The Study on Naked People Image Detection Based on Skin Color
It's in Chinese therefore you may need a translator in case you can't read it.
If you have the option of giving a fixed width to the table cells (and a fixed height to the header), you can used the position: fixed
option:
http://jsfiddle.net/thundercracker/ZxPeh/23/
You would just have to stick it in an iframe
. You could also have horizontal scrolling by giving the iframe
a scrollbar (I think).
Edit 2015
If you can live with a pre-defining the width of your table cells (by percentage), then here's a bit more elegant (CSS-only) solution:
This can now be achieved by simply setting the domain to none
.
ga('create', 'UA-XXXX-Y', 'none');
See: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains#localhost
First of all, you have to create some dynamic memory space. Then you can just strcat the two strings into it. Or you can use the c++ "string" class. The old-school C way:
char* catString = malloc(strlen(one)+strlen(two)+1);
strcpy(catString, one);
strcat(catString, two);
// use the string then delete it when you're done.
free(catString);
New C++ way
std::string three(one);
three += two;
I tried WebLoad it's a pretty neat tool. It comes with and test script IDE which allows you to record user action on a website. It also draws a graph as it perform stress test on your web server. Try it out, I highly recommend it.
For one matched character replace, use str_replace:
$string = str_replace(' ', '_', $string);
For all matched character replace, use preg_replace:
$string = preg_replace('/\s+/', '_', $string);
Use $key => $val
to get the keys:
<?php
$arr = array(
1 => "Value1",
2 => "Value2",
10 => "Value10",
);
foreach ($arr as $key => $val) {
print "$key\n";
}
?>
I had the same error on Debian and all I had to do was:
sudo su
and then run the command again and it worked.
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
The simplest Hello World example...
$hello = "Hello World"
$hello | Out-File c:\debug.txt
It's a type constraint on T
, specifying that it must be a class.
The where
clause can be used to specify other type constraints, e.g.:
where T : struct // T must be a struct
where T : new() // T must have a default parameterless constructor
where T : IComparable // T must implement the IComparable interface
For more information, check out MSDN's page on the where
clause, or generic parameter constraints.
The difference is that functionOne
is a function expression and so only defined when that line is reached, whereas functionTwo
is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).
For example, a function expression:
// TypeError: functionOne is not a function_x000D_
functionOne();_x000D_
_x000D_
var functionOne = function() {_x000D_
console.log("Hello!");_x000D_
};
_x000D_
And, a function declaration:
// Outputs: "Hello!"_x000D_
functionTwo();_x000D_
_x000D_
function functionTwo() {_x000D_
console.log("Hello!");_x000D_
}
_x000D_
Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.
'use strict'; _x000D_
{ // note this block!_x000D_
function functionThree() {_x000D_
console.log("Hello!");_x000D_
}_x000D_
}_x000D_
functionThree(); // ReferenceError
_x000D_
I would use Different IDs but assign each DIV the same class.
<div id="c-1" class="countdown"></div>
<div id="c-2" class="countdown"></div>
This also has the added benefit of being able to reconstruct the IDs based off of the return of jQuery('.countdown').length
Ok what about adding multiple classes to each countdown timer. IE:
<div class="countdown c-1"></div>
<div class="countdown c-2"></div>
<div class="countdown c-1"></div>
That way you get the best of both worlds. It even allows repeat 'IDS'
There are several ways I can think of to do this.
Use a callback:
function FunctInit(someVarible){
//init and fill screen
AndroidCallGetResult(); // Enables Android button.
}
function getResult(){ // Called from Android button only after button is enabled
//return some variables
}
Use a Timeout (this would probably be my preference):
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
if (inited) {
//return some variables
} else {
setTimeout(getResult, 250);
}
}
Wait for the initialization to occur:
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
var a = 1;
do { a=1; }
while(!inited);
//return some variables
}
Automatic bidirectional sorting only works with the SQL data source. Unfortunately, all the documentation in MSDN assumes you are using that, so GridView can get a bit frustrating.
The way I do it is by keeping track of the order on my own. For example:
protected void OnSortingResults(object sender, GridViewSortEventArgs e)
{
// If we're toggling sort on the same column, we simply toggle the direction. Otherwise, ASC it is.
// e.SortDirection is useless and unreliable (only works with SQL data source).
if (_sortBy == e.SortExpression)
_sortDirection = _sortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
else
_sortDirection = SortDirection.Ascending;
_sortBy = e.SortExpression;
BindResults();
}
Mi helped: windows defender settings >> device security >> core insulation (details) >> Memory integrity >> Disable (OFF) SYSTEM RESTART ! this solution is better for me
I had the same issue. Fixed it by adding a static route on my host to my VM via the VMnet8 adapter:
route ADD VM_addr MASK 255.255.255.255 VMnet8_addr
As previously mentioned, you need a bridged connection.
You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html
geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()
emacs works very well with files into the 100's of megabytes, I've used it on log files without too much trouble.
But generally when I have some kind of analysis task, I find writing a perl script a better choice.
Use python library called num2words
Link -> HERE
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:
Just build on the system with the oldest GLIBC you still want to support.
This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:
Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.
Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.
With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.
I had the same problem. Here's what I figured out:
=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")
A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.
I was curious about the relative speed of the two popular approaches - casting to string and using modular arithmetic - so I profiled them and was surprised to see how close they were in terms of performance.
(My use-case was slightly different, I wanted to get all digits in the number.)
The string approach gave:
10000002 function calls in 1.113 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
10000000 1.113 0.000 1.113 0.000 sandbox.py:1(get_digits_str)
1 0.000 0.000 0.000 0.000 cProfile.py:133(__exit__)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
While the modular arithmetic approach gave:
10000002 function calls in 1.102 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
10000000 1.102 0.000 1.102 0.000 sandbox.py:6(get_digits_mod)
1 0.000 0.000 0.000 0.000 cProfile.py:133(__exit__)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
There were 10^7 tests run with a max number size less than 10^28.
Code used for reference:
def get_digits_str(num):
for n_str in str(num):
yield int(n_str)
def get_digits_mod(num, radix=10):
remaining = num
yield remaining % radix
while remaining := remaining // radix:
yield remaining % radix
if __name__ == '__main__':
import cProfile
import random
random_inputs = [random.randrange(0, 10000000000000000000000000000) for _ in range(10000000)]
with cProfile.Profile() as str_profiler:
for rand_num in random_inputs:
get_digits_str(rand_num)
str_profiler.print_stats(sort='cumtime')
with cProfile.Profile() as mod_profiler:
for rand_num in random_inputs:
get_digits_mod(rand_num)
mod_profiler.print_stats(sort='cumtime')
For simple cases like this, TimeUnit should be used. TimeUnit usage is a bit more explicit about what is being represented and is also much easier to read and write when compared to doing all of the arithmetic calculations explicitly. For example, to calculate the number days from milliseconds, the following statement would work:
long days = TimeUnit.MILLISECONDS.toDays(milliseconds);
For cases more advanced, where more finely grained durations need to be represented in the context of working with time, an all encompassing and modern date/time API should be used. For JDK8+, java.time is now included (here are the tutorials and javadocs). For earlier versions of Java joda-time is a solid alternative.
You can solve this fully in the html:
<div>
<input ng-model=collapse type=checkbox>Title
<div ng-show=collapse>
Only shown when checkbox is clicked
</div>
</div>
This also works well with ng-repeat since it will create a local scope for each member.
<table>
<tbody ng-repeat='m in members'>
<tr>
<td><input type=checkbox ng-model=collapse></td>
<td>{{m.title}}</td>
</tr>
<tr ng-show=collapse>
<td> </td>
<td>{{ m.content }}</td>
</tr>
</tbody>
</table>
Be aware that even though a repeat has its own scope, initially it will inherit the value from collapse from super scopes. This allows you to set the initial value in one place but it can be surprising.
You can of course restyle the checkbox. See http://jsfiddle.net/azD5m/5/
Updated fiddle: http://jsfiddle.net/azD5m/374/ Original fiddle used closing </input>
tags to add the HTML text label instead of using <label>
tags.
Let me clear two points here :
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b) are positional parameter
(c=none) is optional parameter
(r="w") is keyword parameter
(d=[]) is list parameter
(*ae) is keyword-only
(**ab) is var-keyword parameter
def example(a, b, c=a,d=b):
argument is not defined when default values are saved,Python computes and saves default values when you define the function
c and d are not defined, does not exist, when this happens (it exists only when the function is executed)
"a,a=b" its not allowed in parameter.
You can simply use event.target.dataset object . This will give you the object with all data attributes.
Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using %lf
, %lg
or %le
(or %la
in C99) to read in doubles.
Try sudo pip install numpy --upgrade --ignore-installed
.
It work in Mac OS 10.11.
You should close The 'Rootless' if above shell isn't work.
data d is in row 0 and column 3 for value d :
DataTable table;
String d = (String)table.Rows[0][3];
This command may solve the problem :
git add -A
All the files and subdirectories will be added to be tracked.
Hope it helps
Try to avoid using null
in Scala. It's really there only for interoperability with Java. In Scala, use Option
for things that might be empty. If you're calling a Java API method that might return null
, wrap it in an Option
immediately.
def getObject : Option[QueueObject] = {
// Wrap the Java result in an Option (this will become a Some or a None)
Option(someJavaObject.getResponse)
}
Note: You don't need to put it in a val
or use an explicit
return
statement in Scala; the result will be the value of
the last expression in the block (in fact, since there's only one statement, you don't even need a block).
def getObject : Option[QueueObject] = Option(someJavaObject.getResponse)
Besides what the others have already shown (for example calling foreach
on the Option
, which might be slightly confusing), you could also call map
on it (and ignore the result of the map operation if you don't need it):
getObject map QueueManager.add
This will do nothing if the Option
is a None
, and call QueueManager.add
if it is a Some
.
I find using a regular if
however clearer and simpler than using any of these "tricks" just to avoid an indentation level. You could also just write it on one line:
if (getObject.isDefined) QueueManager.add(getObject.get)
or, if you want to deal with null
instead of using Option
:
if (getObject != null) QueueManager.add(getObject)
edit - Ben is right, be careful to not call getObject
more than once if it has side-effects; better write it like this:
val result = getObject
if (result.isDefined) QueueManager.add(result.get)
or:
val result = getObject
if (result != null) QueueManager.add(result)
Look into the File class.
You can create a streamwriter with
StreamWriter sw = File.Create(....)
You can open an existing file with
File.Open(...)
You can append text easily with
File.AppendAllText(...);
(Obligatory 'this is probably an internal youtube.com interface and might break at any time')
Instead of linking to another tool that does this, here's an answer to the question of "how to do this"
Use fiddler or your browser devtools (e.g.
Chrome) to inspect the youtube.com HTTP traffic, and there's a response from /api/timedtext
that contains the closed caption info as XML.
It seems that a response like this:
<p t="0" d="5430" w="1">
<s p="2" ac="136">we've</s>
<s t="780" ac="252"> got</s>
</p>
<p t="2280" d="7170" w="1">
<s ac="243">we're</s>
<s t="810" ac="233"> going</s>
</p>
means at time 0
is the word we've
and at time 0+780
is the word got
and at time 2280+810
is the word going
, etc. This time is in milliseconds so for time 3090 you'd want to append &t=3
to the URL.
You can use any tool to stitch together the XML into something readable, but here's my Power BI Desktop script to find words like "privilege":
let
Source = Xml.Tables(File.Contents("C:\Download\body.xml")),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Attribute:format", Int64.Type}}),
body = #"Changed Type"{0}[body],
p = body{0}[p],
#"Changed Type1" = Table.TransformColumnTypes(p,{{"Attribute:t", Int64.Type}, {"Attribute:d", Int64.Type}, {"Attribute:w", Int64.Type}, {"Attribute:a", Int64.Type}, {"Attribute:p", Int64.Type}}),
#"Expanded s" = Table.ExpandTableColumn(#"Changed Type1", "s", {"Attribute:ac", "Attribute:p", "Attribute:t", "Element:Text"}, {"s.Attribute:ac", "s.Attribute:p", "s.Attribute:t", "s.Element:Text"}),
#"Changed Type2" = Table.TransformColumnTypes(#"Expanded s",{{"s.Attribute:t", Int64.Type}}),
#"Removed Other Columns" = Table.SelectColumns(#"Changed Type2",{"s.Attribute:t", "s.Element:Text", "Attribute:t"}),
#"Replaced Value" = Table.ReplaceValue(#"Removed Other Columns",null,0,Replacer.ReplaceValue,{"s.Attribute:t"}),
#"Filtered Rows" = Table.SelectRows(#"Replaced Value", each [#"s.Element:Text"] <> null),
#"Added Custom" = Table.AddColumn(#"Filtered Rows", "Time", each [#"Attribute:t"] + [#"s.Attribute:t"]),
#"Filtered Rows1" = Table.SelectRows(#"Added Custom", each ([#"s.Element:Text"] = " privilege" or [#"s.Element:Text"] = " privileged" or [#"s.Element:Text"] = " privileges" or [#"s.Element:Text"] = "privilege" or [#"s.Element:Text"] = "privileges"))
in
#"Filtered Rows1"
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
RJSONIO from Omegahat is another package which provides facilities for reading and writing data in JSON format.
rjson does not use S4/S3 methods and so is not readily extensible, but still useful. Unfortunately, it does not used vectorized operations and so is too slow for non-trivial data. Similarly, for reading JSON data into R, it is somewhat slow and so does not scale to large data, should this be an issue.
Update (new Package 2013-12-03):
jsonlite: This package is a fork of the RJSONIO
package. It builds on the parser from RJSONIO
but implements a different mapping between R objects and JSON strings. The C code in this package is mostly from the RJSONIO
Package, the R code has been rewritten from scratch. In addition to drop-in replacements for fromJSON
and toJSON
, the package has functions to serialize objects. Furthermore, the package contains a lot of unit tests to make sure that all edge cases are encoded and decoded consistently for use with dynamic data in systems and applications.
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaI have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:
$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');
Looking at the phpmailer code in more detail this is the offending line:
public function SetFrom($address, $name = '',$auto=1) {
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (!self::ValidateAddress($address)) {
$this->SetError($this->Lang('invalid_address').': '. $address);
if ($this->exceptions) {
throw new phpmailerException($this->Lang('invalid_address').': '.$address);
}
echo $this->Lang('invalid_address').': '.$address;
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto) {
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
if (empty($this->Sender)) {
$this->Sender = $address;
}
}
return true;
}
Specifically this line:
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
Thanks for your help everyone!
It is implemented by a Callback interface:
First of all, we have to make an interface:
public interface UpdateFrag {
void updatefrag();
}
In the Activity do the following code:
UpdateFrag updatfrag ;
public void updateApi(UpdateFrag listener) {
updatfrag = listener;
}
from the event from where the callback has to fire in the Activity:
updatfrag.updatefrag();
In the Fragment implement the interface in
CreateView
do the following code:
((Home)getActivity()).updateApi(new UpdateFrag() {
@Override
public void updatefrag() {
.....your stuff......
}
});
convert str => obj
const onePlusStr = '[{"brand":"oneplus"},{"model":"7T"}]';
const onePLusObj = JSON.parse(onePlusStr);
convert obj => str
const onePLusObjToStr = JSON.stringify(onePlusStr);
References of JSON parsing in JS:
JSON.parse() : click
JSON.stringify() : click
How about using sed? It comes standard with most (all?) Linux OS.
sed 's/\t/<your_field_delimiter>/g'
.
This example uses GNU sed (Linux). For POSIX sed (AIX/Solaris)I believe you would type a literal TAB instead of \t
Example (for CSV output):
#mysql mysql -B -e "select * from user" | while read; do sed 's/\t/,/g'; done
localhost,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
localhost,bill,*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,,,,,0,0,0,0,,
127.0.0.1,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
::1,root,,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,Y,,,,,0,0,0,0,,
%,jim,*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,,,,,0,0,0,0,,
Integer Array doesn't contain size() or length() method. Try the below code, it'll work. ArrayList contains size() method. String contains length(). Since you have used int array[], so it will be array.length
public class Example {
int array[] = {1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554, 22, 22, 211};
public void Printrange() {
for (int i = 0; i < array.length; i++) {
if (array[i] > 100 && array[i] < 500) {
System.out.println("numbers with in range" + i);
}
}
}
}