Looks like E*Trade has an API now.
For access to historical data, I've found EODData to have reasonable prices for their data dumps. For side projects, I can't afford (rather don't want to afford) a huge subscription fee just for some data to tinker with.
As already explained by others, processes in "D" state (uninterruptible sleep) are responsible for the hang of ps process. To me it has happened many times with RedHat 6.x and automounted NFS home directories.
To list processes in D state you can use the following commands:
cd /proc
for i in [0-9]*;do echo -n "$i :";cat $i/status |grep ^State;done|grep D
To know the current directory of the process and, may be, the mounted NFS disk that has issues you can use a command similar to the following example (replace 31134 with the sleeping process number):
# ls -l /proc/31134/cwd
lrwxrwxrwx 1 pippo users 0 Aug 2 16:25 /proc/31134/cwd -> /auto/pippo
I found that giving the umount command with the -f (force) switch, to the related mounted nfs file system, was able to wake-up the sleeping process:
umount -f /auto/pippo
the file system wasn't unmounted, because it was busy, but the related process did wake-up and I was able to solve the issue without rebooting.
Docker encapsulates an application with all its dependencies.
A virtualizer encapsulates an OS that can run any applications it can normally run on a bare metal machine.
Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:
HTML:
<ul id="menu">
<li><a href="#">Bla</a></li>
<li><a href="#">Bla</a></li>
<li><a href="#">Bla</a></li>
</ul>
CSS:
#menu {
margin: 0;
}
#menu li {
float: left;
list-style: none;
margin: 0;
}
#menu li a {
display: block;
line-height:30px;
width:100px;
background-color:#000;
}
#menu li a:hover {
background-color:#F00;
}
here is how I usually eliminate duplicates
I would try something like this for a Trim function that takes into account all white-space characters defined by the Unicode Standard (LTRIM and RTRIM do not even trim new-line characters!):
IF OBJECT_ID(N'dbo.IsWhiteSpace', N'FN') IS NOT NULL_x000D_
DROP FUNCTION dbo.IsWhiteSpace;_x000D_
GO_x000D_
_x000D_
-- Determines whether a single character is white-space or not (according to the UNICODE standard)._x000D_
CREATE FUNCTION dbo.IsWhiteSpace(@c NCHAR(1)) RETURNS BIT_x000D_
BEGIN_x000D_
IF (@c IS NULL) RETURN NULL;_x000D_
DECLARE @WHITESPACE NCHAR(31);_x000D_
SELECT @WHITESPACE = ' ' + NCHAR(13) + NCHAR(10) + NCHAR(9) + NCHAR(11) + NCHAR(12) + NCHAR(133) + NCHAR(160) + NCHAR(5760) + NCHAR(8192) + NCHAR(8193) + NCHAR(8194) + NCHAR(8195) + NCHAR(8196) + NCHAR(8197) + NCHAR(8198) + NCHAR(8199) + NCHAR(8200) + NCHAR(8201) + NCHAR(8202) + NCHAR(8232) + NCHAR(8233) + NCHAR(8239) + NCHAR(8287) + NCHAR(12288) + NCHAR(6158) + NCHAR(8203) + NCHAR(8204) + NCHAR(8205) + NCHAR(8288) + NCHAR(65279);_x000D_
IF (CHARINDEX(@c, @WHITESPACE) = 0) RETURN 0;_x000D_
RETURN 1;_x000D_
END_x000D_
GO_x000D_
_x000D_
IF OBJECT_ID(N'dbo.Trim', N'FN') IS NOT NULL_x000D_
DROP FUNCTION dbo.Trim;_x000D_
GO_x000D_
_x000D_
-- Removes all leading and tailing white-space characters. NULL is converted to an empty string._x000D_
CREATE FUNCTION dbo.Trim(@TEXT NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)_x000D_
BEGIN_x000D_
-- Check tiny strings (NULL, 0 or 1 chars)_x000D_
IF @TEXT IS NULL RETURN N'';_x000D_
DECLARE @TEXTLENGTH INT = LEN(@TEXT);_x000D_
IF @TEXTLENGTH < 2 BEGIN_x000D_
IF (@TEXTLENGTH = 0) RETURN @TEXT;_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1)) = 1) RETURN '';_x000D_
RETURN @TEXT;_x000D_
END_x000D_
-- Check whether we have to LTRIM/RTRIM_x000D_
DECLARE @SKIPSTART INT;_x000D_
SELECT @SKIPSTART = dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1));_x000D_
DECLARE @SKIPEND INT;_x000D_
SELECT @SKIPEND = dbo.IsWhiteSpace(SUBSTRING(@TEXT, @TEXTLENGTH, 1));_x000D_
DECLARE @INDEX INT;_x000D_
IF (@SKIPSTART = 1) BEGIN_x000D_
IF (@SKIPEND = 1) BEGIN_x000D_
-- FULLTRIM_x000D_
-- Determine start white-space length_x000D_
SELECT @INDEX = 2;_x000D_
WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise assign index as @SKIPSTART_x000D_
SELECT @SKIPSTART = @INDEX;_x000D_
-- Increase character index_x000D_
SELECT @INDEX = (@INDEX + 1);_x000D_
END_x000D_
-- Return '' if the whole string is white-space_x000D_
IF (@SKIPSTART = (@TEXTLENGTH - 1)) RETURN ''; _x000D_
-- Determine end white-space length_x000D_
SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
WHILE (@INDEX > 1) BEGIN _x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise increase @SKIPEND_x000D_
SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
-- Decrease character index_x000D_
SELECT @INDEX = (@INDEX - 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART - @SKIPEND);_x000D_
END _x000D_
-- LTRIM_x000D_
-- Determine start white-space length_x000D_
SELECT @INDEX = 2;_x000D_
WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise assign index as @SKIPSTART_x000D_
SELECT @SKIPSTART = @INDEX;_x000D_
-- Increase character index_x000D_
SELECT @INDEX = (@INDEX + 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART);_x000D_
END ELSE BEGIN_x000D_
-- RTRIM_x000D_
IF (@SKIPEND = 1) BEGIN_x000D_
-- Determine end white-space length_x000D_
SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
WHILE (@INDEX > 1) BEGIN _x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise increase @SKIPEND_x000D_
SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
-- Decrease character index_x000D_
SELECT @INDEX = (@INDEX - 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, 1, @TEXTLENGTH - @SKIPEND);_x000D_
END _x000D_
END_x000D_
-- NO TRIM_x000D_
RETURN @TEXT;_x000D_
END_x000D_
GO
_x000D_
Extension method based on Linq
public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
{
foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
row.Delete();
}
Then use:
DataTable dt = GetSomeData();
dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");
Seems related to https://groups.google.com/forum/#!msg/google-caja-discuss/ite6K5c8mqs/Ayqw72XJ9G8J.
The so-called "Rosetta Flash" vulnerability is that allowing arbitrary yet identifier-like text at the beginning of a JSONP response is sufficient for it to be interpreted as a Flash file executing in that origin. See for more information: http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
JSONP responses from the proxy servlet now: * are prefixed with "/**/", which still allows them to execute as JSONP but removes requester control over the first bytes of the response. * have the response header Content-Disposition: attachment.
in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the :=
notation (see code sample below)
Application.Thisworkbook
refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:
Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)
If ProtectionMode Then
MySheet.Protect DrawingObjects:=True, Contents:=True, _
AllowSorting:=True, AllowFiltering:=True
Else
MySheet.Unprotect
End If
End Sub
Within the .Protect
method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:
Application.Dialogs(xlDialogProtectDocument).Show
Hope that helps
Good luck - MikeD
The problem with the aforementioned solutions is, that if hour, minute or second, has only one digit (i.e. 0-9), the time would be wrong, e.g. it could be 2:3:9, but it should rather be 02:03:09.
According to this page it seems to be a better solution to use Date's "toLocaleTimeString" method.
using (StreamWriter writer = new StreamWriter(File.Open(@"E:\Sample.txt", FileMode.Append), Encoding.GetEncoding(1250))) ////File.Create(path)
{
writer.Write("Sample Text");
}
One possible thing you could do is use the Dictionary object straight out of the box and then just extend it with your own modifications:
public class TokenTree : Dictionary<string, string>
{
public IDictionary<string, string> SubPairs;
}
This gives you the advantage of not having to enforce the rules of IDictionary for your Key (e.g., key uniqueness, etc).
And yup you got the concept of the constructor right :)
I like to do something like this:
String oneLetter = "" + someChar;
This solution is compatible with Android (I've tested and used it myself). Thanks to @user467257 whose solution I adapted this from.
import android.util.Base64;
public class StringXORer {
public String encode(String s, String key) {
return new String(Base64.encode(xorWithKey(s.getBytes(), key.getBytes()), Base64.DEFAULT));
}
public String decode(String s, String key) {
return new String(xorWithKey(base64Decode(s), key.getBytes()));
}
private byte[] xorWithKey(byte[] a, byte[] key) {
byte[] out = new byte[a.length];
for (int i = 0; i < a.length; i++) {
out[i] = (byte) (a[i] ^ key[i%key.length]);
}
return out;
}
private byte[] base64Decode(String s) {
return Base64.decode(s,Base64.DEFAULT);
}
private String base64Encode(byte[] bytes) {
return new String(Base64.encode(bytes,Base64.DEFAULT));
}
}
Try:
float x = (float)rand()/(float)(RAND_MAX/a);
To understand how this works consider the following.
N = a random value in [0..RAND_MAX] inclusively.
The above equation (removing the casts for clarity) becomes:
N/(RAND_MAX/a)
But division by a fraction is the equivalent to multiplying by said fraction's reciprocal, so this is equivalent to:
N * (a/RAND_MAX)
which can be rewritten as:
a * (N/RAND_MAX)
Considering N/RAND_MAX
is always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a
.
Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):
float x = ((float)rand()/(float)(RAND_MAX)) * a;
Note: the floating point representation of a
must be exact or this will never hit your absolute edge case of a
(it will get close). See this article for the gritty details about why.
Sample
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
srand((unsigned int)time(NULL));
float a = 5.0;
for (int i=0;i<20;i++)
printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
return 0;
}
Output
1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719
Performance wise there is no difference. The only purpose of having const_iterator
over iterator
is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:
std::vector<int> integers{ 3, 4, 56, 6, 778 };
If we were to read & write the members of a container we will use iterator:
for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
{*it = 4; std::cout << *it << std::endl; }
If we were to only read the members of the container integers
you might wanna use const_iterator which doesn't allow to write or modify members of container.
for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
{ cout << *it << endl; }
NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.
Oops, can't comment yet (!) but re: Nick and logic analyser, beware: RS232 signal levels not typically Logic Analyser compatible unless you get/make a special serial probe. A 'proper' RS232/Serial port can use +/-12v swings (on all signals) and sometimes more. A laptop sometimes uses 0-5v swings (and often won't work with real serial interfaces) so could work with a vbasic 'ttl-level' LA interface.
$('#toptitle').html('New world');
or
$('#toptitle').text('New world');
A lookup table (pthread_t : int)
could become a memory leak in programs that start a lot of short-lived threads.
Creating a hash of the bytes of the pthread_t
(whether it be structure or pointer or long integer or whatever) may be a usable solution that doesn't require lookup tables. As with any hash there is a risk of collisions, but you could tune the length of the hash to suit your requirements.
I had similar problem when using minikube over hyperv with 2048GB memory. I found that in HyperV manager the Memory Demand was higher than allocated.
So I stopped minikube and assigned somewhere between 4096-6144GB. It worked fine after that, all pods running!
I don't know if this can nail down the issue in every case. But just have a look at the memory and disk allocated to the minikube.
In many circumstances they are different names for the same thing, but in some contexts they are quite different. So it depends. Terminology is not applied in a totally consistent way across the whole software industry.
For example in the classic sockets API, a non-blocking socket is one that simply returns immediately with a special "would block" error message, whereas a blocking socket would have blocked. You have to use a separate function such as select
or poll
to find out when is a good time to retry.
But asynchronous sockets (as supported by Windows sockets), or the asynchronous IO pattern used in .NET, are more convenient. You call a method to start an operation, and the framework calls you back when it's done. Even here, there are basic differences. Asynchronous Win32 sockets "marshal" their results onto a specific GUI thread by passing Window messages, whereas .NET asynchronous IO is free-threaded (you don't know what thread your callback will be called on).
So they don't always mean the same thing. To distil the socket example, we could say:
didn't work for me. I had to explicitly use onPrepareOptionsMenu
to set an item invisible.
So use onCreateOptionsMenu
to create the menu and onPrepareOptionsMenu
to change visibility etc.
A workaround that worked for me (using Backbone.js), was to add "#/" to the end of the redirect URL passed to Facebook. Facebook will keep the provided fragment, and not append its own "_=_".
Upon return, Backbone will remove the "#/" part. For AngularJS, appending "#!" to the return URL should work.
Note that the fragment identifier of the original URL is preserved on redirection (via HTTP status codes 300, 301, 302 and 303) by most browsers, unless the redirect URL also has a fragment identifier. This seems to be recommended behaviour.
If you use a handler script that redirects the user elsewhere, you can append "#" to the redirect URL here to replace the fragment identifier with an empty string.
You can project 3D point in 2D using: Commons Math: The Apache Commons Mathematics Library with just two classes.
Example for Java Swing.
import org.apache.commons.math3.geometry.euclidean.threed.Plane;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
Plane planeX = new Plane(new Vector3D(1, 0, 0));
Plane planeY = new Plane(new Vector3D(0, 1, 0)); // Must be orthogonal plane of planeX
void drawPoint(Graphics2D g2, Vector3D v) {
g2.drawLine(0, 0,
(int) (world.unit * planeX.getOffset(v)),
(int) (world.unit * planeY.getOffset(v)));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawPoint(g2, new Vector3D(2, 1, 0));
drawPoint(g2, new Vector3D(0, 2, 0));
drawPoint(g2, new Vector3D(0, 0, 2));
drawPoint(g2, new Vector3D(1, 1, 1));
}
Now you only needs update the planeX
and planeY
to change the perspective-projection, to get things like this:
I think in this case concat
is what you want:
In [12]:
pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
attr_1 attr_2 attr_3 id quantity
0 0 1 NaN 1 20
1 1 1 NaN 2 23
2 1 1 NaN 3 19
3 0 0 NaN 4 19
4 1 NaN 0 5 8
5 0 NaN 1 6 13
6 1 NaN 1 7 20
7 1 NaN 1 8 25
by passing axis=0
here you are stacking the df's on top of each other which I believe is what you want then producing NaN
value where they are absent from their respective dfs.
Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.
Quote:
Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.
ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.
You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-ful API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.
It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.
To give a real world example: I'm currently working with an ERP system that provides a REST-ful API to its entities. For this API, WebAPI would be a good candidate. At the same time, the ERP system provides a highly AJAX-ified web application that you can use to create queries for the REST-ful API. The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc.
One interesting location where interfaces fare better than abstract classes is when you need to add extra functionality to a group of (related or unrelated) objects. If you cannot give them a base abstract class (e.g., they are sealed
or already have a parent), you can give them a dummy (empty) interface instead, and then simply write extension methods for that interface.
Here's the simplest, most robust, and scalable solution to get tabs on the bottom of the screen.
layout_height
to wrap_content
on both FrameLayout and TabWidget android:layout_weight="1"
android:layout_weight="0"
(0 is default, but for emphasis, readability, etc)android:layout_marginBottom="-4dp"
(to remove the bottom divider)Full code:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_weight="1"/>
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:layout_marginBottom="-4dp"/>
</LinearLayout>
</TabHost>
Renames all .pdf
files based on current system date. For example a file named Gross Profit.pdf
is renamed to Gross Profit 2014-07-31.pdf
. If you run it tomorrow, it will rename it to Gross Profit 2014-08-01.pdf
.
You could replace the ?
with the report name Gross Profit
, but it will only rename the one report. The ?
renames everything in the Conduit
folder. The reason there are so many ?
, is that some .pdf
s have long names. If you just put 12 ?
s, then any name longer than 12 characters will be clipped off at the 13th character. Try it with 1 ?
, then try it with many ?
s. The ?
length should be a little longer or as long as the longest report name.
@ECHO OFF
SET NETWORKSOURCE=\\flcorpfile\shared\"SHORE Reports"\2014\Conduit
REN %NETWORKSOURCE%\*.pdf "????????????????????????????????????????????????? %date:~-4,4%-%date:~-10,2%-%date:~7,2%.pdf"
You can use the cherry-pick to get the particular bug fix commit(s)
$ git checkout branch
$ git cherry-pick bugfix
Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.
import com.google.gson.Gson;
public class Foo
{
static String jsonInput =
"{" +
"\"name\":\"John\"," +
"\"age\":\"20\"," +
"\"address\":\"some address\"," +
"\"someobject\":" +
"{" +
"\"field\":\"value\"" +
"}" +
"}";
String age;
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
Foo thing = gson.fromJson(jsonInput, Foo.class);
if (thing.age != null)
{
System.out.println("age is " + thing.age);
}
else
{
System.out.println("age element not present or value is null");
}
}
}
but the file i am getting from server after download it gives the size of 226 bytes
This is the size of a ZIP header. Apparently there is no data in the downloaded ZIP file. So, can you verify that the files to be added into the ZIP file are, indeed, there (relative to the path of the download PHP script)?
Consider adding a check on addFile
too:
foreach($file_names as $file)
{
$inputFile = $file_path . $file;
if (!file_exists($inputFile))
trigger_error("The input file $inputFile does not exist", E_USER_ERROR);
if (!is_readable($inputFile))
trigger_error("The input file $inputFile exists, but has wrong permissions or ownership", E_USER_ERROR);
if (!$zip->addFile($inputFile, $file))
trigger_error("Could not add $inputFile to ZIP file", E_USER_ERROR);
}
The observed behaviour is consistent with some problem (path error, permission problems, ...) preventing the files from being added to the ZIP file. On receiving an "empty" ZIP file, the client issues an error referring to the ZIP central directory missing (the actual error being that there is no directory, and no files).
I don't understand why the other friends tell you use HH
, But after I test so many time, The correct 24 hour format is :
hh
.
I see it from : http://www.malot.fr/bootstrap-datetimepicker/
I don't know why they don't use the common type HH
for 24 hour.....
I hope anyone could tell me if I'm wrong.....
Use option bty = "n"
in legend
to remove the box around the legend. For example:
legend(1, 5,
"This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
bty = "n")
This solves the problem:
df['newcolumn'] = df.A * df.B
You could also do:
def fab(row):
return row['A'] * row['B']
df['newcolumn'] = df.apply(fab, axis=1)
Key differences between Serializable
and Externalizable
Serializable
is marker interface without any methods. Externalizable
interface contains two methods: writeExternal()
and readExternal()
.Serializable
interface. Programmer defined Serialization process will be kicked-in for classes implementing Externalizable
interface.Externalizable
interface. You can support different versions of your object. If you implement Externalizable
, it's your responsibility to serialize super
classSerializable
uses reflection to construct object and does not require no arg constructor. But Externalizable
demands public no-arg constructor.Refer to blog by Hitesh Garg
for more details.
$("#message > span").text("your text");
or
$("#message").find("span").text("your text");
or
$("span","#message").text("your text");
or
$("#message > a.close-notify").siblings('span').text("your text");
If you are using Spring container and you want to initialize non-nullable bean field, lateinit
is better suited.
@Autowired
lateinit var myBean: MyBean
Facebook uses MQTT instead of HTTP. Push is better than polling. Through HTTP we need to poll the server continuously but via MQTT server pushes the message to clients.
Comparision between MQTT and HTTP: http://www.youtube.com/watch?v=-KNPXPmx88E
Note: my answers best fits for mobile devices.
Probably too late to comment but here's what I did when I ran into issues with setting php PATH for my XAMPP installation on Mac OSX
export PATH=/path/to/your/php/installation/bin:leave/rest/of/the/stuff/untouched/:$PATH
Explanation: Terminal / Mac tries to run a search on the PATHS it knows about, in a hope of finding the program, when user initiates a program from the "Terminal", hence the trick here is to make the terminal find the php, the user intends to, by pointing it to the user's version of PHP at some bin folder, installed by the user.
Worked for me :)
P.S I'm still a lost sheep around my new Computer ;)
Another scenario where this occurs is when you have a base class and one or more subclasses, where at least one of the subclasses introduce extra properties:
class Folder {
[key]
public string Id { get; set; }
public string Name { get; set; }
}
// Adds no props, but comes from a different view in the db to Folder:
class SomeKindOfFolder: Folder {
}
// Adds some props, but comes from a different view in the db to Folder:
class AnotherKindOfFolder: Folder {
public string FolderAttributes { get; set; }
}
If these are mapped in the DbContext
like below, the "'Invalid column name 'Discriminator'" error occurs when any type based on Folder
base type is accessed:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Folder>().ToTable("All_Folders");
modelBuilder.Entity<SomeKindOfFolder>().ToTable("Some_Kind_Of_Folders");
modelBuilder.Entity<AnotherKindOfFolder>().ToTable("Another_Kind_Of_Folders");
}
I found that to fix the issue, we extract the props of Folder
to a base class (which is not mapped in OnModelCreating()
) like so - OnModelCreating
should be unchanged:
class FolderBase {
[key]
public string Id { get; set; }
public string Name { get; set; }
}
class Folder: FolderBase {
}
class SomeKindOfFolder: FolderBase {
}
class AnotherKindOfFolder: FolderBase {
public string FolderAttributes { get; set; }
}
This eliminates the issue, but I don't know why!
I had to use vbLf only in an ASP script where the original data was POSTed from a PHP script on a cPanel box over to ASP on a win server
(VBScript)
EmailText = Replace(EmailText, vbLf, "<br>")
This is my implementation based on many answers above:
var activeRequest = false; //global var
var filters = {...};
apply_filters(filters);
//function triggering the ajax request
function apply_filters(filters){
//prepare data and other functionalities
var data = {};
//limit the ajax calls
if (activeRequest === false){
activeRequest = true;
}else{
//abort if another ajax call is pending
$request.abort();
//just to be sure the ajax didn't complete before and activeRequest it's already false
activeRequest = true;
}
$request = $.ajax({
url : window.location.origin + '/your-url.php',
data: data,
type:'POST',
beforeSend: function(){
$('#ajax-loader-custom').show();
$('#blur-on-loading').addClass('blur');
},
success:function(data_filters){
data_filters = $.parseJSON(data_filters);
if( data_filters.posts ) {
$(document).find('#multiple-products ul.products li:last-child').after(data_filters.posts).fadeIn();
}
else{
return;
}
$('#ajax-loader-custom').fadeOut();
},
complete: function() {
activeRequest = false;
}
});
}
Just compare the column with that value:
In [9]: df = pandas.DataFrame([1,2,3,4], columns=["data"])
In [10]: df
Out[10]:
data
0 1
1 2
2 3
3 4
In [11]: df["desired"] = df["data"] > 2.5
In [11]: df
Out[12]:
data desired
0 1 False
1 2 False
2 3 True
3 4 True
remove href
attribute:
<a id="" onclick="f1()">jhhghj</a>
if link styles are important then:
<a href="javascript:void(f1())">jhhghj</a>
You can use startInstrumentation
method of Activity
. You need implement empty Instrumentation
and pointed in manifest. After that you can call this method for restart your app. Like this:
try {
InstrumentationInfo info = getPackageManager().queryInstrumentation(getPackageName(), 0).get(0);
ComponentName component = new ComponentName(this, Class.forName(info.name));
startInstrumentation(component, null, null);
} catch (Throwable e) {
new RuntimeException("Failed restart with Instrumentation", e);
}
I get Instrumentation class name dynamically but you can hardcode it. Some like this:
try {
startInstrumentation(new ComponentName(this, RebootInstrumentation.class), null, null);
} catch (Throwable e) {
new RuntimeException("Failed restart with Instrumentation", e);
}
Call startInstrumentation
make reload of your app. Read description of this method. But it can be not safe if acting like kill app.
For Chrome on Android, you can use the -webkit-tap-highlight-color CSS property:
-webkit-tap-highlight-color is a non-standard CSS property that sets the color of the highlight that appears over a link while it's being tapped. The highlighting indicates to the user that their tap is being successfully recognized, and indicates which element they're tapping on.
To remove the highlighting completely, you can set the value to transparent
:
-webkit-tap-highlight-color: transparent;
Be aware that this might have consequences on accessibility: see outlinenone.com
Only text type
$(".form-edit-account :input[type=text]").attr("disabled", "disabled");
Only Password type
$(".form-edit-account :input[type=password]").attr("disabled", "disabled");
Only Email Type
$(".form-edit-account :input[type=email]").attr("disabled", "disabled");
The ISO file that suggested in the accepted answer is still not complete. The very complete offline installer is about 24GB! There is only one way to get it. follow these steps:
temp
folderC:\VS Community\
C:\VS
Community\
with this argument: /Layout .
Good Luck
Here's an efficient way of achieving the result with two caveats.
See sample test cases here.
123.12345678 ==> 123.123
1.230000 ==> 1.23
1.1 ==> 1.1
1 ==> 1.0
0.000 ==> 0.0
0.00 ==> 0.0
0.4 ==> 0.4
0 ==> 0.0
1.4999 ==> 1.499
1.4995 ==> 1.499
1.4994 ==> 1.499
Here's the code. The two caveats I mentioned above can be addressed pretty easily, however, speed mattered more to me than accuracy, so i left it here.
String manipulations like System.out.printf("%.2f",123.234);
are computationally costly compared to mathematical operations. In my tests, the below code (without the sysout) took 1/30th the time compared to String manipulations.
public double limitPrecision(String dblAsString, int maxDigitsAfterDecimal) {
int multiplier = (int) Math.pow(10, maxDigitsAfterDecimal);
double truncated = (double) ((long) ((Double.parseDouble(dblAsString)) * multiplier)) / multiplier;
System.out.println(dblAsString + " ==> " + truncated);
return truncated;
}
grant CREATE SESSION
Ref.. http://ss64.com/ora/grant.html
HTH,
Kent
I think the simplest way to just open a single database and start querying is:
sqlite> .open "test.db"
sqlite> SELECT * FROM table_name ... ;
Notice: This works only for versions 3.8.2+
In general you just have to define a slightly transparent color when creating the shape.
You can achieve that by setting the colors alpha channel.
#FF000000
will get you a solid black whereas #00000000
will get you a 100% transparent black (well it isn't black anymore obviously).
The color scheme is like this #AARRGGBB
there A stands for alpha channel, R stands for red, G for green and B for blue.
The same thing applies if you set the color in Java. There it will only look like 0xFF000000
.
UPDATE
In your case you'd have to add a solid
node. Like below.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shape_my">
<stroke android:width="4dp" android:color="#636161" />
<padding android:left="20dp"
android:top="20dp"
android:right="20dp"
android:bottom="20dp" />
<corners android:radius="24dp" />
<solid android:color="#88000000" />
</shape>
The color here is a half transparent black.
The only way to avoid exception handling is to use the GetNames() method, and we all know that exceptions shouldn't be abused for common application logic :)
I think you need quotes around your {$row['null_field']}
, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',)
which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
string.Concat(los.ToArray());
If you just want to concatenate the strings then use string.Concat() instead of string.Join().
I think the easiest way is checking for this condition:
$('.abc:checked').length == $('.abc').length
You could do it every time a new checkbox is checked:
$(".abc").change(function(){
if ($('.abc:checked').length == $('.abc').length) {
//do something
}
});
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), date, 112) + ' ' + CONVERT(CHAR(8), time, 108))
FROM tablename
If you want to format the JSON and also do some syntax highlighting, you can use the ng-prettyjson
directive. See the npm package.
Here is how to use it: <pre pretty-json="jsonObject"></pre>
Credentials do not work if API is not enabled. In my case the next steps were needed:
Another take based on John Skeet's answer that doesn't return the tags:
void Main()
{
XmlString("Brackets & stuff <> and \"quotes\"").Dump();
}
public string XmlString(string text)
{
return new XElement("t", text).LastNode.ToString();
}
This returns just the value passed in, in XML encoded format:
Brackets & stuff <> and "quotes"
Both handlers get called.
You may be thinking of inline event binding (eg "onclick=..."
), where a big drawback is only one handler may be set for an event.
jQuery conforms to the DOM Level 2 event registration model:
The DOM Event Model allows registration of multiple event listeners on a single EventTarget. To achieve this, event listeners are no longer stored as attribute values
http://www.program-transformation.org/Transform/VisualBasicDecompilers
This link provides a lot of resources for VB6 Decompiling, but it seems like it will depend greatly on what you DO have (do you still have the pre-link Object code [EDIT: er... p-code I mean], or just the EXE?) Either way, it looks like there's something, take a look in there.
Are you looking for a Windows API?
Just use SHGetFolderPath function with CSIDL_INTERNET_CACHE flag or SHGetKnownFolderPath with FOLDERID_InternetCache flag to get the exact location. This way you don't have to worry about the OS. The former function works in Windows XP. The latter one works in Windows Vista+.
For the ones that want to create a calculated column in a table to store the age:
CASE WHEN DateOfBirth< DATEADD(YEAR, (DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth))*-1, GETDATE())
THEN DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth)
ELSE DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth) -1 END
Steps to get sources of a jar file as a zip :
Download JD-GUI from http://java-decompiler.github.io/ and save it at any location on your system.
Drag and drop the jar or open .jar file for which you want the sources on the JD.
Java Decompiler will open with all the package structure in a tree format.
Click on File menu and select save jar sources. It will save the sources as a zip with the same name as the jar.
Example:-
We can use Eclipse IDE for Java EE Developers as well for update/extract code if require.
From eclipse chose Import Jar and then select jar which you need. Follow instruction as per image below
You can copy this to your eclipse.ini
file to have 1024M:
-clean -showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Xms512m
-Xmx1024m
-XX:PermSize=128m
-XX:MaxPermSize=256m
You can implement this very simply, here is an example:
<div ng-controller="MenuCtrl">
<ul class="menu">
<li ng-class="menuClass('home')"><a href="#home">Page1</a></li>
<li ng-class="menuClass('about')"><a href="#about">Page2</a></li>
</ul>
</div>
And your Controller should be this:
app.controller("MenuCtrl", function($scope, $location) {
$scope.menuClass = function(page) {
var current = $location.path().substring(1);
return page === current ? "active" : "";
};
});
var icon1 = "imageA.png";
var icon2 = "imageB.png";
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: icon1,
title: "some marker"
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
});
To turn off line numbering, again follow the preceding instructions, except this time enter the following line at the : prompt:
set nonumber
Won't you need to take the e
in e666.76
into account?
With
(e|0-9)\d*\d.\d{1,2)
Use a variable and call clearInterval
to stop it.
var interval;
$(document).on('ready',function()
interval = setInterval(updateDiv,3000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
// I want to stop it here
clearInterval(interval);
}
});
}
window.open('', '_self', '').close();
_x000D_
Sorry a bit late here, but i found the solution, at least for my case. Tested on Safari 11.0.3 and Google Chrome 64.0.3282.167
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
java.io.File
class contains four static separator variables. For better understanding, Let's understand with the help of some code
Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables. FileSeparator.java
import java.io.File;
public class FileSeparator {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :
Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
I think you are using chrome. The problem is the certificate mismatch or the expiration of the certificate.Check your certificate properly.
Just visit here for more information.
The normal way to plot plots with points in different colors in matplotlib is to pass a list of colors as a parameter.
E.g.:
import matplotlib.pyplot
matplotlib.pyplot.scatter([1,2,3],[4,5,6],color=['red','green','blue'])
When you have a list of lists and you want them colored per list. I think the most elegant way is that suggesyted by @DSM, just do a loop making multiple calls to scatter.
But if for some reason you wanted to do it with just one call, you can make a big list of colors, with a list comprehension and a bit of flooring division:
import matplotlib
import numpy as np
X = [1,2,3,4]
Ys = np.array([[4,8,12,16],
[1,4,9,16],
[17, 10, 13, 18],
[9, 10, 18, 11],
[4, 15, 17, 6],
[7, 10, 8, 7],
[9, 0, 10, 11],
[14, 1, 15, 5],
[8, 15, 9, 14],
[20, 7, 1, 5]])
nCols = len(X)
nRows = Ys.shape[0]
colors = matplotlib.cm.rainbow(np.linspace(0, 1, len(Ys)))
cs = [colors[i//len(X)] for i in range(len(Ys)*len(X))] #could be done with numpy's repmat
Xs=X*nRows #use list multiplication for repetition
matplotlib.pyplot.scatter(Xs,Ys.flatten(),color=cs)
cs = [array([ 0.5, 0. , 1. , 1. ]),
array([ 0.5, 0. , 1. , 1. ]),
array([ 0.5, 0. , 1. , 1. ]),
array([ 0.5, 0. , 1. , 1. ]),
array([ 0.28039216, 0.33815827, 0.98516223, 1. ]),
array([ 0.28039216, 0.33815827, 0.98516223, 1. ]),
array([ 0.28039216, 0.33815827, 0.98516223, 1. ]),
array([ 0.28039216, 0.33815827, 0.98516223, 1. ]),
...
array([ 1.00000000e+00, 1.22464680e-16, 6.12323400e-17,
1.00000000e+00]),
array([ 1.00000000e+00, 1.22464680e-16, 6.12323400e-17,
1.00000000e+00]),
array([ 1.00000000e+00, 1.22464680e-16, 6.12323400e-17,
1.00000000e+00]),
array([ 1.00000000e+00, 1.22464680e-16, 6.12323400e-17,
1.00000000e+00])]
Message queues are ideal for requests which may take a long time to process. Requests are queued and can be processed offline without blocking the client. If the client needs to be notified of completion, you can provide a way for the client to periodically check the status of the request.
Message queues also allow you to scale better across time. It improves your ability to handle bursts of heavy activity, because the actual processing can be distributed across time.
Note that message queues and web services are orthogonal concepts, i.e. they are not mutually exclusive. E.g. you can have a XML based web service which acts as an interface to a message queue. I think the distinction your looking for is Message Queues versus Request/Response, the latter is when the request is processed synchronously.
You can use a window MAX() like this:
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
to get max dates per group
alongside other data:
group date cash checks max_date
----- -------- ---- ------ --------
1 1/1/2013 0 0 1/3/2013
2 1/1/2013 0 800 1/1/2013
1 1/3/2013 0 700 1/3/2013
3 1/1/2013 0 600 1/5/2013
1 1/2/2013 0 400 1/3/2013
3 1/5/2013 0 200 1/5/2013
Using the above output as a derived table, you can then get only rows where date
matches max_date
:
SELECT
group,
date,
checks
FROM (
SELECT
*,
max_date = MAX(date) OVER (PARTITION BY group)
FROM table
) AS s
WHERE date = max_date
;
to get the desired result.
Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.
You can try the method at SQL Fiddle.
We use pdflib to create PDF files from our rails apps. It has bindings for PHP, and a ton of other languages.
We use the commmercial version, but they also have a free/open source version which has some limitations.
Unfortunately, this only allows creation of PDF's.
If you want to open and 'edit' existing files, pdflib do provide a product which does this this, but costs a LOT
SELECT DISTINCT * FROM MyFooTable;
If you group by all columns, you are just requesting that duplicate data be removed.
For example a table with the following data:
id | value
----+----------------
1 | foo
2 | bar
1 | foo
3 | something else
If you perform the following query which is essentially the same as SELECT * FROM MyFooTable GROUP BY *
if you are assuming * means all columns:
SELECT * FROM MyFooTable GROUP BY id, value;
id | value
----+----------------
1 | foo
3 | something else
2 | bar
It removes all duplicate values, which essentially makes it semantically identical to using the DISTINCT keyword with the exception of the ordering of results. For example:
SELECT DISTINCT * FROM MyFooTable;
id | value
----+----------------
1 | foo
2 | bar
3 | something else
Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.
Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; String Performance an Analysis
More:
Ajaxian >> String Performance in IE: Array.join vs += continued
Josh is correct but he left out one variation:
ALTER ROLE <role_name> IN DATABASE <db_name> SET search_path TO schema1,schema2;
Set the search path for the user, in one particular database.
Since the question got bumped I will go ahead and post my solution.
using (var finished = new CountdownEvent(1))
{
for (DataObject data in dataList)
{
finished.AddCount();
var localData = (DataObject)data.Clone();
var thread = new Thread(
delegate()
{
try
{
DoThreadStuff(localData);
threadFinish.Set();
}
finally
{
finished.Signal();
}
}
);
thread.Start();
}
finished.Signal();
finished.Wait(YOUR_TIMEOUT);
}
As an improvement on Peters code above you can use this:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (!roleManager.RoleExists("Member"))
roleManager.Create(new IdentityRole("Member"));
I think Citrix does that kind of thing. Though I'm not sure on specifics as I've only used it a couple of times. I think the one I used was called XenApp but I'm not sure if thats what you're after.
If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL
echo "foo";
echo PHP_EOL ;
echo "bar";
In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.
ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.
foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;
How you'd find a line break varies between operating system encodings. Windows would be \r\n
, but Linux just uses \n
and Apple uses \r
.
I found this in JavaScript line breaks:
someText = someText.replace(/(\r\n|\n|\r)/gm, "");
That should remove all kinds of line breaks.
you can get all product information from following code
$product_id=6//Suppose
$_product=Mage::getModel('catalog/product')->load($product_id);
$product_data["id"]=$_product->getId();
$product_data["name"]=$_product->getName();
$product_data["short_description"]=$_product->getShortDescription();
$product_data["description"]=$_product->getDescription();
$product_data["price"]=$_product->getPrice();
$product_data["special price"]=$_product->getFinalPrice();
$product_data["image"]=$_product->getThumbnailUrl();
$product_data["model"]=$_product->getSku();
$product_data["color"]=$_product->getAttributeText('color'); //get cusom attribute value
$storeId = Mage::app()->getStore()->getId();
$summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId) ->load($_product->getId());
$product_data["rating"]=($summaryData['rating_summary']*5)/100;
$product_data["shipping"]=Mage::getStoreConfig('carriers/flatrate/price');
if($_product->isSalable() ==1)
$product_data["in_stock"]=1;
else
$product_data["in_stock"]=0;
echo "<pre>";
print_r($product_data);
//echo "</pre>";
I took a list and used,
!MyList.Contains(table.columb.tostring())
Note: Make sure to use List and not Ilist
You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.
Just use dt.Clear()
Also you can set your TableAdapter/DataAdapter to clear before it fills with data.
You can get this with .BuiltInDocmementProperties
.
For example:
Public Sub PrintDocumentProperties()
Dim oApp As New Excel.Application
Dim oWB As Workbook
Set oWB = ActiveWorkbook
Dim title As String
title = oWB.BuiltinDocumentProperties("Title")
Dim lastauthor As String
lastauthor = oWB.BuiltinDocumentProperties("Last Author")
Debug.Print title
Debug.Print lastauthor
End Sub
See this page for all the fields you can access with this: http://msdn.microsoft.com/en-us/library/bb220896.aspx
If you're trying to do this outside of the client (i.e. with Excel closed and running code from, say, a .NET program), you need to use DSOFile.dll.
You can definitely do this. Basically:
class AsyncConstructor {
constructor() {
return (async () => {
// All async code here
this.value = await asyncFunction();
return this; // when done
})();
}
}
to create the class use:
let instance = await new AsyncConstructor();
This solution has a few short falls though:
super
note: If you need to usesuper
, you cannot call it within the async callback.
TypeScript note: this causes issues with TypeScript because the constructor returns type
Promise<MyClass>
instead ofMyClass
. There is no definitive way to resolve this that I know of. One potential way suggested by @blitter is to put/** @type {any} */
at the beginning of the constructor body— I do not know if this works in all situations however.
strings.Join()
from the "strings" package
If you have a type mismatch(like if you are trying to join an int and a string), you do RANDOMTYPE (thing you want to change)
EX:
package main
import (
"fmt"
"strings"
)
var intEX = 0
var stringEX = "hello all you "
var stringEX2 = "people in here"
func main() {
s := []string{stringEX, stringEX2}
fmt.Println(strings.Join(s, ""))
}
Output :
hello all you people in here
Johny the programmer needs a stapler, so he goes down to the office supply department and ask for one, after filling the request form he can either stand there and wait for the clerk go look around the warehouse for the stapler (like a blocking function call) or go do something else meantime.
since this usually takes time, johny puts a note together with the request form asking them to call him when the stapler is ready for pickup, so meantime he can go do something else like napping on his desk.
$spinTime: 3;
html, body { height: 100%; }
* { user-select: none; }
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: 'Raleway', sans-serif;
font-size: 72px;
input {
display: none;
+ div > span {
display: inline-block;
position: relative;
white-space: nowrap;
color: rgba(#fff, 0);
transition: all 0.5s ease-in-out;
span {
display: inline-block;
position: absolute;
left: 50%;
text-align: center;
color: rgba(#000, 1);
transform: translateX(-50%);
transform-origin: left;
transition: all 0.5s ease-in-out;
&:first-of-type {
transform: rotateY(0deg) translateX(-50%);
}
&:last-of-type {
transform: rotateY(0deg) translateX(0%) scaleX(0.75) skew(23deg,0deg);
}
}
}
&#fat:checked ~ div > span span {
&:first-of-type {
transform: rotateY(0deg) translateX(-50%);
}
&:last-of-type {
transform: rotateY(0deg) translateX(0%) scaleX(0.75) skew(23deg,0deg);
}
}
&#fit:checked ~ div > span {
margin: 0 -10px;
span {
&:first-of-type {
transform: rotateY(90deg) translateX(-50%);
}
&:last-of-type {
transform: rotateY(0deg) translateX(-50%) scaleX(1) skew(0deg,0deg);
}
}
}
+ div + div {
width: 280px;
margin-top: 10px;
label {
display: block;
padding: 20px 10px;
text-align: center;
transition: all 0.15s ease-in-out;
background: #fff;
border-radius: 10px;
box-sizing: border-box;
width: 48%;
font-size: 64px;
cursor: pointer;
&:first-child {
float: left;
box-shadow:
inset 0 0 0 4px #1597ff,
0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
}
&:last-child { float: right; }
}
}
&#fat:checked ~ div + div label {
&:first-child {
box-shadow:
inset 0 0 0 4px #1597ff,
0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
}
&:last-child {
box-shadow:
inset 0 0 0 0px #1597ff,
0 10px 15px -20px rgba(#1597ff, 0);
}
}
&#fit:checked ~ div + div label {
&:first-child {
box-shadow:
inset 0 0 0 0px #1597ff,
0 10px 15px -20px rgba(#1597ff, 0);
}
&:last-child {
box-shadow:
inset 0 0 0 4px #1597ff,
0 15px 15px -10px rgba(darken(#1597ff, 10%), 0.375);
}
}
}
}
<input type="radio" id="fat" name="fatfit">
<input type="radio" id="fit" name="fatfit">
<div>
GET F<span>A<span>A</span><span>I</span></span>T
</div>
<div>
<label for="fat"></label>
<label for="fit"></label>
</div>
How about this?
List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();
While Fosco's answer is not wrong there is a case to be considered with this one: mixed arrays. Imagine I have an array like this:
$a = array(
"nice",
"car" => "fast",
"none"
);
Now, PHP allows this kind of syntax but it has one problem: if I run Fosco's code I get 0
which is wrong for me, but why this happens?
Because when doing comparisons between strings and integers PHP converts strings to integers (and this is kinda stupid in my opinion), so when array_search()
searches for the index it stops at the first one because apparently ("car" == 0)
is true.
Setting array_search()
to strict mode won't solve the problem because then array_search("0", array_keys($a))
would return false even if an element with index 0 exists.
So my solution just converts all indexes from array_keys()
to strings and then compares them correctly:
echo array_search("car", array_map("strval", array_keys($a)));
Prints 1
, which is correct.
EDIT:
As Shaun pointed out in the comment below, the same thing applies to the index value, if you happen to search for an int index like this:
$a = array(
"foo" => "bar",
"nice",
"car" => "fast",
"none"
);
$ind = 0;
echo array_search($ind, array_map("strval", array_keys($a)));
You will always get 0
, which is wrong, so the solution would be to cast the index (if you use a variable) to a string like this:
$ind = 0;
echo array_search((string)$ind, array_map("strval", array_keys($a)));
By far the easiest way is by using TaskFactory.FromAsync from the TPL. It's literally a couple of lines of code when used in conjunction with the new async/await keywords:
var request = WebRequest.Create("http://www.stackoverflow.com");
var response = (HttpWebResponse) await Task.Factory
.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse,
null);
Debug.Assert(response.StatusCode == HttpStatusCode.OK);
If you can't use the C#5 compiler then the above can be accomplished using the Task.ContinueWith method:
Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,
request.EndGetResponse,
null)
.ContinueWith(task =>
{
var response = (HttpWebResponse) task.Result;
Debug.Assert(response.StatusCode == HttpStatusCode.OK);
});
$("#text").val(function(i,v) {
return v.replace(".", ":");
});
childClass::customMethod()
has different arguments, or a different access level (public/private/protected) than parentClass::customMethod()
.
It refers to the element in the DOM to which the onclick
attribute belongs:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
function func(e) {
$(e).text('there');
}
</script>
<a onclick="func(this)">here</a>
(This example uses jQuery.)
Quick note for Xamarin developers.
If you would like to call System.gc()
in Xamarin.Android apps you should call Java.Lang.JavaSystem.Gc()
@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
return jsonObject;
}
Here's the workflow I use all the time, using the keyboard only
Note that this doesn't work if there are blank lines in the selection.
Here's a list of all the ways I could think of to counting unique elements:
M = randi([1 7], [1500 1]);
t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);
counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );
counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);
[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);
counts5 = arrayfun( @(x)sum(M==x), unique(M) );
counts6 = sum( bsxfun(@eq, M, unique(M)') )';
counts7 = full(sparse(M,1,1));
enable -n echo
echo -n "Some string..."
I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".
However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.
I think thats not the reason everybody told above. There is something wrong in your code, maybe miss spelling or mismatching with the database column names. If mysqli query gets no result then it will return false, so that it is not a object - is a wrong idea. Everything works fine. it returns 1 or 0 if query have result or not.
So, my suggestion is check your variable names and table column names or any other misspelling.
This can be done in a single line, as long as the worksheet is active:
ActiveSheet.Visible = xlSheetHidden
However, you may not want to do this, especially if you use any "select" operations or you use any more ActiveSheet operations.
From Maven - Settings Reference
The repositories for download and deployment are defined by the repositories
and distributionManagement
elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
...
<servers>
<server>
<id>server001</id>
<username>my_login</username>
<password>my_password</password>
<privateKey>${user.home}/.ssh/id_dsa</privateKey>
<passphrase>some_passphrase</passphrase>
<filePermissions>664</filePermissions>
<directoryPermissions>775</directoryPermissions>
<configuration></configuration>
</server>
</servers>
...
</settings>
id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.
username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.
privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa
) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.
filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corrosponding to *nix file permissions, ie. 664, or 775.
Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.
All you should need is the id
, username
and password
The id
and URL
should be defined in your pom.xml
like this:
<repositories>
...
<repository>
<id>acme-nexus-releases</id>
<name>acme nexus</name>
<url>https://nexus.acme.net/content/repositories/releases</url>
</repository>
...
</repositories>
If you need a username and password to your server, you should encrypt it. Maven Password Encryption
You can now accomplish this in Chrome by right clicking on the object and selecting "Store as Global Variable": http://www.youtube.com/watch?v=qALFiTlVWdg
If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc
This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array
import numpy as np
from sklearn.metrics import auc
dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)
print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))
both output the same area: 4607.5
the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect
quite simple way: suppose you want import file with relative path ../../MyLibs/pyfunc.py
libPath = '../../MyLibs'
import sys
if not libPath in sys.path: sys.path.append(libPath)
import pyfunc as pf
But if you make it without a guard you can finally get a very long path
If you're using jQuery, you can also use:
$.getJSON(url, function(data) { });
Then you can do things like
data.key1.something
data.key1.something_else
etc.
If you need to get that in a program with Python on a Linux system for reproducibility:
with open('/proc/driver/nvidia/version') as f:
version = f.read().strip()
print(version)
gives:
NVRM version: NVIDIA UNIX x86_64 Kernel Module 384.90 Tue Sep 19 19:17:35 PDT 2017
GCC version: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)
SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices
The asterisk is just a repetition operator, but you need to tell it what you repeat. /*abc*/
matches a string containing ab and zero or more c's (because the second * is on the c; the first is meaningless because there's nothing for it to repeat). If you want to match anything, you need to say .*
-- the dot means any character (within certain guidelines). If you want to just match abc, you could just say grep 'abc' myFile
. For your more complex match, you need to use .*
-- grep 'abc.*def' myFile
will match a string that contains abc followed by def with something optionally in between.
Update based on a comment:
*
in a regular expression is not exactly the same as * in the console. In the console, * is part of a glob construct, and just acts as a wildcard (for instance ls *.log
will list all files that end in .log). However, in regular expressions, * is a modifier, meaning that it only applies to the character or group preceding it. If you want * in regular expressions to act as a wildcard, you need to use .*
as previously mentioned -- the dot is a wildcard character, and the star, when modifying the dot, means find one or more dot; ie. find one or more of any character.
I know that the question was for Java
. But I want to share a possible solution for Kotlin
because I think it is useful.
With Kotlin you can write an extension function which converts a JSONArray
into an native (Kotlin) array:
fun JSONArray.asArray(): Array<Any> {
return Array(this.length()) { this[it] }
}
Now you can call asArray()
directly on a JSONArray
instance.
I have figured out a solution to this problem. We can build a Function or View with "rendered" sql in a stored procedure that can then be executed as normal.
1.Create another sproc
CREATE PROCEDURE [dbo].[usp_FunctionBuilder]
DECLARE @outerSql VARCHAR(MAX)
DECLARE @innerSql VARCHAR(MAX)
2.Build the dynamic sql that you want to execute in your function (Example: you could use a loop and union, you could read in another sproc, use if statements and parameters for conditional sql, etc.)
SET @innerSql = 'your sql'
3.Wrap the @innerSql in a create function statement and define any external parameters that you have used in the @innerSql so they can be passed into the generated function.
SET @outerSql = 'CREATE FUNCTION [dbo].[fn_GeneratedFunction] ( @Param varchar(10))
RETURNS TABLE
AS
RETURN
' + @innerSql;
EXEC(@outerSql)
This is just pseudocode but the solution solves many problems such as linked server limitations, parameters, dynamic sql in function, dynamic server/database/table name, loops, etc.
You will need to tweak it to your needs, (Example: changing the return in the function)
Select the commit you would like to roll back to and reverse the changes by clicking Reverse File
, Reverse Hunk
or Reverse Selected Lines
. Do this for all the commits after the commit you would like to roll back to also.
Right click on the commit and click on Reset current branch to this commit
.
For Android Studio 3.1, select the icon below the Build one in the Build window.
By Android Studio 3.3 (possibly in 3.2.1), the icon has changed, though the location is the same:
The build window should open when you run a build action (e.g. from the Build menu). If you don't see it, you can try the "Build" button along the bottom of the window (also visible in the above screenshots), or through the menus View ? Tool Windows ? Build.
I'm not sure of the question, so here are two answers :
If you want to move your repository :
Simply copy the whole repository (with its .git
directory).
There is no absolute path in the .git
structure and nothing preventing it to be moved so you have nothing to do after the move. All the links to github (see in .git/config
) will work as before.
If you want to move files inside the repository :
Simply move the files. Then add the changes listed in git status
. The next commit
will do the necessary. You'll be happy to learn that no file will be duplicated : moving a file in git is almost costless.
We use something like this [use in one line]:
<a title="send to Facebook"
href="http://www.facebook.com/sharer.php?s=100&p[title]=YOUR_TITLE&p[summary]=YOUR_SUMMARY&p[url]=YOUR_URL&p[images][0]=YOUR_IMAGE_TO_SHARE_OBJECT"
target="_blank">
<span>
<img width="14" height="14" src="'icons/fb.gif" alt="Facebook" /> Facebook
</span>
</a>
Adding internal style is not good for SEO and Performance. I add an id to the div e.g. id="jumbocustom" and style it
#jumbocustom
{
background:red;
}
Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).
jQuery Cycle is one of my favourite light weight libraries.
What you want to achieve could be done in just
jQuery("#slideshow").cycle({
timeout:0, // no autoplay
fx: 'fade', //fade effect, although there are heaps
next: '#next',
prev: '#prev'
});
you can include maven dependency like below in your pom.xml file
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
Like Andrew said /exclude
parameter of xcopy should be existing file that has list of excludes.
Documentation of xcopy says:
Using /exclude
List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
Example:
xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
and list-of-excluded-files.txt
should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:
exclusion.txt
I think you're missing your routes, you need to define at least one route for example '/' to index.
e.g.
app.get('/', function (req, res) {
res.render('index', {});
});
You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".
Make sure to restart the SQL Server service.
Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.
I hope this might be helpful
<script type="text/javascript">_x000D_
function redirect() {_x000D_
document.getElementById("formid").submit();_x000D_
}_x000D_
window.onload = redirect;_x000D_
</script>
_x000D_
<form id="formid" method="post" action="anypage.jsp">_x000D_
........._x000D_
</form>
_x000D_
Use Array.pop:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
Just for the shake of completing the answer given by eipi10.
I was facing the same problem, without using scale_y_continuous
nor coord_cartesian
.
The conflict was coming from the x axis, where I defined limits = c(1, 30)
. It seems such limits do not provide enough space if you want to "dodge" your bars, so R still throws the error
Removed 8 rows containing missing values (geom_bar)
Adjusting the limits of the x axis to limits = c(0, 31)
solved the problem.
In conclusion, even if you are not putting limits to your y axis, check out your x axis' behavior to ensure you have enough space
If you are using Maven you may have both src/{main,test}/resources/META-INF/persistence.xml
. This is a common setup: test your JPA code with h2 or Derby and deploy it with PostgreSQL or some other full DBMS. If you're using this pattern, do make sure the two files have different unit names, else some versions of the Persistence
class will try to load BOTH (because of course your test-time CLASSPATH includes both classes and test-classes); this will cause conflicting definitions of the persistence unit, resulting in the dreaded annoying message that we all hate so much!
Worse: this may "work" with some older versions of e.g., Hibernate, but fail with current versions. Worth getting it right anyway...
If you don't want to install the cors library and instead want to fix your original code, the other step you are missing is that Access-Control-Allow-Origin:* is wrong. When passing Authentication tokens (e.g. JWT) then you must explicitly state every url that is calling your server. You can't use "*" when doing authentication tokens.
It should be like this :
<string name="game_settings_dragNDropMove_checkBox">Move by Drag&Drop</string>
I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar
.
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
See this example:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
Because doA()
does not modify the global total the output is 1 not 11.
As I mentioned here Purge Kafka Queue:
Tested in Kafka 0.8.2, for the quick-start example: First, Add one line to server.properties file under config folder:
delete.topic.enable=true
then, you can run this command:
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test
You can use the first selector.
var header = $('.header:first')
A small usage of np.nan ! = np.nan
s[s==s]
Out[953]:
0 1.0
1 2.0
2 3.0
3 4.0
5 5.0
dtype: float64
More Info
np.nan == np.nan
Out[954]: False
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_
you can use this function
var validateEmail = function (email) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
if (pattern.test(email)) {
return true;
}
else {
return false;
}
};
I'm not sure how necessary this is, and it adds a call to getElementById
, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:
<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>
And then in your JavaScript:
var size_of_widget = document.getElementById("metadata-size-of-widget").title;
With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:
Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:
my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )
# Iterate on the list:
for k in key_list:
print(key_list)
print(my_dic)
del( my_dic[k] )
print( my_dic )
# {}
I'll answer this question via Simple Javascript that is supported in all browsers that I have tested so far (IE8 to IE11, Chrome, FF etc).
Here is the code.
function GetFileSizeNameAndType()_x000D_
{_x000D_
var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE._x000D_
_x000D_
var totalFileSize = 0;_x000D_
_x000D_
// VALIDATE OR CHECK IF ANY FILE IS SELECTED._x000D_
if (fi.files.length > 0)_x000D_
{_x000D_
// RUN A LOOP TO CHECK EACH SELECTED FILE._x000D_
for (var i = 0; i <= fi.files.length - 1; i++)_x000D_
{_x000D_
//ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE_x000D_
var fsize = fi.files.item(i).size;_x000D_
totalFileSize = totalFileSize + fsize;_x000D_
document.getElementById('fp').innerHTML =_x000D_
document.getElementById('fp').innerHTML_x000D_
+_x000D_
'<br /> ' + 'File Name is <b>' + fi.files.item(i).name_x000D_
+_x000D_
'</b> and Size is <b>' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB_x000D_
+_x000D_
'</b> KB and File Type is <b>' + fi.files.item(i).type + "</b>.";_x000D_
}_x000D_
}_x000D_
document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";_x000D_
}
_x000D_
<p>_x000D_
<input type="file" id="file" multiple onchange="GetFileSizeNameAndType()" />_x000D_
</p>_x000D_
_x000D_
<div id="fp"></div>_x000D_
<p>_x000D_
<div id="divTotalSize"></div>_x000D_
</p>
_x000D_
*Please note that we are displaying filesize in KB (Kilobytes). To get in MB divide it by 1024 * 1024 and so on*.
You can you use subprocess
to achieve this.
import subprocess
#This command could have multiple commands separated by a new line \n
some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt"
p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
#This makes the wait possible
p_status = p.wait()
#This will give you the output of the command being executed
print "Command output: " + output
the solution was simple -
toDoublefunc = UserDefinedFunction(lambda x: float(x),DoubleType())
changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show']))
This is the answer.
<asp:TextBox id="yourtextBoxname" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
_x000D_
AutoCompleteType="Disabled"
If you still get the pre-filled boxes for example in the Firefox browser then its the browser's fault. You have to go
'Options' --> 'Security'(tab) --> Untick
'Remember password for sites and click on Saved Passwords button to delete any details that the browser has saved.
This should solve the problem
That's a known issue. Currently you have to use a workaround like shown in your question.
This is working as intended. When the change event is emitted ngModelChange
(the (...)
part of [(ngModel)]
hasn't updated the bound model yet:
<input type="checkbox" (ngModelChange)="myModel=$event" [ngModel]="mymodel">
See also
On Ubuntu it's Ctrl + Shift + I.
Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import
to Tkinter
rather than tkinter
(the difference being the capitalization):
import tkinter as tk
#import Tkinter as tk # for python 2
def create_window():
window = tk.Toplevel(root)
root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()
root.mainloop()
This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.
First the good news. This code does what you want (please note the "line numbers")
Sub a()
10: On Error GoTo ErrorHandler
20: DivisionByZero = 1 / 0
30: Exit Sub
ErrorHandler:
41: If Err.Number <> 0 Then
42: Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
43: MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
44: End If
50: Resume Next
60: End Sub
When it runs, the expected MsgBox is shown:
And now the bad news:
Line numbers are a residue of old versions of Basic. The programming environment usually took charge of inserting and updating them. In VBA and other "modern" versions, this functionality is lost.
However, Here there are several alternatives for "automatically" add line numbers, saving you the tedious task of typing them ... but all of them seem more or less cumbersome ... or commercial.
HTH!
Because you initialized the top
variable to -1
in your constructor, you need to increment the top
variable in your push()
method before you access the array. Note that I've changed the assignment to use ++top
:
public void push(int i)
{
if (top == stack.length)
{
extendStack();
}
stack[++top]= i;
}
That will fix the ArrayIndexOutOfBoundsException
you posted about. I can see other issues in your code, but since this is a homework assignment I'll leave those as "an exercise for the reader." :)
Select All Occurrences of Find Match editor.action.selectHighlights
.
Ctrl+Shift+L
Cmd+Shift+L or Cmd+Ctrl+G on Mac
Why don't you use a QSpinBox
for this purpose ? You can set the up/down buttons invisible with the following line of codes:
// ...
QSpinBox* spinBox = new QSpinBox( this );
spinBox->setButtonSymbols( QAbstractSpinBox::NoButtons ); // After this it looks just like a QLineEdit.
//...
The other answers are probably sufficient in most cases but I thought I'd add my two cents as I ran into a problem on a BusyBox system.
The system in question did not support the %N
format option and doesn't have no Python or Perl interpreter.
After much head scratching, we (thanks Dave!) came up with this:
adjtimex | awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }'
It extracts the seconds and microseconds from the output of adjtimex
(normally used to set options for the system clock) and prints them without new lines (so they get glued together). Note that the microseconds field has to be pre-padded with zeros, but this doesn't affect the seconds field which is longer than six digits anyway. From this it should be trivial to convert microseconds to milliseconds.
If you need a trailing new line (maybe because it looks better) then try
adjtimex | awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }' && printf "\n"
Also note that this requires adjtimex
and awk
to be available. If not then with BusyBox you can point to them locally with:
ln -s /bin/busybox ./adjtimex
ln -s /bin/busybox ./awk
And then call the above as
./adjtimex | ./awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }'
Or of course you could put them in your PATH
EDIT:
The above worked on my BusyBox device. On Ubuntu I tried the same thing and realised that adjtimex
has different versions. On Ubuntu this worked to output the time in seconds with decimal places to microseconds (including a trailing new line)
sudo apt-get install adjtimex
adjtimex -p | awk '/raw time:/ { print $6 }'
I wouldn't do this on Ubuntu though. I would use date +%s%N
check the link below, it has the html, css, JS and a live demo :) enjoy
http://codepen.io/senff/pen/ayGvD
// Create a clone of the menu, right next to original._x000D_
$('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();_x000D_
_x000D_
scrollIntervalID = setInterval(stickIt, 10);_x000D_
_x000D_
_x000D_
function stickIt() {_x000D_
_x000D_
var orgElementPos = $('.original').offset();_x000D_
orgElementTop = orgElementPos.top; _x000D_
_x000D_
if ($(window).scrollTop() >= (orgElementTop)) {_x000D_
// scrolled past the original position; now only show the cloned, sticky element._x000D_
_x000D_
// Cloned element should always have same left position and width as original element. _x000D_
orgElement = $('.original');_x000D_
coordsOrgElement = orgElement.offset();_x000D_
leftOrgElement = coordsOrgElement.left; _x000D_
widthOrgElement = orgElement.css('width');_x000D_
_x000D_
$('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement+'px').show();_x000D_
$('.original').css('visibility','hidden');_x000D_
} else {_x000D_
// not scrolled past the menu; only show the original menu._x000D_
$('.cloned').hide();_x000D_
$('.original').css('visibility','visible');_x000D_
}_x000D_
}
_x000D_
* {font-family:arial; margin:0; padding:0;}_x000D_
.logo {font-size:40px; font-weight:bold;color:#00a; font-style:italic;}_x000D_
.intro {color:#777; font-style:italic; margin:10px 0;}_x000D_
.menu {background:#00a; color:#fff; height:40px; line-height:40px;letter-spacing:1px; width:100%;}_x000D_
.content {margin-top:10px;}_x000D_
.menu-padding {padding-top:40px;}_x000D_
.content {padding:10px;}_x000D_
.content p {margin-bottom:20px;}
_x000D_
<div class="intro">Some tagline goes here</div>
_x000D_
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
I had the same problem with Entity Framework database first on all CLOB columns.
As a workaround, I filled the text values with spaces to be at least 4000 in width in insert operations (did not come with any better solution).
You can do it with few lines of CSS code. You can align all div's which you want to appear next to each other to right.
<div class="div_r">First Element</div>
<div class="div_r">Second Element</div>
<style>
.div_r{
float:right;
color:red;
}
</style>
I've also tried everything but finally I'm writing below code to make URL shorter:
var curURL = window.location.href;
history.replaceState(history.state, '', '/');
window.print();
history.replaceState(history.state, '', curURL);
But you need to make a custom PRINT button for user to click.
there is a simple procedure to do it go to controlpanel->system and security ->system->advanced system settings->advanced->environment variables
then add new path enter this in your variable path and values
This will print everything after each match, on that same line only:
perl -lne 'print $1 if /^potato:\s*(.*)/' file.txt
This will do the same, except it will also print all subsequent lines:
perl -lne 'if ($found){print} elsif (/^potato:\s*(.*)/){print $1; $found++}' file.txt
These command-line options are used:
-n
loop around each line of the input file-l
removes newlines before processing, and adds them back in afterwards -e
execute the perl code Not so much an answer as a cautionary tale: this was bugging me as well - and I thought I had a solution by pre-pending a zero and using the @(...)
syntax. i.e your code would have been:
var nonID = 0@(nonProID);
var proID = 0@(proID);
Getting output like:
var nonId = 0123;
What I didn't realise was that this is how JavaScript (version 3) represents octal/base-8 numbers and is actually altering the value. Additionally, if you are using the "use strict";
command then it will break your code entirely as octal numbers have been removed.
I'm still looking for a proper solution to this.
the simpler, the better.
index.php
<?
if (empty($_SERVER['QUERY_STRING'])) {
$name="index";
} else {
$name=basename($_SERVER['QUERY_STRING']);
}
$file="txt/".$name.".htm";
if (is_readable($file)) {
include 'header.php';
readfile($file);
} else {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
header.php
<a href="index.php">Main page</a><br>
<a href=?about>About</a><br>
<a href=?links>Links</a><br>
<br><br>
the actual static html pages stored in the txt
folder in the page
.htm format
You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScript
instead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.
part of manifest.json
"browser_action": {
"default_title": "Test",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="test">TEST!</button>
<script src="test.js"></script>
</body>
</html>
test.js
document.getElementById("test").addEventListener('click', () => {
console.log("Popup DOM fully loaded and parsed");
function modifyDOM() {
//You can play with your DOM here or check URL against your regex
console.log('Tab script:');
console.log(document.body);
return document.body.innerHTML;
}
//We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
}, (results) => {
//Here we have just the innerHTML and not DOM structure
console.log('Popup script:')
console.log(results[0]);
});
});
Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).
However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).
To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.
Loading the values in an array would be much faster:
Dim data(), dict As Object, r As Long
Set dict = CreateObject("Scripting.Dictionary")
data = ActiveSheet.UsedRange.Columns(1).Value
For r = 1 To UBound(data)
dict(data(r, some_column_number)) = Empty
Next
data = WorksheetFunction.Transpose(dict.keys())
You should also consider early binding for the Scripting.Dictionary:
Dim dict As New Scripting.Dictionary ' requires `Microsoft Scripting Runtime` '
Note that using a dictionary is way faster than Range.AdvancedFilter on large data sets.
As a bonus, here's a procedure similare to Range.RemoveDuplicates to remove duplicates from a 2D array:
Public Sub RemoveDuplicates(data, ParamArray columns())
Dim ret(), indexes(), ids(), r As Long, c As Long
Dim dict As New Scripting.Dictionary ' requires `Microsoft Scripting Runtime` '
If VarType(data) And vbArray Then Else Err.Raise 5, , "Argument data is not an array"
ReDim ids(LBound(columns) To UBound(columns))
For r = LBound(data) To UBound(data) ' each row '
For c = LBound(columns) To UBound(columns) ' each column '
ids(c) = data(r, columns(c)) ' build id for the row
Next
dict(Join$(ids, ChrW(-1))) = r ' associate the row index to the id '
Next
indexes = dict.Items()
ReDim ret(LBound(data) To LBound(data) + dict.Count - 1, LBound(data, 2) To UBound(data, 2))
For c = LBound(ret, 2) To UBound(ret, 2) ' each column '
For r = LBound(ret) To UBound(ret) ' each row / unique id '
ret(r, c) = data(indexes(r - 1), c) ' copy the value at index '
Next
Next
data = ret
End Sub
Just in case anybody else lands here from Google, I was bitten by this error message when using XDocument.Load(Stream) method.
XDocument xDoc = XDocument.Load(xmlStream);
Make sure the stream position is set to 0 (zero) before you try and load the Stream, its an easy mistake I always overlook!
if (xmlStream.Position > 0)
{
xmlStream.Position = 0;
}
XDocument xDoc = XDocument.Load(xmlStream);
Dim
simply declares the value and the type.
Set
assigns a value to the variable.
Something nobody has mentioned is that the DB guarantees atomic actions, transactional integrity and deals with concurrency. Even referentially integrity is out of the window with a filesystem - so how do you know your file names are really still correct?
If you have your images in a file-system and someone is reading the file as you're writing a new version or even deleting the file - what happens?
We use blobs because they're easier to manage (backup, replication, transfer) too. They work well for us.
Three steps needed:
Explicitly mark SSL2.0, TLS1.0, TLS1.1 as forbidden on your server machine, by adding Enabled=0
and DisabledByDefault=1
to your registry (the full path is HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols
). See screen for details
Explicitly enable TLS1.2
by following the steps from 1. Just use Enabled=1
and DisabledByDefault=0
respectively.
NOTE: verify server version: Windows Server 2003
does not support the TLS 1.2
protocol
Enable TLS1.2
only on app level, like @John Wu suggested above.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Hope this guide helps.
UPDATE As @Subbu mentioned: Official guide
I would do it in the Initialize event of the controller like this...
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
const string culture = "en-US";
CultureInfo ci = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
There are two commands which will work in this situation,
root>git reset --hard HEAD~1
root>git push -f
For more git commands refer this page
There are available Extension methods to parse them into other primitive types.
"10".toInt()
"10".toLong()
"true".toBoolean()
"10.0".toFloat()
"10.0".toDouble()
"10".toByte()
"10".toShort()
String num = "10";
Integer.parseInt(num );
The Uri.parse(extras.getString("imageUri"))
was causing an error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.putExtra(java.lang.String, android.os.Parcelable)' on a null object reference
So I changed to the following:
intent.putExtra("imageUri", imageUri)
and
Uri uri = (Uri) getIntent().get("imageUri");
This solved the problem.
you can set the opacity by the last parameter of rgb
function.
the opacity is 0.5
in the example
.modal-backdrop {
background-color: rgb(0, 0, 0, 0.5);
}
if (vi_video[0].exitFullScreen) vi_video[0].exitFullScreen();
else if (vi_video[0].webkitExitFullScreen) vi_video[0].webkitExitFullScreen();
else if (vi_video[0].mozExitFullScreen) vi_video[0].mozExitFullScreen();
else if (vi_video[0].oExitFullScreen) vi_video[0].oExitFullScreen();
else if (vi_video[0].msExitFullScreen) vi_video[0].msExitFullScreen();
else { vi_video.parent().append(vi_video.remove()); }
It seems to complain about \x08
you will need to escape that.
Edit:
Or you can have the parser ignore the errors using recover
from lxml import etree
parser = etree.XMLParser(recover=True)
etree.fromstring(xmlstring, parser=parser)
FOR MAC USERS if you are working with open cv
import cv2
cv2.imwrite('path_to_folder/image.jpg',image)
In Workbench 6.3 it is supereasy:
In the web a stateful protocol is based on having a temporary token that is exchanged between a browser and a server (via cookie header or URI rewriting) on every request. That token is usually created on the server end, and it is a piece of opaque data that has a certain time-to-live, and it has the sole purpose of identifying a specific web user agent. That is, the token is temporary, and becomes a STATE that the web server has to maintain on behalf of a client user agent during the duration of that conversation. Therefore, the communication using a token in this way is STATEFUL. And if the conversation between client and server is STATEFUL it is not RESTful.
The username/password (sent on the Authorization header) is usually persisted on the database with the intent of identifying a user. Sometimes the user could mean another application; however, the username/password is NEVER intended to identify a specific web client user agent. The conversation between a web agent and server based on using the username/password in the Authorization header (following the HTTP Basic Authorization) is STATELESS because the web server front-end is not creating or maintaining any STATE information whatsoever on behalf of a specific web client user agent. And based on my understanding of REST, the protocol states clearly that the conversation between clients and server should be STATELESS. Therefore, if we want to have a true RESTful service we should use username/password (Refer to RFC mentioned in my previous post) in the Authorization header for every single call, NOT a sension kind of token (e.g. Session tokens created in web servers, OAuth tokens created in authorization servers, and so on).
I understand that several called REST providers are using tokens like OAuth1 or OAuth2 accept-tokens to be be passed as "Authorization: Bearer " in HTTP headers. However, it appears to me that using those tokens for RESTful services would violate the true STATELESS meaning that REST embraces; because those tokens are temporary piece of data created/maintained on the server side to identify a specific web client user agent for the valid duration of a that web client/server conversation. Therefore, any service that is using those OAuth1/2 tokens should not be called REST if we want to stick to the TRUE meaning of a STATELESS protocol.
Rubens
Update - I verified the below works. Maybe the creation of your JArray isn't quite right.
[TestMethod]
public void TestJson()
{
var jsonString = @"{""trends"": [
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
},
{
""name"": ""#HNCJ"",
""url"": ""http://twitter.com/search?q=%23HNCJ"",
""promoted_content"": null,
""query"": ""%23HNCJ"",
""events"": null
},
{
""name"": ""Boston"",
""url"": ""http://twitter.com/search?q=Boston"",
""promoted_content"": null,
""query"": ""Boston"",
""events"": null
},
{
""name"": ""#prayforboston"",
""url"": ""http://twitter.com/search?q=%23prayforboston"",
""promoted_content"": null,
""query"": ""%23prayforboston"",
""events"": null
},
{
""name"": ""#TheMrsCarterShow"",
""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
""promoted_content"": null,
""query"": ""%23TheMrsCarterShow"",
""events"": null
},
{
""name"": ""#Raw"",
""url"": ""http://twitter.com/search?q=%23Raw"",
""promoted_content"": null,
""query"": ""%23Raw"",
""events"": null
},
{
""name"": ""Iran"",
""url"": ""http://twitter.com/search?q=Iran"",
""promoted_content"": null,
""query"": ""Iran"",
""events"": null
},
{
""name"": ""#gaa"",
""url"": ""http://twitter.com/search?q=%23gaa"",
""promoted_content"": null,
""query"": ""gaa"",
""events"": null
},
{
""name"": ""Facebook"",
""url"": ""http://twitter.com/search?q=Facebook"",
""promoted_content"": null,
""query"": ""Facebook"",
""events"": null
}]}";
var twitterObject = JToken.Parse(jsonString);
var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;
foreach (var item in trendsArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
}
So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.
foreach(var item in yourJArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
fade the other in in the callback of fadeout, which runs when fadeout is done. Using your code:
$('#two, #three').hide();
$('.slide').click(function(){
var $this = $(this);
$this.fadeOut(function(){ $this.next().fadeIn(); });
});
alternatively, you can just "pause" the chain, but you need to specify for how long:
$(this).fadeOut().next().delay(500).fadeIn();
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
Some versions of Android support custom Activity
transitions and some don't (older devices). If you want to use custom transitions it's good practice to check whether the Activity
has the overridePendingTransition()
method, as on older versions it does not.
To know whether the method exists or not, reflection API can be used. Here is the simple code which will check and return the method if it exists:
Method mOverridePendingTransition;
try {
mOverridePendingTransition = Activity.class.getMethod(
"overridePendingTransition", new Class[] { Integer.TYPE, Integer.TYPE } );
/* success */
} catch (NoSuchMethodException nsme) {
/* failure, this version of Android doesn't have this method */
}
And then, we can apply our own transition, i.e. use this method if it exists:
if (UIConstants.mOverridePendingTransition != null) {
try {
UIConstants.mOverridePendingTransition.invoke(MainActivity.this, R.anim.activity_fade_in, R.anim.activity_fade_out);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Here, as an example, simple fade-in and fade-out animations were used for transition demonstration..
It can work for all kind of layout.
android:windowSoftInputMode="adjustResize"
for example:
<activity android:name=".ActivityLogin"
android:screenOrientation="portrait"
android:theme="@style/AppThemeTransparent"
android:windowSoftInputMode="adjustResize"/>
android:fitsSystemWindows="true"
and
android:layout_alignParentBottom="true"
for example:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:fitsSystemWindows="true">
Unicode is not equal to UTF-8. The latter is just an encoding for the former.
You are doing it the wrong way around. You are reading UTF-8-encoded data, so you have to decode the UTF-8-encoded String into a unicode string.
So just replace .encode
with .decode
, and it should work (if your .csv is UTF-8-encoded).
Nothing to be ashamed of, though. I bet 3 in 5 programmers had trouble at first understanding this, if not more ;)
Update:
If your input data is not UTF-8 encoded, then you have to .decode()
with the appropriate encoding, of course. If nothing is given, python assumes ASCII, which obviously fails on non-ASCII-characters.
If there is no bulk insert into mongodb, we loop all objects in the small_collection
and insert them one by one into the big_collection
:
db.small_collection.find().forEach(function(obj){
db.big_collection.insert(obj)
});
Here is an example using ng-messages (available in angular 1.3) and a custom directive.
Validation message is displayed on blur for the first time user leaves the input field, but when he corrects the value, validation message is removed immediately (not on blur anymore).
JavaScript
myApp.directive("validateOnBlur", [function() {
var ddo = {
restrict: "A",
require: "ngModel",
scope: {},
link: function(scope, element, attrs, modelCtrl) {
element.on('blur', function () {
modelCtrl.$showValidationMessage = modelCtrl.$dirty;
scope.$apply();
});
}
};
return ddo;
}]);
HTML
<form name="person">
<input type="text" ng-model="item.firstName" name="firstName"
ng-minlength="3" ng-maxlength="20" validate-on-blur required />
<div ng-show="person.firstName.$showValidationMessage" ng-messages="person.firstName.$error">
<span ng-message="required">name is required</span>
<span ng-message="minlength">name is too short</span>
<span ng-message="maxlength">name is too long</span>
</div>
</form>
PS. Don't forget to download and include ngMessages in your module:
var myApp = angular.module('myApp', ['ngMessages']);
Wunderbart's post worked for me combined with statler's improvements. Adding a few more comments and syntax cleanup, and also passing back the orientation value and I have the following code feel free to use. Just call readImageFile()
function below and you get back the transformed image and the original orientation.
const JpegOrientation = [
"NOT_JPEG",
"NORMAL",
"FLIP-HORIZ",
"ROT180",
"FLIP-HORIZ-ROT180",
"FLIP-HORIZ-ROT270",
"ROT270",
"FLIP-HORIZ-ROT90",
"ROT90"
];
//Provided a image file, determines the orientation of the file based on the EXIF information.
//Calls the "callback" function with an index into the JpegOrientation array.
//If the image is not a JPEG, returns 0. If the orientation value cannot be read (corrupted file?) return -1.
function getOrientation(file, callback) {
const reader = new FileReader();
reader.onload = (e) => {
const view = new DataView(e.target.result);
if (view.getUint16(0, false) !== 0xFFD8) {
return callback(0); //NOT A JPEG FILE
}
const length = view.byteLength;
let offset = 2;
while (offset < length) {
if (view.getUint16(offset+2, false) <= 8) //unknown?
return callback(-1);
const marker = view.getUint16(offset, false);
offset += 2;
if (marker === 0xFFE1) {
if (view.getUint32(offset += 2, false) !== 0x45786966)
return callback(-1); //unknown?
const little = view.getUint16(offset += 6, false) === 0x4949;
offset += view.getUint32(offset + 4, little);
const tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++) {
if (view.getUint16(offset + (i * 12), little) === 0x0112) {
return callback(view.getUint16(offset + (i * 12) + 8, little)); //found orientation code
}
}
}
else if ((marker & 0xFF00) !== 0xFF00) {
break;
}
else {
offset += view.getUint16(offset, false);
}
}
return callback(-1); //unknown?
};
reader.readAsArrayBuffer(file);
}
//Takes a jpeg image file as base64 and transforms it back to original, providing the
//transformed image in callback. If the image is not a jpeg or is already in normal orientation,
//just calls the callback directly with the source.
//Set type to the desired output type if transformed, default is image/jpeg for speed.
function resetOrientation(srcBase64, srcOrientation, callback, type = "image/jpeg") {
if (srcOrientation <= 1) { //no transform needed
callback(srcBase64);
return;
}
const img = new Image();
img.onload = () => {
const width = img.width;
const height = img.height;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < srcOrientation && srcOrientation < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (srcOrientation) {
//case 1: normal, no transform needed
case 2:
ctx.transform(-1, 0, 0, 1, width, 0);
break;
case 3:
ctx.transform(-1, 0, 0, -1, width, height);
break;
case 4:
ctx.transform(1, 0, 0, -1, 0, height);
break;
case 5:
ctx.transform(0, 1, 1, 0, 0, 0);
break;
case 6:
ctx.transform(0, 1, -1, 0, height, 0);
break;
case 7:
ctx.transform(0, -1, -1, 0, height, width);
break;
case 8:
ctx.transform(0, -1, 1, 0, 0, width);
break;
default:
break;
}
// draw image
ctx.drawImage(img, 0, 0);
//export base64
callback(canvas.toDataURL(type), srcOrientation);
};
img.src = srcBase64;
};
//Read an image file, providing the returned data to callback. If the image is jpeg
//and is transformed according to EXIF info, transform it first.
//The callback function receives the image data and the orientation value (index into JpegOrientation)
export function readImageFile(file, callback) {
getOrientation(file, (orientation) => {
console.log("Read file \"" + file.name + "\" with orientation: " + JpegOrientation[orientation]);
const reader = new FileReader();
reader.onload = () => { //when reading complete
const img = reader.result;
resetOrientation(img, orientation, callback);
};
reader.readAsDataURL(file); //start read
});
}
For those who just need to save some int
value in the resources, you can do the following.
integers.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="default_value">100</integer>
</resources>
Code
int defaultValue = getResources().getInteger(R.integer.default_value);
Not without writing your own class loader. You can add jars to the jar's classpath, but they must be co-located, not contained in the main jar.
You're loosing your height attribute because you're changing the block element to inline (it's now going to act like a <p>
). You're probably picking up that 14px height because of the text height inside your in-line div.
Inline-block may work for your needs, but you may have to implement a work around or two for cross-browser support.
IE supports inline-block, but only for elements that are natively inline.
If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.
web.config
file of your application.web.config
file.Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…