Form correlation matrix, in my case zdf is the dataframe which i need perform correlation matrix.
corrMatrix =zdf.corr()
corrMatrix.to_csv('sm_zscaled_correlation_matrix.csv');
html = corrMatrix.style.background_gradient(cmap='RdBu').set_precision(2).render()
# Writing the output to a html file.
with open('test.html', 'w') as f:
print('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-widthinitial-scale=1.0"><title>Document</title></head><style>table{word-break: break-all;}</style><body>' + html+'</body></html>', file=f)
Then we can take screenshot. or convert html to an image file.
Your rows
object holds an Item
attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString()
on the row.
You should access each column from the row separately, use a for
or a foreach
to walk the array of columns.
Here, take a look at the class:
http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx
Since it was a successful comment, I am adding it as an answer:
with files:
find . | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"
I think I found the answer in my kernel source documentation: /usr/src/linux-2.6.37-rc3/Documentation/filesystems/proc.txt
1.7 TTY info in /proc/tty
-------------------------
Information about the available and actually used tty's can be found in the
directory /proc/tty.You'll find entries for drivers and line disciplines in
this directory, as shown in Table 1-11.
Table 1-11: Files in /proc/tty
..............................................................................
File Content
drivers list of drivers and their usage
ldiscs registered line disciplines
driver/serial usage statistic and status of single tty lines
..............................................................................
To see which tty's are currently in use, you can simply look into the file
/proc/tty/drivers:
> cat /proc/tty/drivers
pty_slave /dev/pts 136 0-255 pty:slave
pty_master /dev/ptm 128 0-255 pty:master
pty_slave /dev/ttyp 3 0-255 pty:slave
pty_master /dev/pty 2 0-255 pty:master
serial /dev/cua 5 64-67 serial:callout
serial /dev/ttyS 4 64-67 serial
/dev/tty0 /dev/tty0 4 0 system:vtmaster
/dev/ptmx /dev/ptmx 5 2 system
/dev/console /dev/console 5 1 system:console
/dev/tty /dev/tty 5 0 system:/dev/tty
unknown /dev/tty 4 1-63 console
Here is a link to this file: http://git.kernel.org/?p=linux/kernel/git/next/linux-next.git;a=blob_plain;f=Documentation/filesystems/proc.txt;hb=e8883f8057c0f7c9950fa9f20568f37bfa62f34a
I think all the previous answers are wrong, as they state that dereferencing means accessing the actual value. Wikipedia gives the correct definition instead: https://en.wikipedia.org/wiki/Dereference_operator
It operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer.
That said, we can dereference the pointer without ever accessing the value it points to. For example:
char *p = NULL;
*p;
We dereferenced the NULL pointer without accessing its value. Or we could do:
p1 = &(*p);
sz = sizeof(*p);
Again, dereferencing, but never accessing the value. Such code will NOT crash: The crash happens when you actually access the data by an invalid pointer. However, unfortunately, according the the standard, dereferencing an invalid pointer is an undefined behaviour (with a few exceptions), even if you don't try to touch the actual data.
So in short: dereferencing the pointer means applying the dereference operator to it. That operator just returns an l-value for your future use.
For anyone of you who wants the image to fit exact the imageview with proper scaling and no cropping use
imageView.setScaleType(ScaleType.FIT_XY);
where imageView is the view representing your ImageView
There is another library called arrow
really great to make manipulation on python date.
import arrow
import datetime
a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True
mysql allows you to insert multiple rows at once INSERT manual
Im pretty confident that the application you found actually gets their information form Themoviedb.org's API(they get most of there stuff from IMDB). They have a free open API that is used alot of the movie organizer/XMBC applications.
I know this is late, but this is how I normally do it,
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");
The link you gave seems to be attempting something different to the test you are trying to avoid repeating.
if (a == null || a=='')
tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).
The test you described can be replaced by:
if (!a)
Because in javascript, an empty string, and null, both evaluate to false in a boolean context.
I have to struggle to find how to achieve especial those who are new to this tool (like me)
C# code:
IWebElement ddl = ffDriver.FindElement(By.Id("ddlGoTo"));
OpenQA.Selenium.Support.UI.SelectElement clickthis = new OpenQA.Selenium.Support.UI.SelectElement(ddl);
clickthis.SelectByText("Your Text");
hope this help others!
I use Remote login with vnc-ltsp-config with GNOME Desktop Environment on CentOS 5.9. From experimenting today, I managed to get cut and paste working for the session and the login prompt (because I'm lazy and would rather copy and paste difficult passwords).
I created a file vncconfig.desktop in the /etc/xdg/autostart directory which enabled cut and paste during the session after login. The vncconfig process is run as the logged in user.
[Desktop Entry]
Name=No name
Encoding=UTF-8
Version=1.0
Exec=vncconfig -nowin
X-GNOME-Autostart-enabled=true
Added vncconfig -nowin & to the bottom of the file /etc/gdm/Init/Desktop which enabled cut and paste in the session during login but terminates after login. The vncconfig process is run as root.
Adding vncconfig -nowin & to the bottom of the file /etc/gdm/PostLogin/Desktop also enabled cut and paste during the session after login. The vncconfig process is run as root however.
That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.
This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.
Hope that helps...
The substitute of fcntl
on windows are win32api
calls. The usage is completely different. It is not some switch you can just flip.
In other words, porting a fcntl
-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl
call does and then find the equivalent win32api
code, if any.
There's also the possibility that some code using fcntl
has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.
If you provide more details about the fcntl
calls people can find windows equivalents.
git rebase -i master
you will get the editor vm open and msgs something like this
Pick 2994283490 commit msg1
f 7994283490 commit msg2
f 4654283490 commit msg3
f 5694283490 commit msg4
#Some message
#
#some more
Here I have changed pick for all the other commits to "f" (Stands for fixup).
git push -f origin feature/feature-branch-name-xyz
this will fixup all the commits to one commit and will remove all the other commits . I did this and it helped me.
You need to use an id selector:
//show
$('#passwordsNoMatchRegister').show();
//hide
$('#passwordsNoMatchRegister').hide();
#
is an id selector and passwordsNoMatchRegister
is the id of the div.
In new version of jquery, could done it via following steps:
serializeArray()
push()
or similar methods to add additional params to the array,$.param(arr)
to get serialized string, which could be used as jquery ajax's data
param.Example code:
var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
// ...
}
For Swift 3, many Foundation
types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString
.
I feel this is easier to understand
[row[i] for row in a for i in range(len(a))]
result: [1, 2, 3, 4]
There are a couple of good solutions here.
Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:
# Change this code:
facet_grid(.~size) +
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))
This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.
The RFC for HTTP (as cited above) dictates that the headers are case-insensitive, however you will find that with certain browsers (I'm looking at you, IE) that capitalizing each of the words tends to be best:
Location: http://stackoverflow.com
Content-Type: text/plain
vs
location: http://stackoverflow.com
content-type: text/plain
This isn't "HTTP" standard, but just another one of the browser quirks, we as developers, have to think about.
There are two options:
A: You care about retaining array order:
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
B: You don't care about retaining order (this is probably faster):
a[i] = a[len(a)-1] // Replace it with the last one. CAREFUL only works if you have enough elements.
a = a[:len(a)-1] // Chop off the last one.
See the link to see implications re memory leaks if your array is of pointers.
The WebSocket connection starts its life with an HTTP or HTTPS handshake. When the page is accessed through HTTP, you can use WS or WSS (WebSocket secure: WS over TLS) . However, when your page is loaded through HTTPS, you can only use WSS - browsers don't allow to "downgrade" security.
public static void main(String[] args) throws IOException {
String filePath = "/Users/myXml/VH181.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
printElement(doc);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException e1) {
e1.printStackTrace();
}
}
private static void printElement(Document someNode) {
NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
for(int z=0,size= nodeList.getLength();z<size; z++) {
String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
System.out.println("Choice Interaction Id:"+Value);
}
}
we Can try this code using method
I love the Try
pattern. It's a tidy pattern.
if (double.TryParse(name, out var result))
{
// handle success
}
else
{
// handle error
}
But, it's challenging with async
. That doesn't mean we don't have real options. Here are the three core approaches you can consider for async
methods in a quasi-version of the Try
pattern.
This looks most like a sync Try
method only returning a tuple
instead of a bool
with an out
parameter, which we all know is not permitted in C#.
var result = await DoAsync(name);
if (result.Success)
{
// handle success
}
else
{
// handle error
}
With a method that returns true
of false
and never throws an exception
.
Remember, throwing an exception in a
Try
method breaks the whole purpose of the pattern.
async Task<(bool Success, StorageFile File, Exception exception)> DoAsync(string fileName)
{
try
{
var folder = ApplicationData.Current.LocalCacheFolder;
return (true, await folder.GetFileAsync(fileName), null);
}
catch (Exception exception)
{
return (false, null, exception);
}
}
We can use anonymous
methods to set external variables. It's clever syntax, though slightly complicated. In small doses, it's fine.
var file = default(StorageFile);
var exception = default(Exception);
if (await DoAsync(name, x => file = x, x => exception = x))
{
// handle success
}
else
{
// handle failure
}
The method obeys the basics of the Try
pattern but sets out
parameters to passed in callback methods. It's done like this.
async Task<bool> DoAsync(string fileName, Action<StorageFile> file, Action<Exception> error)
{
try
{
var folder = ApplicationData.Current.LocalCacheFolder;
file?.Invoke(await folder.GetFileAsync(fileName));
return true;
}
catch (Exception exception)
{
error?.Invoke(exception);
return false;
}
}
There's a question in my mind about performance here. But, the C# compiler is so freaking smart, that I think you're safe choosing this option, almost for sure.
What if you just use the TPL
as designed? No tuples. The idea here is that we use exceptions to redirect ContinueWith
to two different paths.
await DoAsync(name).ContinueWith(task =>
{
if (task.Exception != null)
{
// handle fail
}
if (task.Result is StorageFile sf)
{
// handle success
}
});
With a method that throws an exception
when there is any kind of failure. That's different than returning a boolean
. It's a way to communicate with the TPL
.
async Task<StorageFile> DoAsync(string fileName)
{
var folder = ApplicationData.Current.LocalCacheFolder;
return await folder.GetFileAsync(fileName);
}
In the code above, if the file is not found, an exception is thrown. This will invoke the failure ContinueWith
that will handle Task.Exception
in its logic block. Neat, huh?
Listen, there's a reason we love the
Try
pattern. It's fundamentally so neat and readable and, as a result, maintainable. As you choose your approach, watchdog for readability. Remember the next developer who in 6 months and doesn't have you to answer clarifying questions. Your code can be the only documentation a developer will ever have.
Best of luck.
You can try putting a new line in the data:
<data>Foo bar baz
baz bar</data>
If that does not work you might need to parse the string manually.
If you need direct XAML that's easy by the way:
<TextBlock>
Lorem <LineBreak/>
Ipsum
</TextBlock>
you can use below methods
public static String parseUrl(String surl) throws Exception
{
URL u = new URL(surl);
return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}
or
public String parseURL(String url, Map<String, String> params)
{
Builder builder = Uri.parse(url).buildUpon();
for (String key : params.keySet())
{
builder.appendQueryParameter(key, params.get(key));
}
return builder.build().toString();
}
the second one is better than first.
just use printf
instead of
repo forall -c '....$variable'
use printf to replace the variable token with the expanded variable.
For example:
template='.... %s'
repo forall -c $(printf "${template}" "${variable}")
If you run a script directly e.g., ./xx.py
and your script has no shebang such as #!/usr/bin/env python
at the very top then your shell may execute it as a shell script. POSIX says:
If the execl() function fails due to an error equivalent to the [ENOEXEC] error defined in the System Interfaces volume of POSIX.1-2008, the shell shall execute a command equivalent to having a shell invoked with the pathname resulting from the search as its first operand, with any remaining arguments passed to the new shell, except that the value of "$0" in the new shell may be set to the command name. If the executable file is not a text file, the shell may bypass this command execution. In this case, it shall write an error message, and shall return an exit status of 126.
Note: you may get ENOEXEC
if your text file has no shebang.
Without the shebang, you shell tries to run your Python script as a shell script that leads to the error: import: command not found
.
Also, if you run your script as python xx.py
then you do not need the shebang. You don't even need it to be executable (+x
). Your script is interpreted by python
in this case.
On Windows, shebang is not used unless pylauncher is installed. It is included in Python 3.3+.
Threads share the code and data segments and the heap, but they don't share the stack.
Another forum provided this answer:
Ahh, figured this out. The following system properties need to be set, so that the "logging.properties" file can be picked up.
Assuming that the tomcat is located under an Eclipse project, add the following under the "Arguments" tab of its launch configuration:
-Dcatalina.base="${project_loc}\<apache-tomcat-5.5.23_loc>"
-Dcatalina.home="${project_loc}\<apache-tomcat-5.5.23_loc>"
-Djava.util.logging.config.file="${project_loc}\<apache-tomcat-5.5.23_loc>\conf\logging.properties"
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
http://www.coderanch.com/t/442412/Tomcat/Tweaking-tomcat-logging-properties-file
As of python 3.5+:
@functools.wraps(f)
def g():
pass
Is an alias for g = functools.update_wrapper(g, f)
. It does exactly three things:
__module__
, __name__
, __qualname__
, __doc__
, and __annotations__
attributes of f
on g
. This default list is in WRAPPER_ASSIGNMENTS
, you can see it in the functools source.__dict__
of g
with all elements from f.__dict__
. (see WRAPPER_UPDATES
in the source)__wrapped__=f
attribute on g
The consequence is that g
appears as having the same name, docstring, module name, and signature than f
. The only problem is that concerning the signature this is not actually true: it is just that inspect.signature
follows wrapper chains by default. You can check it by using inspect.signature(g, follow_wrapped=False)
as explained in the doc. This has annoying consequences:
Signature.bind()
.Now there is a bit of confusion between functools.wraps
and decorators, because a very frequent use case for developing decorators is to wrap functions. But both are completely independent concepts. If you're interested in understanding the difference, I implemented helper libraries for both: decopatch to write decorators easily, and makefun to provide a signature-preserving replacement for @wraps
. Note that makefun
relies on the same proven trick than the famous decorator
library.
The "encoded_c" mentioned in the @smehmood's Vigenere cipher answer should be "key_c".
Here are working encode/decode functions.
import base64
def encode(key, clear):
enc = []
for i in range(len(clear)):
key_c = key[i % len(key)]
enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
def decode(key, enc):
dec = []
enc = base64.urlsafe_b64decode(enc)
for i in range(len(enc)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec)
Disclaimer: As implied by the comments, this should not be used to protect data in a real application, unless you read this and don't mind talking with lawyers:
As of TypeScript 2.4, enums can contain string intializers https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html
This allows you to write:
enum Order {
ONE = "First",
TWO = "Second"
}
console.log(`One is ${Order.ONE.toString()}`);
and get this output:
One is First
Did you tried JQuery's scrollTo
method? http://demos.flesler.com/jquery/scrollTo/
Or you can extend JQuery and add your custom mentod:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 400);
}});
Then you can call this method like:
$("#header").scrollToMe();
To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.
public class KeyValuePairList<Tkey,TValue> : List<KeyValuePair<Tkey,TValue>>{
public void Add(Tkey key, TValue value){
base.Add(new KeyValuePair<Tkey, TValue>(key, value));
}
}
What this means is that the constructor can be initialized with better syntax::
var myList = new KeyValuePairList<int,string>{{1,"one"},{2,"two"},{3,"three"}};
I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.
If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although Tuple
is a class not a struct like KeyValuePair
this is an interesting distinction).
Curiously enough, the initializer list syntax is available on any IEnumerable
and it allows you to use any Add
method, even those not actually enumerable by your object. It's pretty handy to allow things like adding an object[]
member as a params object[]
member.
You could use a semaphore.
While the condition is not met, another thread acquires the semaphore.
Your thread would try to acquire it with acquireUninterruptibly()
or tryAcquire(int permits, long timeout, TimeUnit unit)
and would be blocked.
When the condition is met, the semaphore is also released and your thread would acquire it.
You could also try using a SynchronousQueue
or a CountDownLatch
.
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.
Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.
However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.
I suggest (note that the indent is a TAB):
tool: tool.o file1.o file2.o
$(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@
or
LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
tool: tool.o file1.o file2.o
The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable (i.e.: tool.c
and tool
).
Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. Consequently, this Makefile
work for C and C++ (and also for Fortran, etc...).
Also notice, by default, Makefile use $(CC)
as the linker. $(CC)
does not work for linking C++ object files. We modify LINK.o
only because of that. If you want to compile C code, you don't have to force the LINK.o
value.
Sure, you can also add your compilation flags with variable CFLAGS
and add your libraries in LDLIBS
. For example:
CFLAGS = -Wall
LDLIBS = -lm
One side note: if you have to use external libraries, I suggest to use pkg-config in order to correctly set CFLAGS
and LDLIBS
:
CFLAGS += $(shell pkg-config --cflags libssl)
LDLIBS += $(shell pkg-config --libs libssl)
The attentive reader will notice that this Makefile
does not rebuild properly if one header is changed. Add these lines to fix the problem:
override CPPFLAGS += -MMD
include $(wildcard *.d)
-MMD
allows to build .d files that contains Makefile fragments about headers dependencies. The second line just uses them.
For sure, a well written Makefile should also include clean
and distclean
rules:
clean:
$(RM) *.o *.d
distclean: clean
$(RM) tool
Notice, $(RM)
is the equivalent of rm -f
, but it is a good practice to not call rm
directly.
The all
rule is also appreciated. In order to work, it should be the first rule of your file:
all: tool
You may also add an install
rule:
PREFIX = /usr/local
install:
install -m 755 tool $(DESTDIR)$(PREFIX)/bin
DESTDIR
is empty by default. The user can set it to install your program at an alternative system (mandatory for cross-compilation process). Package maintainers for multiple distribution may also change PREFIX
in order to install your package in /usr
.
One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile
in the root directory and use full paths to identify your files (i.e. subdir/file.o
).
So to summarise, your full Makefile should look like:
LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
PREFIX = /usr/local
override CPPFLAGS += -MMD
include $(wildcard *.d)
all: tool
tool: tool.o file1.o file2.o
clean:
$(RM) *.o *.d
distclean: clean
$(RM) tool
install:
install -m 755 tool $(DESTDIR)$(PREFIX)/bin
Here is code for getting value return from Store procedure
Stored procedure:
alter proc [dbo].[UserlogincheckMVC]
@username nvarchar(max),
@password nvarchar(max)
as
begin
if exists(select Username from Adminlogin where Username =@username and Password=@password)
begin
return 1
end
else
begin
return 0
end
end
Code:
var parameters = new DynamicParameters();
string pass = EncrytDecry.Encrypt(objUL.Password);
conx.Open();
parameters.Add("@username", objUL.Username);
parameters.Add("@password", pass);
parameters.Add("@RESULT", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
var RS = conx.Execute("UserlogincheckMVC", parameters, null, null, commandType: CommandType.StoredProcedure);
int result = parameters.Get<int>("@RESULT");
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
This is for others who would have struggled like me to get this working....I wasted more than half a day on a seemingly trivial thing...
If you want to use SQL Express 2012 LocalDB from VS2010 you must have this patch installed http://www.microsoft.com/en-us/download/details.aspx?id=27756
Just like mentioned in the comments above I too had Microsoft .NET Framework Version 4.0.30319 SP1Rel and since its mentioned everywhere that you need "Framework 4.0.2 or Above" I thought I am good to go...
However, when I explicitly downloaded that 4.0.2 patch and installed it I got it working....
Cookies are your best bet. Look for the jquery cookie plugin.
Cookies are designed for this sort of situation -- you want to keep some information about this client on client side. Just be aware that cookies are passed back and forth on every web request so you can't store large amounts of data in there. But just a simple answer to a question should be fine.
cbind inherents order by its argument order.
User your first column(s) as your first argument
cbind(fst_col , df)
fst_col df_col1 df_col2
1 0 0.2 -0.1
2 0 0.2 -0.1
3 0 0.2 -0.1
4 0 0.2 -0.1
5 0 0.2 -0.1
cbind(df, last_col)
df_col1 df_col2 last_col
1 0.2 -0.1 0
2 0.2 -0.1 0
3 0.2 -0.1 0
4 0.2 -0.1 0
5 0.2 -0.1 0
You can easily do this with Xcode 6.3.1. Select your NavigationBar in the Document outline. Select the Attributes Inspector. Uncheck Translucent. Set Bar Tint to your desired color. Done!
In brief
There is a similar question Extract main domain name from a given url. If you take a look at this answer , you will see that it is very easy. You just need to use java.net.URL
and String
utility - Split
Oracle does not have a simple database model like MySQL or MS SQL Server. I find the closest thing is to query the tablespaces and the corresponding users within them.
For example, I have a DEV_DB tablespace with all my actual 'databases' within them:
SQL> SELECT TABLESPACE_NAME FROM USER_TABLESPACES;
Resulting in:
SYSTEM SYSAUX UNDOTBS1 TEMP USERS EXAMPLE DEV_DB
It is also possible to query the users in all tablespaces:
SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS;
Or within a specific tablespace (using my DEV_DB tablespace as an example):
SQL> select USERNAME, DEFAULT_TABLESPACE from DBA_USERS where DEFAULT_TABLESPACE = 'DEV_DB';
ROLES DEV_DB
DATAWARE DEV_DB
DATAMART DEV_DB
STAGING DEV_DB
Swifter Swift has a pretty sweet way to do this without any work really. Just provide the pattern that should be matched and what attributes to apply to it. They're great for a lot of things check them out.
``` Swift
let defaultGenreText = NSAttributedString(string: "Select Genre - Required")
let redGenreText = defaultGenreText.applying(attributes: [NSAttributedString.Key.foregroundColor : UIColor.red], toRangesMatching: "Required")
``
If you have multiple places where this would be applied and you only want it to happen for specific instances then this method wouldn't work.
You can do this in one step, just easier to read when separated.
Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden
as well, e.g.:
<div style="overflow: hidden">
<div style="overflow: hidden">some text that should not overflow<div>
</div>
Why? I have no idea but it worked for me. See https://medium.com/@crrollyson/overflow-hidden-not-working-check-the-child-element-c33ac0c4f565 (ignore the sniping at stackoverflow!)
It's implementation-specific, but in practice the rule (in the absence of #pragma pack
or the like) is:
sizeof(T)
bytes.So, given the following struct:
struct ST
{
char ch1;
short s;
char ch2;
long long ll;
int i;
};
ch1
is at offset 0s
at offset 2ch2
is at offset 4, immediately after sll
at offset 8i
is at offset 16, right after llSo sizeof(ST)
is 24.
It can be reduced to 16 bytes by rearranging the members to avoid padding:
struct ST
{
long long ll; // @ 0
int i; // @ 8
short s; // @ 12
char ch1; // @ 14
char ch2; // @ 15
} ST;
If you are using Spring MVC or Spring Boot try to avoid: @ModelAttribute("user") in one controoler, and in other controller model.addAttribute("user", userRepository.findOne(someId);
This situation can produce such error.
Let's say you have a Login
action which provides the user with a login screen, then receives the user name and password back after the user submits the form:
public ActionResult Login() {
return View();
}
public ActionResult Login(string userName, string password) {
// do login stuff
return View();
}
MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.
Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.
[HttpGet]
public ActionResult Login() {
return View();
}
[HttpPost]
public ActionResult Login(string userName, string password) {
// do login stuff
return View();
}
You can also combine the request method attributes if your action serves requests from multiple verbs:
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
.
This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.
However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.
In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.
Here is a simple example based on a SAP system I have access to.
Public Sub SimpleSAPExport()
Set SapGuiAuto = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI
Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
Set session = SAPCon.Children(0) 'Get the first session (window) on that connection
'Start the transaction to view a table
session.StartTransaction "SE16"
'Select table T001
session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
session.findById("wnd[0]/tbar[1]/btn[7]").Press
'Set our selection criteria
session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
session.findById("wnd[0]/tbar[1]/btn[8]").press
'Click the export to file button
session.findById("wnd[0]/tbar[1]/btn[45]").press
'Choose the export format
session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Choose the export filename
session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"
'Export the file
session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub
To help find the names of elements such aswnd[1]/tbar[0]/btn[0]
you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Then find the Script Recording and Playback menu item.
Within that the More
button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.
The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI")
defines the SapGuiAuto object.
If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx
in the SAP GUI installation folder.
Check out mk-parallel-dump which is part of the ever-useful maatkit suite of tools. This can dump comma-separated files with the --csv option.
This can do your whole db without specifying individual tables, and you can specify groups of tables in a backupset table.
Note that it also dumps table definitions, views and triggers into separate files. In addition providing a complete backup in a more universally accessible form, it also immediately restorable with mk-parallel-restore
More recent and much cleaner: use event.key
. No more arbitrary number codes! If you are transpiling or know your users are all on modern browsers, use this!
node.addEventListener('keydown', function(event) {
const key = event.key; // "ArrowRight", "ArrowLeft", "ArrowUp", or "ArrowDown"
});
Verbose Handling:
switch (event.key) {
case "ArrowLeft":
// Left pressed
break;
case "ArrowRight":
// Right pressed
break;
case "ArrowUp":
// Up pressed
break;
case "ArrowDown":
// Down pressed
break;
}
Modern Switch Handling:
const callback = {
"ArrowLeft" : leftHandler,
"ArrowRight" : rightHandler,
"ArrowUp" : upHandler,
"ArrowDown" : downHandler,
}[event.key]
callback?.()
NOTE: The old properties (
.keyCode
and.which
) are Deprecated.
"w", "a", "s", "d"
for direction, use event.code
To support users who are using non-qwerty/English keyboard layouts, you should instead use event.code
. This will preserve physical key location, even if resulting character changes.
event.key
would be , on Dvorak and z on Azerty, making your game unplayable.
const {code} = event
if (code === "KeyW") // KeyA, KeyS, KeyD
Optimally, you also allow key remapping, which benefits the player regardless of their situation.
P.S. event.code
is the same for arrows
To answer your direct question, it is:
Range("A1").NumberFormat = "@"
Or
Cells(1,1).NumberFormat = "@"
However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.
I have created this jquery that solved my problem.
public void ChangeClassIntoSelected(String name,String div) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
" $(element).addClass('ui-selected');\n" +
"});");
}
With this script you are able to change the actual class name into some other thing.
For getting the buffer size in c/c++ program the following is the flow
int n;
unsigned int m = sizeof(n);
int fdsocket;
fdsocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // example
getsockopt(fdsocket,SOL_SOCKET,SO_RCVBUF,(void *)&n, &m);
// now the variable n will have the socket size
IEnumerable
is just an interface and so can't be instantiated directly.
You need to create a concrete class (like a List
)
IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3" };
you can then pass this to anything expecting an IEnumerable
.
var dataString = "flag=fetchmediaaudio&id="+id;
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
success: function(html)
{
alert(html);
}
});
Once you have detected the bounding box of the document, you can perform a four-point perspective transform to obtain a top-down birds eye view of the image. This will fix the skew and isolate only the desired object.
Input image:
Detected text object
Top-down view of text document
Code
from imutils.perspective import four_point_transform
import cv2
import numpy
# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None
for c in cnts:
# Perform contour approximation
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4:
displayCnt = approx
break
# Obtain birds' eye view of image
warped = four_point_transform(image, displayCnt.reshape(4, 2))
cv2.imshow("thresh", thresh)
cv2.imshow("warped", warped)
cv2.imshow("image", image)
cv2.waitKey()
The Issue is with pip --version or python --version.
try solving issue with pip2.7 uninstall Django
command
If you are not able to uninstall using the above command then for sure your pip2.7 version is not installed so you can follow the below steps:
1)which pip2.7
it should give you an output like this :
/usr/local/bin/pip2.7
2) If you have not got this output please install pip using following commands
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
3) Now check your pip version : which pip2.7
Now you will get
/usr/local/bin/pip2.7 as output
4) uninstall Django using pip2.7 uninstall Django
command.
Problem can also be related to Python version. I had a similar problem, this is how I uninstalled Django.
Issue occurred because I had multiple python installed in my virtual environment.
$ ls
activate activate_this.py easy_install-3.4 pip2.7 python python3 wheel
activate.csh easy_install pip pip3 python2 python3.4
activate.fish easy_install-2.7 pip2 pip3.4 python2.7 python-config
Now when I tried to un-install using pip uninstall Django
Django got uninstalled from python 2.7 but not from python 3.4 so I followed the following steps to resolve the issue :
1)alias python=/usr/bin/python3
2) Now check your python version using python -V
command
3) If you have switched to your required python version now you can simply uninstall Django using pip3 uninstall Django
command
Hope this answer helps.
The simplest way would be to use FOpen or one of FOpen's Wrappers.
$page = file_get_contents("http://www.domain.com/filename");
This does require FOpen which some web hosts disable and some web hosts will allow FOpen, but not allow access to external files. You may want to check where you are going to run the script to see if you have access to External FOpen.
Here's what worked for me. Note: Adding the image within a row introduces some space so I've intentionally used only a div to encapsulate the image.
<div class="container-fluid w-100 h-auto m-0 p-0">
<img src="someimg.jpg" class="img-fluid w-100 h-auto p-0 m-0" alt="Patience">
</div>
Get rid of the parentheses.
Sample batch file:
echo "%1"
if ("%1"=="") echo match1
if "%1"=="" echo match2
Output from running above script:
C:\>echo ""
""
C:\>if ("" == "") echo match1
C:\>if "" == "" echo match2
match2
I think it is actually taking the parentheses to be part of the strings and they are being compared.
_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:
<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
var test = "<?php echo $test?>";
</script>
<?php
echo $test;
?>
Of course, I don't know why you want this, so I'm not sure the best solution.
EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.
To avoid this issue, you need to remove NO_ZERO_DATE
from the mysql mode configuration.
NO_ZERO_DATE
(and its trailing comma) from the configuration.This is a very common issue in the local environment with wamp or xamp.
I don't know how to make the chart label the axis in the format "X1 min : X2 sec", but here's another way to get durations, in the format of minutes with decimals representing seconds (.5 = 30 sec, .25 = 15 sec, etc.)
Suppose in column A you have your time data, for example in cell A1 you have 12:03:06, which your 3min 6sec data misinterpreted as 3:06 past midnight, and column B is free.
In cell B1 enter this formula: =MINUTE(A1) + SECOND(A1)/60 and hit enter/return. Grab the lower right corner of cell B2 and drag as far down as the A column goes to apply the formula to all data in col A.
Last step, be sure to highlight all of column B and set it to Number format (the application of the formula may have automatically set format to Time).
You are trying to assign a value to a function, which is not possible in C. Try the comparison operator instead:
if (strcmp("hello", "hello") == 0)
try this:
If Application.WorksheetFunction.CountIf(RangeToSearchIn, ValueToSearchFor) = 0 Then
Debug.Print "none"
End If
Answear taken from Php manual strtotime function comments :
echo date( "Y-m-d", strtotime( "2009-01-31 -1 day"));
Or
$date = "2009-01-31";
echo date( "Y-m-d", strtotime( $date . "-1 day"));
You can try this:
@OneToOne(cascade = CascadeType.REFRESH)
or
@OneToMany(cascade = CascadeType.REFRESH)
Syntax for AngularJS v1.4.8 + (v1.5.0)
$http.post(url, data, config)
.then(
function (response) {
// success callback
},
function (response) {
// failure callback
}
);
Eg:
var url = "http://example.com";
var data = {
"param1": "value1",
"param2": "value2",
"param3": "value3"
};
var config = {
headers: {
'Content-Type': "application/json"
}
};
$http.post(url, data, config)
.then(
function (response) {
// success callback
},
function (response) {
// failure callback
}
);
I selected columns that I want to delete 0 values then clicked DATA > FILTER. In column's header there is a filter icon appears. I clicked on that icon and selected only 0 values and clicked OK. Only 0 values becomes selected. Finally clear content OR use DELETE button.
Then to remove the blank rows from the deleted 0 values removed. I click DATA > FILTER I clicked on that filter icon and unselected blanks copy and paste the remaining data into a new sheet.
This started happening to my site after I enabled namespace and custom Open Graph actions and objects. Once you enable it, you lose support for standard object types such as bar, or in my case article. (or it's possible Facebook may have deprecated certain types, I'm not 100% sure) When no supported type is specified, Facebook defaults to website.
To fix this what you need to do is go into your app dashboard, select your app, then go to the Open Graph section. Under "Object Types", define your own types, such as "bar."
Next you will have to change your meta tags to look like this:
<meta property="og:type" content="your_namespace:your_object_type" />
If you click on "Get Code" next to the object type in the dashboard, Facebook will provide you with an example of meta tags to use.
As shown in this example, you can apply a background to a canvas
element through CSS and this background will not be considered part the image, e.g. when fetching the contents through toDataURL()
.
Here are the contents of the example, for Stack Overflow posterity:
<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>Canvas Background through CSS</title>
<style type="text/css" media="screen">
canvas, img { display:block; margin:1em auto; border:1px solid black; }
canvas { background:url(lotsalasers.jpg) }
</style>
</head><body>
<canvas width="800" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
var can = document.getElementsByTagName('canvas')[0];
var ctx = can.getContext('2d');
ctx.strokeStyle = '#f00';
ctx.lineWidth = 6;
ctx.lineJoin = 'round';
ctx.strokeRect(140,60,40,40);
var img = document.getElementsByTagName('img')[0];
img.src = can.toDataURL();
</script>
</body></html>
I'm going to weigh in on this (Angular 7 Solution)
input [appFocus]="focus"....
import {AfterViewInit, Directive, ElementRef, Input,} from '@angular/core';
@Directive({
selector: 'input[appFocus]',
})
export class FocusDirective implements AfterViewInit {
@Input('appFocus')
private focused: boolean = false;
constructor(public element: ElementRef<HTMLElement>) {
}
ngAfterViewInit(): void {
// ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
if (this.focused) {
setTimeout(() => this.element.nativeElement.focus(), 0);
}
}
}
Sure. Just walk through the $_POST
array:
foreach ($_POST as $key => $value) {
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
}
Be ware with this:
RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}
It is likely a case of IIS 7 'handling' the HTTP OPTIONS response instead of your application specifying it. To determine this, in IIS7,
Go to your site's Handler Mappings.
Scroll down to 'OPTIONSVerbHandler'.
Change the 'ProtocolSupportModule' to 'IsapiHandler'
Set the executable: %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll
Now, your config entries above should kick in when an HTTP OPTIONS verb is sent.
Alternatively you can respond to the HTTP OPTIONS verb in your BeginRequest method.
protected void Application_BeginRequest(object sender,EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}
There are a few ways you can define constants in Kotlin,
Using companion object
companion object {
const val ITEM1 = "item1"
const val ITEM2 = "item2"
}
you can use above companion object block inside any class and define all your fields inside this block itself. But there is a problem with this approach, the documentation says,
even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces.
When you create your constants using companion object, and see the decompiled bytecode, you'll something like below,
ClassName.Companion Companion = ClassName.Companion.$$INSTANCE;
@NotNull
String ITEM1 = "item1";
@NotNull
String ITEM2 = "item2";
public static final class Companion {
@NotNull
private static final String ITEM1 = "item1";
@NotNull
public static final String ITEM2 = "item2";
// $FF: synthetic field
static final ClassName.Companion $$INSTANCE;
private Companion() {
}
static {
ClassName.Companion var0 = new ClassName.Companion();
$$INSTANCE = var0;
}
}
From here you can easily see what the documentation said, even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects It's doing extra work than required.
Now comes another way, where we don't need to use companion object like below,
object ApiConstants {
val ITEM1: String = "item1"
}
Again if you see the decompiled version of the byte code of above snippet, you'll find something like this,
public final class ApiConstants {
private static final String ITEM1 = "item1";
public static final ApiConstants INSTANCE;
public final String getITEM1() {
return ITEM1;
}
private ApiConstants() {
}
static {
ApiConstants var0 = new ApiConstants();
INSTANCE = var0;
CONNECT_TIMEOUT = "item1";
}
}
Now if you see the above decompiled code, it's creating get method for each variable. This get method is not required at all.
To get rid of these get methods, you should use const before val like below,
object ApiConstants {
const val ITEM1: String = "item1"
}
Now if you see the decompiled code of above snippet, you'll find it easier to read as it does the least background conversion for your code.
public final class ApiConstants {
public static final String ITEM1 = "item1";
public static final ApiConstants INSTANCE;
private ApiConstants() {
}
static {
ApiConstants var0 = new ApiConstants();
INSTANCE = var0;
}
}
So this is the best way to create constants.
Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote
:
git ls-remote --tags /url/to/upstream/repo
(as illustrated in "When listing git-ls-remote why there's “^{}
” after the tag name?")
xbmono illustrates in the comments that quotes are needed:
git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"
Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):
git push --follow-tags
See Push git commits & tags simultaneously.
Regarding Atlassian SourceTree specifically:
Note that, from this thread, SourceTree ONLY shows local tags.
There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015
since Dec. 2015.
A simple workaround:
see a list of only unpushed tags?
git push --tags
or check the "
Push all tags
" box on the "Push" dialog box, all tags will be pushed to your remote.
That way, you will be "sure that they are present in remote so that other developers can pull them".
Find elements:
var elements = document.getElementsByClassName('widget hover');
Since elements
is a live
array and reflects all dom changes you can remove all hover
classes with a simple while loop:
while(elements.length > 0){
elements[0].classList.remove('hover');
}
You can use the event ProgressChanged ; the last time it is raised will indicate that the document is fully rendered:
this.webBrowser.ProgressChanged += new
WebBrowserProgressChangedEventHandler(webBrowser_ProgressChanged);
Use Thread.Sleep
when you want to block the current thread.
Use Task.Delay
when you want a logical delay without blocking the current thread.
Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.
For someone who needs quick reference of C# Escape Sequences that can be used in string
literals:
\t Horizontal tab (ASCII code value: 9)
\n Line feed (ASCII code value: 10)
\r Carriage return (ASCII code value: 13)
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\x12 ASCII character in hexadecimal notation (e.g. for 0x12)
\x1234 Unicode character in hexadecimal notation (e.g. for 0x1234)
It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline
which gets adjusted to current OS settings. With .Net Core it gets really important.
Even though Caffeine Coma's issue was resolved, I would like to offer another potential cause for the title not showing up on a UIButton.
If you set an image for the UIButton using
- (void)setImage:(UIImage *)image forState:(UIControlState)state
It can cover the title. I found this out the hard way and imagine some of you end up reading this page for the same reason.
Use this method instead
- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state
for the button image and the title will not be affected.
I tested this with programmatically created buttons and buttons created in a .xib
You don't need to pass the quotes enclosing the custom headers to curl. Also, your variables in the middle of the data
argument should be quoted.
First, write a function that generates the post data of your script. This saves you from all sort of headaches concerning shell quoting and makes it easier to read an maintain the script than feeding the post data on curl's invocation line as in your attempt:
generate_post_data()
{
cat <<EOF
{
"account": {
"email": "$email",
"screenName": "$screenName",
"type": "$theType",
"passwordSettings": {
"password": "$password",
"passwordConfirm": "$password"
}
},
"firstName": "$firstName",
"lastName": "$lastName",
"middleName": "$middleName",
"locale": "$locale",
"registrationSiteId": "$registrationSiteId",
"receiveEmail": "$receiveEmail",
"dateOfBirth": "$dob",
"mobileNumber": "$mobileNumber",
"gender": "$gender",
"fuelActivationDate": "$fuelActivationDate",
"postalCode": "$postalCode",
"country": "$country",
"city": "$city",
"state": "$state",
"bio": "$bio",
"jpFirstNameKana": "$jpFirstNameKana",
"jpLastNameKana": "$jpLastNameKana",
"height": "$height",
"weight": "$weight",
"distanceUnit": "MILES",
"weightUnit": "POUNDS",
"heightUnit": "FT/INCHES"
}
EOF
}
It is then easy to use that function in the invocation of curl:
curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data "$(generate_post_data)" "https://xxx:[email protected]/xxxxx/xxxx/xxxx"
This said, here are a few clarifications about shell quoting rules:
The double quotes in the -H
arguments (as in -H "foo bar"
) tell bash to keep what's inside as a single argument (even if it contains spaces).
The single quotes in the --data
argument (as in --data 'foo bar'
) do the same, except they pass all text verbatim (including double quote characters and the dollar sign).
To insert a variable in the middle of a single quoted text, you have to end the single quote, then concatenate with the double quoted variable, and re-open the single quote to continue the text: 'foo bar'"$variable"'more foo'
.
This was pretty well answered over here: How to make a YouTube embedded video a full page width one?
If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)
<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
of the video it should play on load. Here's a demo over at jsfiddle.
Since you are using Java, printf
is available from version 1.5
You may use it like this
System.out.printf("%03d ", x);
For Example:
System.out.printf("%03d ", 5);
System.out.printf("%03d ", 55);
System.out.printf("%03d ", 555);
Will Give You
005 055 555
as output
See: System.out.printf
and Format String Syntax
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
adapter.remove(adapter.getItem(i));
}
then call notifyDataSetChanged();
Apart from above correct answer, also make sure that you have set correct Main Interface in General.
No, there is no way to do this yet. I wish they add a future like this in browsers.
EDIT:
Now there is a Full Screen API for the web You can requestFullscreen
on an Video or Canvas element to ask user to give you permisions and make it full screen.
Let's consider this element:
<video controls id="myvideo">
<source src="somevideo.webm"></source>
<source src="somevideo.mp4"></source>
</video>
We can put that video into fullscreen mode with script like this:
var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
}
vitaminwater's answer is working for me.
If your textview's text is bouncing up and down during edit, after setting [textView setScrollEnabled:NO];
, set Size Inspector > Scroll View > Content Insets > Never
.
Hope it helps.
Within the view you want to bring to the top... (in swift)
superview?.bringSubviewToFront(self)
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(12, 18)
);
Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.
Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.
Sub RepairFormula()
Dim FormulaString As String
FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString
This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.
I'm using pandas 0.16.2. This has better performance on my large dataset:
data.groupby(data.date.dt.year)
Using the dt
option and playing around with weekofyear
, dayofweek
etc. becomes far easier.
Try using input type="tel"
instead. It pops up a keyboard with numbers, and it doesn’t show spin boxes. It requires no JavaScript or CSS or plugins or anything else.
With Google Firebase ML Kit's barcode scanning API, you can read data encoded using most standard barcode formats.
https://firebase.google.com/docs/ml-kit/read-barcodes?authuser=0
You can follow this link to read barcodes efficiently.
An advice: Always ask MySQL what the problem is. In my case, less /var/log/mysql/error.log
and see this:
2015-07-28 12:01:48 23224 [ERROR] /usr/sbin/mysqld: unknown variable 'log_slow_queries=/var/log/mysql/mysql-slow.log'
2015-07-28 12:01:48 23224 [ERROR] Aborting
It is complaining, because I uncommented this option in my.cnf
, but after commenting this option, it started without any problem.
@scanlegentil I like this.
A little improvement would be:
$Depth = 2
$Path = "."
$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host
As mentioned, this would only scan the specified depth, so this modification is an improvement:
$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2 # How many levels deep to scan
$Path = "." # starting path
For ($i=$StartLevel; $i -le $Depth; $i++) {
$Levels = "\*" * $i
(Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
Select FullName
}
If you would like to replace but still keeping the style of previous str. It is possible.
For example: highlight the string "test asdasd TEST asd tEst asdasd".
sentence = "test asdasd TEST asd tEst asdasd"
result = re.sub(
'(test)',
r'<b>\1</b>', # \1 here indicates first matching group.
sentence,
flags=re.IGNORECASE)
test asdasd TEST asd tEst asdasd
Open your Android SDK Manager and ensure that you download/install a system image for the API level you are developing with.
This is what I used for similar type of use case as yours.
<style type="text/css">
#element1 {display:inline-block; width:45%; padding:10px}
#element2 {display:inline-block; width:45%; padding:10px}
</style>
<div id="element1">
element 1 markup
</div>
<div id="element2">
element 2 markup
</div>
Adjust your width and padding as per your requirement. Note - Do not exceed 'width' more than 100% altogether (ele1_width+ ele2_width) to add 'padding', keep it less than 100%.
document.getElementById('username').value = 'foo';
document.getElementById('login_form').submit();
Cloud watch also allows you to create metrics for your S3 bucket. It shows you metrics by the size and object count. Services> Management Tools> Cloud watch. Pick the region where your S3 bucket is and the size and object count metrics would be among those available metrics.
if you want to fill all the column:
update 'column' set 'info' where keyID!=0;
You can use js2py context to execute your js code and get output from document.write with mock document object:
import js2py
js = """
var output;
document = {
write: function(value){
output = value;
}
}
""" + your_script
context = js2py.EvalJs()
context.execute(js)
print(context.output)
.img-wrap:hover img {_x000D_
transform: scale(0.8);_x000D_
}_x000D_
.img-wrap img {_x000D_
display: block;_x000D_
transition: all 0.3s ease 0s;_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="img-wrap">_x000D_
<img src="http://www.sampleimages/images.jpg"/> // Your image_x000D_
</div>
_x000D_
This code is only for zoom-out effect.Set the div "img-wrap" according to your styles and insert the above style results zoom-out effect.For zoom-in effect you must increase the scale value(eg: for zoom-in,use transform: scale(1.3);
Check permission for INTERNET in mainfest file and check network connectivity.
Use YQL and you don't need to worry. It's a query language by Yahoo and you can get all the stock data including the name of the company for the ticker. It's a REST API and it returns the results via XML or JSON. I have a full tutorial and source code on my site take a look: http://www.jarloo.com/yahoo-stock-symbol-lookup/
This has changed in iOS 8. See the following tech note: https://developer.apple.com/library/ios/technotes/tn2406/_index.html
The Apple sanctioned way (from the link above) is as follows:
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
If the colspan
or rowspan
is all set to 1
, counting the children td
s will give the correct answer. However, if there are spans, we cannot count the number of columns exactly, even by the maximum number of td
s of the rows. Consider the following example:
var mytable = document.getElementById('table')_x000D_
for (var i=0; i < mytable.rows.length; ++i) {_x000D_
document.write(mytable.rows[i].cells.length + "<br>");_x000D_
}
_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
border-collapse: collapse;_x000D_
padding: 3px;_x000D_
}
_x000D_
<table id="table">_x000D_
<thead>_x000D_
<tr>_x000D_
<th colspan="2">Header</th>_x000D_
<th rowspan="2">Hi</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Month</th>_x000D_
<th>Savings</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td colspan="2">hello</td>_x000D_
<td>world</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>hello</td>_x000D_
<td colspan="2">again</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
I had the same issue with a dll yesterday and all it referenced was System, System.Data, and System.Xml. Turns out the build configuration for the Platform type didn't line up. The dll was build for x86 and the program using it was "Any CPU" and since I am running a x64 machine, it ran the program as x64 and had issues with the x86 dll. I don't know if this is your issue or not, just thought that I would mention it as something else to check.
// on configuration sections
[ConfigurationProperty]
// in asp.net
[NotifyParentProperty(true)]
The other answers will give you a good idea how to accomplish what you have asked for....
However
There are not many cases where this is a good idea. It is usually better to store only the filename in the database and the file on the file system.
That way your database is much smaller, can be transported around easier and more importantly is quicker to backup / restore.
Using PowerShell, you can use the following
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Select name
This will show a list off all services which displayname starts with "NATION-".
You can also directly stop or start the services;
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Stop-Service
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Start-Service
or simply
Get-Service | Where-Object {$_.displayName.StartsWith("NATION-")} | Restart-Service
===method 1 with http login===
[php.ini]
session.gc_maxlifetime = 86400
[config.inc.php]
$cfg['Servers'][$i]['auth_type'] = 'http';
===method 2 with cookie login===
[php.ini]
session.gc_maxlifetime = 86400
[config.inc.php]
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['LoginCookieValidity'] = 86400;
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['controluser'] = 'phpmyadmin_pma';
$cfg['Servers'][$i]['controlpass'] = 'nigookike';
$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig'; // there's a lot of other table required for full functionality,
// all others can be left out unconfig except this one
[mysql]
-import phpMyAdmin/sql/create_tables.sql
-grant PRIVILEGES to phpmyadmin_pma as below
db/table
phpmyadmin ALL PRIVILEGES
mysql/db SELECT
mysql/host SELECT
mysql/tables_priv USAGE
mysql/user USAGE
-clear all entries should old one exists
phpmyadmin/pma__userconfig
[webUI]
-clear broswer cookie
-as normal mysql user, access http://mysql/phpmyadmin , at the bottom of page:
The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. [Find out why.]
-near top of the page
[Create missing phpMyAdmin configuration storage tables.]
-access http://mysql/phpmyadmin > settings > features > Login cookie validity > 86400 > [apply]
-check phpmyadmin/pma__userconfig contain new entries of aforemention mysql user
N.B.
every user has independent setting and [webUI] procedure has to be repeated for each user
if "The phpMyAdmin configuration storage is not completely configured, some extended features have been deactivated. [Find out why.]"
link does not appears on frontpage, go settings > features > warnings > Missing phpMyAdmin configuration storage tables > [refresh] a few times will make it appears
Looking at your example, I think this is what you want:
var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);
With pure javascript:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
Here's how I ended up doing this:
<div id="divform">
<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div><input type="button" value="Upload" onclick="closeSelf();"/></div>
</form>
</div>
<div id="closelink" style="display:none">
<a href="javascript:window.close()">Click Here to Close this Page</a>
</div>
function closeSelf(){
document.forms['certform'].submit();
hide(document.getElementById('divform'));
unHide(document.getElementById('closelink'));
}
Where hide()
and unhide()
set the style.display
to 'none'
and 'block'
respectively.
Not exactly what I had in mind, but this will have to do for the time being. Works on IE, Safari, FF and Chrome.
The clean way to do so is to pass a new instance of the created entity through the controller:
//GET
public ActionResult CreateNewMyEntity(string default_value)
{
MyEntity newMyEntity = new MyEntity();
newMyEntity._propertyValue = default_value;
return View(newMyEntity);
}
If you want to pass the default value through ActionLink
@Html.ActionLink("Create New", "CreateNewMyEntity", new { default_value = "5" })
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
Add volley.jar
as library
[MyProjectPath]/app/libs/
folderUse the source files from git (a rather manual/general way described here)
git clone https://github.com/git/git
... sry bad one, but couldn't resist ^^)git clone https://android.googlesource.com/platform/frameworks/volley
com
folder from within [path_where_you_typed_git_clone]/volley/src
to your projects app/src/main/java
folder (Integrate it instead, if you already have a com folder there!! ;-))The files show up immediately in Android Studio. For Eclipse you will have to right-click
on the src
folder and press refresh
(or F5
) first.
Use gradle via the "unofficial" maven mirror
In your project's src/build.gradle
file add following volley dependency:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// ...
compile 'com.mcxiaoke.volley:library:1.+'
}
Click on Try Again
which should right away appear on the top of the file, or just Build
it if not
The main "advantage" here is, that this will keep the version up to date for you, whereas in the other two cases you would have to manually update volley.
On the "downside" it is not officially from google, but a third party weekly mirror.
But both of these points, are really relative to what you would need/want.
Also if you don't want updates, just put the desired version there instead e.g. compile 'com.mcxiaoke.volley:library:1.0.7'
.
This is how I solved my problem:
List<User> list = GetAllUsers(); //Private Method
if (!sortAscending)
{
list = list
.OrderBy(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
.ToList();
}
else
{
list = list
.OrderByDescending(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
.ToList();
}
If you need a unique ID, you must first decide on your definition of unique. If you want/intend to use it for a copy-protection mechanism, then use something simple. This is because if someone really wants to use your software, (s)he will find a way to break your protection, given enough time and skill. In the case of a unique hardware ID, just think about virtual machines and you'll see that it is possible to spoof anything so someone can tamper with your software.
There is not much you can take from a PC and consider it as uniqueness over its whole lifetime. (Hardware changes will most likely require regenerating the ID at some point.) If you need something like that, you should investigate using an authentication USB Dongle which you can send to your customers.
If you just need some unique identifier that is not as hard to obtain, you could take the MAC address (unreliable), the OS serial number or the domain and user's name, but all of them are susceptible to forgery. However, if your main goal is to lock out unauthorised people, you won't sell anything because no one will want to use your software if it is hard to install, register or to move from one PC to another, although the last consideration is part and parcel of per-machine licensing. (This will likely happen quite often.)
As a first step, make it easy: Use something simple which is not easy to spoof in your target group. (For example, domain and user names can't be easily spoofed by enterprise customers, because their PCs are running in a larger environment implementing policies, etc.) Just forget about the others until you have that.
Maybe you can lock them out but that doesn't mean they're going to buy your software; they just won't use it anymore. What you have to consider is how many potential customers won't be or aren't willing to pay because you made it so complicated to use your program.
Those are untracked files. This means git isn't tracking them. It's only listing them because they're not in the git ignore file. Since they're not being tracked by git, git reset
won't touch them.
If you want to blow away all untracked files, the simplest way is git clean -f
(use git clean -n
instead if you want to see what it would destroy without actually deleting anything). Otherwise, you can just delete the files you don't want by hand.
Actually without PDB files and symbolic information they have it would be impossible to create a successful crash report (memory dump files) and Microsoft would not have the complete picture what caused the problem.
And so having PDB improves crash reporting.
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
From the comments, the problem was caused by using dlls that were built with Visual Studio 2013 in a project compiled with Visual Studio 2012. The reason for this was a third party library named the folders containing the dlls vc11, vc12. One has to be careful with any system that uses the compiler version (less than 4 digits) since this does not match the version of Visual Studio (except for Visual Studio 2010).
The Microsoft C++ runtime dlls use a 2 or 3 digit code also based on the compiler version not the version of Visual Studio.
There is binary compatibility between Visual Studio 2015, 2017 and 2019.
The warning appears only because the demo code has:
function TabPanel(props) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}> // <==NOTE P TAG HERE
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
Changing it like this takes care of it:
function TabPanel(props) {
const {children, value, index, classes, ...other} = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Container>
<Box> // <== P TAG REMOVED
{children}
</Box>
</Container>
)}
</div>
);
}
You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name
According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.
"Release 0.8.7 - May 13 2016
-Fix for issue when inserting read-only images on Windows. Issue #352.
-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.
-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."
There are several good answers here. I however prefer [1] not using a regular expression, and [2] using logic that is simple to read, and [3] to have a short function that [4] does not return true if the name is a substring of another cookie name . Lastly [5] we can't use a for each loop since a return doesn't break it.
function cookieExists(name) {
var cks = document.cookie.split(';');
for(i = 0; i < cks.length; i++)
if (cks[i].split('=')[0].trim() == name) return true;
}
As pointed above, BFS can only be used to find shortest path in a graph if:
There are no loops
All edges have same weight or no weight.
To find the shortest path, all you have to do is start from the source and perform a breadth first search and stop when you find your destination Node. The only additional thing you need to do is have an array previous[n] which will store the previous node for every node visited. The previous of source can be null.
To print the path, simple loop through the previous[] array from source till you reach destination and print the nodes. DFS can also be used to find the shortest path in a graph under similar conditions.
However, if the graph is more complex, containing weighted edges and loops, then we need a more sophisticated version of BFS, i.e. Dijkstra's algorithm.
It is possible to define a function from inside another function. the inner function does not exist until the outer function gets executed.
echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';
$x=x(2);
echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n';
Output
y is not defined
y is defined
Simple thing you can not call function y before executed x
Another simple solution with +=
:
$y = 1;
for ($x = $y; $x <= 15; $y++) {
printf("The number of first paragraph is: $y <br>");
printf("The number of second paragraph is: $x+=2 <br>");
}
I think a better way to do this is to change the base_size
argument. It will increase the text sizes consistently.
g + theme_grey(base_size = 22)
As seen here.
This is quite easy to do with your Apache environment variables. This only works with Apache 2, which I assume you are using.
Simply use the following PHP code:
<?php
$request_url = apache_getenv("HTTP_HOST") . apache_getenv("REQUEST_URI");
echo $request_url;
?>
I had this problem and solved it by adding:
lintOptions {
checkReleaseBuilds false
}
to my build.gradle
file within the android{ }
section.
JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.
Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.
Try this:
tr -d " \t" <filename
See the manpage for tr(1) for more details.
add the activity in your manifest file
<activity android:name=".OrderScreen" />
As this question How to dynamically call methods within a class using method-name assignment to a variable [duplicate] marked as a duplicate as this one, I am posting a related answer here:
The scenario is, a method in a class want to call another method on the same class dynamically, I have added some details to original example which offers some wider scenario and clarity:
class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func = getattr(MyClass, 'function{}'.format(self.i))
func(self, 12) # This one will work
# self.func(12) # But this does NOT work.
def function1(self, p1):
print('function1: {}'.format(p1))
# do other stuff
def function2(self, p1):
print('function2: {}'.format(p1))
# do other stuff
if __name__ == "__main__":
class1 = MyClass(1)
class1.get()
class2 = MyClass(2)
class2.get()
Output (Python 3.7.x)
function1: 12
function2: 12
I encounter the error as well,
_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting
But list args work well.
I use mysqlclient python lib. The lib looks like not to accept tuple args. To pass list args like ['arg1', 'arg2']
will work.
The following may work with all the backends, but I tested it only on QT:
import numpy as np
import matplotlib.pyplot as plt
import time
plt.switch_backend('QT4Agg') #default on my system
print('Backend: {}'.format(plt.get_backend()))
fig = plt.figure()
ax = fig.add_axes([0,0, 1,1])
ax.axis([0,10, 0,10])
ax.plot(5, 5, 'ro')
mng = plt._pylab_helpers.Gcf.figs.get(fig.number, None)
mng.window.showMaximized() #maximize the figure
time.sleep(3)
mng.window.showMinimized() #minimize the figure
time.sleep(3)
mng.window.showNormal() #normal figure
time.sleep(3)
mng.window.hide() #hide the figure
time.sleep(3)
fig.show() #show the previously hidden figure
ax.plot(6,6, 'bo') #just to check that everything is ok
plt.show()
import sys
import time
a = 0
for x in range (0,3):
a = a + 1
b = ("Loading" + "." * a)
# \r prints a carriage return first, so `b` is printed on top of the previous line.
sys.stdout.write('\r'+b)
time.sleep(0.5)
print (a)
Note that you might have to run sys.stdout.flush()
right after sys.stdout.write('\r'+b)
depending on which console you are doing the printing to have the results printed when requested without any buffering.
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
RewriteEngine on
RewriteBase /basic_test/
RewriteRule ^index.php$ test.php
Here's a nifty utility I use:
/**
* A common method for all enums since they can't have another base class
* @param <T> Enum type
* @param c enum type. All enums must be all caps.
* @param string case insensitive
* @return corresponding enum, or null
*/
public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
if( c != null && string != null ) {
try {
return Enum.valueOf(c, string.trim().toUpperCase());
} catch(IllegalArgumentException ex) {
}
}
return null;
}
Then in my enum class I usually have this to save some typing:
public static MyEnum fromString(String name) {
return getEnumFromString(MyEnum.class, name);
}
If your enums are not all caps, just change the Enum.valueOf
line.
Too bad I can't use T.class
for Enum.valueOf
as T
is erased.
var shadows = UIView()
shadows.frame = view.frame
shadows.clipsToBounds = false
view.addSubview(shadows)
let shadowPath0 = UIBezierPath(roundedRect: shadows.bounds, cornerRadius: 10)
let layer0 = CALayer()
layer0.shadowPath = shadowPath0.cgPath
layer0.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.23).cgColor
layer0.shadowOpacity = 1
layer0.shadowRadius = 6
layer0.shadowOffset = CGSize(width: 0, height: 3)
layer0.bounds = shadows.bounds
layer0.position = shadows.center
shadows.layer.addSublayer(layer0)
Sample code you can use to let Tika take care of container files for you. http://wiki.apache.org/tika/RecursiveMetadata
Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.
Seems I don't have enough rep to post a comment, so another answer will have to do.
When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.
Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()
function purge(d) {
var a = d.attributes, i, l, n;
if (a) {
for (i = a.length - 1; i >= 0; i -= 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}
And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.
And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.
The supercalifragilisticexpialidocious answer is:
add this at the top of your js file or script tag
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
document.body.scrollTop = 0; // For Safari
Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique
org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)
Sample code
HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap)
Google Chrome and safari needs a tweak for body and background issues. We have use additional identifier as mentioned below.
<style>
body { background:#204960 url(../images/example.gif) repeat-x top; margin:0; padding:0; font-family:Tahoma; font-size:12px; }
#body{ background:#204960 url(../images/example.gif) repeat-x top; margin:0; padding:0; font-family:Tahoma; font-size:12px;}
</style>
<body id="body">
Use both body and #body identifier and enter same styles in both. Make the body tag with id attribute of body.
This works for me.
I formerly voted to close this question as off-topic but actually I changed my mind as this is quite nice visual effect which, unfortunately, is not yet part of support library. It will most likely show up in future update, but there's no time frame announced.
Luckily there are few custom implementations already available:
including Materlial themed widget sets compatible with older versions of Android:
so you can try one of these or google for other "material widgets" or so...
You need to use an explicit color value (e.g. #000
or blue
) for the color
-property. none
is invalid here. The initial value is browser-specific and cannot be restored using CSS. Keep in mind that there are some other pseudo-classes than :active
, too.
It worked for me when HDD with win8.1 crashed and my new HDD has win10. Important to know - Create Legacy folder mentioned in this link. - Remember to rename the StickyNotes.snt to ThresholdNotes.snt. - Restart the app
Find details here https://www.reddit.com/r/Windows10/comments/4wxfds/transfermigrate_sticky_notes_to_new_anniversary/
To change the font size of the <input />
tag in HTML, use this:
<input style="font-size:20px" type="text" value="" />
It will create a text input box and the text inside the text box will be 20 pixels.
Here comes Linq:
var listItem = list.Single(i => i.Title == title);
It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault
.
If you want a collection of items matching the title, there's:
var listItems = list.Where(i => i.Title == title);
You can run it through the Apache proxy, but it would have to be running in a virtual directory (e.g. http://mysite.something/myreactapp ).
This may seem sort of redundant but if you have other pages that are not part of your React app (e.g. PHP pages), you can serve everything via port 80 and make it apear that the whole thing is a cohesive website.
1.) Start your react app with npm run, or whatever command you are using to start the node server. Assuming it is running on http://127.0.0.1:8080
2.) Edit httpd-proxy.conf and add:
ProxyRequests On
ProxyVia On
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /myreactapp http://127.0.0.1:8080/
ProxyPassReverse /myreactapp http://127.0.0.1:8080/
3.) Restart Apache
You can get some inspiration by reading an entrypoint.sh
script written by the contributors from MySQL that checks whether the specified variables were set.
As the script shows, you can pipe them with -a
, e.g.:
if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
...
fi
No.
Maintenance-light best practice is to specify only the required columns.
At least 2 reasons:
Edit (July 2011):
If you drag from Object Explorer the Columns
node for a table, it puts a CSV list of columns in the Query Window for you which achieves one of your goals
Man, I had the issue in one of my eclipse projects, amazingly the issue was the order of the jars in my .project file. believe it or not!
You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.
To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data
to an array before not after you try to slice it:
R = np.array(mean_data)[:,0]
instead of
R = np.array(mean_data[:,0])
But, assuming mean_data has a shape nx3
, instead of
R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]
You can simply do
A = np.array(mean_data).mean(axis=0)
which averages over the 0
th axis and returns a length-n
array
But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:
Make sure you have the URL correct for whatever you are downloading. First of all, URLs with characters like ?
and such cannot be parsed and resolved. This will confuse the cmd line and accept any characters that aren't resolved into the source URL name as the file name you are downloading into.
For example:
wget "sourceforge.net/projects/ebosse/files/latest/download?source=typ_redirect"
will download into a file named, ?source=typ_redirect
.
As you can see, knowing a thing or two about URLs helps to understand wget
.
I am booting from a hirens disk and only had Linux 2.6.1 as a resource (import os is unavailable). The correct syntax that solved my problem downloading an ISO onto the physical hard drive was:
wget "(source url)" -O (directory where HD was mounted)/isofile.iso"
One could figure the correct URL by finding at what point wget
downloads into a file named index.html
(the default file), and has the correct size/other attributes of the file you need shown by the following command:
wget "(source url)"
Once that URL and source file is correct and it is downloading into index.html
, you can stop the download (ctrl + z) and change the output file by using:
-O "<specified download directory>/filename.extension"
after the source url.
In my case this results in downloading an ISO and storing it as a binary file under isofile.iso
, which hopefully mounts.
You need to add a pseudo-hostname to the CALLBACK_URL 'app://' doesn't make sense as a URL and cannot be parsed.
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
Previous comments about using abstract classes for common implementation is definitely on the mark. One benefit I haven't seen mentioned yet is that the use of interfaces makes it much easier to implement mock objects for the purpose of unit testing. Defining IPet and PetBase as Jason Cohen described enables you to mock different data conditions easily, without the overhead of a physical database (until you decide it's time to test the real thing).
import java.util.*;
imports everything within java.util including the Date class.
import java.util.Date;
just imports the Date class.
Doing either of these could not make any difference.
Another nice thing about @HostBinding
is that you can combine it with @Input
if your binding relies directly on an input, eg:
@HostBinding('class.fixed-thing')
@Input()
fixed: boolean;
In the OnCreate method add this:
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Then add this method:
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
I use $.data - http://api.jquery.com/jquery.data/
//Set value 7 to data-id
$.data(this, 'id', 7);
//Get value from data-id
alert( $(this).data("id") ); // => outputs 7
I wrote a plugin called hasEventListener which exactly does that.
Hope this helps.
you can do top level await since typescript 3.8
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#-top-level-await
From the post:
This is because previously in JavaScript (along with most other languages with a similar feature), await was only allowed within the body of an async function. However, with top-level await, we can use await at the top level of a module.
const response = await fetch("...");
const greeting = await response.text();
console.log(greeting);
// Make sure we're a module
export {};
Note there’s a subtlety: top-level await only works at the top level of a module, and files are only considered modules when TypeScript finds an import or an export. In some basic cases, you might need to write out export {} as some boilerplate to make sure of this.
Top level await may not work in all environments where you might expect at this point. Currently, you can only use top level await when the target compiler option is es2017 or above, and module is esnext or system. Support within several environments and bundlers may be limited or may require enabling experimental support.
Additionally to nargs
, you might want to use choices
if you know the list in advance:
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
First, make sure you are on the right branch.
Then (one time only):
git branch --track
After that this works again:
git pull
Important things for Java benchmarks are:
System.gc()
between iterations, it's a good idea to run it between tests, so that each test will hopefully get a "clean" memory space to work with. (Yes, gc()
is more of a hint than a guarantee, but it's very likely that it really will garbage collect in my experience.)I'm just in the process of blogging about the design of a benchmarking framework in .NET. I've got a couple of earlier posts which may be able to give you some ideas - not everything will be appropriate, of course, but some of it may be.
Apple hand three categories of certificates: Trusted
, Always Ask
and Blocked
. You'll encounter the issue if your certificate's type on the Blocked
and Always Ask
list. On Safari it show’s like:
And you can find the type of Always Ask
certificates on Settings > General > About > Certificate Trust Setting
There is the List of available trusted root certificates in iOS 11
From the GNU UPC website:
Compiler build fails with fatal error: gnu/stubs-32.h: No such file or directory
This error message shows up on the 64 bit systems where GCC/UPC multilib feature is enabled, and it indicates that 32 bit version of libc is not installed. There are two ways to correct this problem:
- Install 32 bit version of glibc (e.g. glibc-devel.i686 on Fedora, CentOS, ..)
- Disable 'multilib' build by supplying "--disable-multilib" switch on the compiler configuration command
You can create extension method like:
public static IEnumerable<TResult> LeftOuterJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source, IEnumerable<TInner> other, Func<TSource, TKey> func, Func<TInner, TKey> innerkey, Func<TSource, TInner, TResult> res)
{
return from f in source
join b in other on func.Invoke(f) equals innerkey.Invoke(b) into g
from result in g.DefaultIfEmpty()
select res.Invoke(f, result);
}
You should be able to install from NuGet (http://www.nuget.org/packages/Microsoft.AspNet.Mvc) into VS2012. Change the Target Framework to .NET 4.5.
Not sure the new project templates are ready for VS2012. But if you have an ASP.NET MVC 4 app you can upgrade using the link below.
If you want an alert to appear after a certain about time, you can use this code:
setTimeout(function() { alert("my message"); }, time);
If you want an alert to appear and disappear after a specified interval has passed, then you're out of luck. When an alert
has fired, the browser stops processing the javascript code until the user clicks "ok". This happens again when a confirm
or prompt
is shown.
If you want the appear/disappear behavior, then I would recommend using something like jQueryUI's dialog widget. Here's a quick example on how you might use it to achieve that behavior.
var dialog = $(foo).dialog('open');
setTimeout(function() { dialog.dialog('close'); }, time);
Swift 4.2
Thank god, this solved. After setting a text to the button, you can retrieve intrinsicContentSize which is the natural size from an UIView (the official document is here). For UIButton, you can use it like below.
button.intrinsicContentSize.width
For your information, I adjusted the width to make it look properly.
button.frame = CGRect(fx: xOffset, y: 0.0, width: button.intrinsicContentSize.width + 18, height: 40)
Simulator
UIButtons with intrinsicContentSize
Source: https://riptutorial.com/ios/example/16418/get-uibutton-s-size-strictly-based-on-its-text-and-font
As MySql accepts the date in y-m-d format in date type column, you need to STR_TO_DATE
function to convert the date into yyyy-mm-dd format for insertion in following way:
INSERT INTO table_name(today)
VALUES(STR_TO_DATE('07-25-2012','%m-%d-%y'));
Similary, if you want to select the date in different format other than Mysql format, you should try DATE_FORMAT
function
SELECT DATE_FORMAT(today, '%m-%d-%y') from table_name;
It is simple.
Thats it. Hope this helps.
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();
Position Independent Code means that the generated machine code is not dependent on being located at a specific address in order to work.
E.g. jumps would be generated as relative rather than absolute.
Pseudo-assembly:
PIC: This would work whether the code was at address 100 or 1000
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP
Non-PIC: This will only work if the code is at address 100
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP
EDIT: In response to comment.
If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.
Add a double quotes outside the brackets and replace double quotes inside the {}
with \"
So: "{\"data\":{..... }"
For any sub domain request, use this:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.band\.s\.co
RewriteCond %{HTTP_HOST} ^(.*)\.band\.s\.co
RewriteCond %{REQUEST_URI} !^/([a-zA-Z0-9-z\-]+)
RewriteRule ^(.*)$ /%1/$1 [L]
Just make some folder same as sub domain name you need. Folder must be exist like this: domain.com/sub for sub.domain.com.
From here:
-Xmn : the size of the heap for the young generation
Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".
And a more "official" source from IBM:
-Xmn
Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.