Since it seems impossible to do just with symbol versioning hacks, let's go one step further and compile glibc ourselves.
This setup might work and is quick as it does not recompile the whole GCC toolchain, just glibc.
But it is not reliable as it uses host C runtime objects such as crt1.o
, crti.o
, and crtn.o
provided by glibc. This is mentioned at: https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location Those objects do early setup that glibc relies on, so I wouldn't be surprised if things crashed in wonderful and awesomely subtle ways.
For a more reliable setup, see Setup 2 below.
Build glibc and install locally:
export glibc_install="$(pwd)/glibc/build/install"
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
mkdir build
cd build
../configure --prefix "$glibc_install"
make -j `nproc`
make install -j `nproc`
test_glibc.c
#define _GNU_SOURCE
#include <assert.h>
#include <gnu/libc-version.h>
#include <stdatomic.h>
#include <stdio.h>
#include <threads.h>
atomic_int acnt;
int cnt;
int f(void* thr_data) {
for(int n = 0; n < 1000; ++n) {
++cnt;
++acnt;
}
return 0;
}
int main(int argc, char **argv) {
/* Basic library version check. */
printf("gnu_get_libc_version() = %s\n", gnu_get_libc_version());
/* Exercise thrd_create from -pthread,
* which is not present in glibc 2.27 in Ubuntu 18.04.
* https://stackoverflow.com/questions/56810/how-do-i-start-threads-in-plain-c/52453291#52453291 */
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], f, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("The atomic counter is %u\n", acnt);
printf("The non-atomic counter is %u\n", cnt);
}
Compile and run with test_glibc.sh
:
#!/usr/bin/env bash
set -eux
gcc \
-L "${glibc_install}/lib" \
-I "${glibc_install}/include" \
-Wl,--rpath="${glibc_install}/lib" \
-Wl,--dynamic-linker="${glibc_install}/lib/ld-linux-x86-64.so.2" \
-std=c11 \
-o test_glibc.out \
-v \
test_glibc.c \
-pthread \
;
ldd ./test_glibc.out
./test_glibc.out
The program outputs the expected:
gnu_get_libc_version() = 2.28
The atomic counter is 10000
The non-atomic counter is 8674
Command adapted from https://sourceware.org/glibc/wiki/Testing/Builds?action=recall&rev=21#Compile_against_glibc_in_an_installed_location but --sysroot
made it fail with:
cannot find /home/ciro/glibc/build/install/lib/libc.so.6 inside /home/ciro/glibc/build/install
so I removed it.
ldd
output confirms that the ldd
and libraries that we've just built are actually being used as expected:
+ ldd test_glibc.out
linux-vdso.so.1 (0x00007ffe4bfd3000)
libpthread.so.0 => /home/ciro/glibc/build/install/lib/libpthread.so.0 (0x00007fc12ed92000)
libc.so.6 => /home/ciro/glibc/build/install/lib/libc.so.6 (0x00007fc12e9dc000)
/home/ciro/glibc/build/install/lib/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007fc12f1b3000)
The gcc
compilation debug output shows that my host runtime objects were used, which is bad as mentioned previously, but I don't know how to work around it, e.g. it contains:
COLLECT_GCC_OPTIONS=/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crt1.o
Now let's modify glibc with:
diff --git a/nptl/thrd_create.c b/nptl/thrd_create.c
index 113ba0d93e..b00f088abb 100644
--- a/nptl/thrd_create.c
+++ b/nptl/thrd_create.c
@@ -16,11 +16,14 @@
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
+#include <stdio.h>
+
#include "thrd_priv.h"
int
thrd_create (thrd_t *thr, thrd_start_t func, void *arg)
{
+ puts("hacked");
_Static_assert (sizeof (thr) == sizeof (pthread_t),
"sizeof (thr) != sizeof (pthread_t)");
Then recompile and re-install glibc, and recompile and re-run our program:
cd glibc/build
make -j `nproc`
make -j `nproc` install
./test_glibc.sh
and we see hacked
printed a few times as expected.
This further confirms that we actually used the glibc that we compiled and not the host one.
Tested on Ubuntu 18.04.
This is an alternative to setup 1, and it is the most correct setup I've achieved far: everything is correct as far as I can observe, including the C runtime objects such as crt1.o
, crti.o
, and crtn.o
.
In this setup, we will compile a full dedicated GCC toolchain that uses the glibc that we want.
The only downside to this method is that the build will take longer. But I wouldn't risk a production setup with anything less.
crosstool-NG is a set of scripts that downloads and compiles everything from source for us, including GCC, glibc and binutils.
Yes the GCC build system is so bad that we need a separate project for that.
This setup is only not perfect because crosstool-NG does not support building the executables without extra -Wl
flags, which feels weird since we've built GCC itself. But everything seems to work, so this is only an inconvenience.
Get crosstool-NG and configure it:
git clone https://github.com/crosstool-ng/crosstool-ng
cd crosstool-ng
git checkout a6580b8e8b55345a5a342b5bd96e42c83e640ac5
export CT_PREFIX="$(pwd)/.build/install"
export PATH="/usr/lib/ccache:${PATH}"
./bootstrap
./configure --enable-local
make -j `nproc`
./ct-ng x86_64-unknown-linux-gnu
./ct-ng menuconfig
The only mandatory option that I can see, is making it match your host kernel version to use the correct kernel headers. Find your host kernel version with:
uname -a
which shows me:
4.15.0-34-generic
so in menuconfig
I do:
Operating System
Version of linux
so I select:
4.14.71
which is the first equal or older version. It has to be older since the kernel is backwards compatible.
Now you can build with:
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
and now wait for about thirty minutes to two hours for compilation.
The .config
that we generated with ./ct-ng x86_64-unknown-linux-gnu
has:
CT_GLIBC_V_2_27=y
To change that, in menuconfig
do:
C-library
Version of glibc
save the .config
, and continue with the build.
Or, if you want to use your own glibc source, e.g. to use glibc from the latest git, proceed like this:
Paths and misc options
Try features marked as EXPERIMENTAL
: set to trueC-library
Source of glibc
Custom location
: say yesCustom location
Custom source location
: point to a directory containing your glibc sourcewhere glibc was cloned as:
git clone git://sourceware.org/git/glibc.git
cd glibc
git checkout glibc-2.28
Once you have built he toolchain that you want, test it out with:
#!/usr/bin/env bash
set -eux
install_dir="${CT_PREFIX}/x86_64-unknown-linux-gnu"
PATH="${PATH}:${install_dir}/bin" \
x86_64-unknown-linux-gnu-gcc \
-Wl,--dynamic-linker="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib/ld-linux-x86-64.so.2" \
-Wl,--rpath="${install_dir}/x86_64-unknown-linux-gnu/sysroot/lib" \
-v \
-o test_glibc.out \
test_glibc.c \
-pthread \
;
ldd test_glibc.out
./test_glibc.out
Everything seems to work as in Setup 1, except that now the correct runtime objects were used:
COLLECT_GCC_OPTIONS=/home/ciro/crosstool-ng/.build/install/x86_64-unknown-linux-gnu/bin/../x86_64-unknown-linux-gnu/sysroot/usr/lib/../lib64/crt1.o
It does not seem possible with crosstool-NG, as explained below.
If you just re-build;
env -u LD_LIBRARY_PATH time ./ct-ng build CT_JOBS=`nproc`
then your changes to the custom glibc source location are taken into account, but it builds everything from scratch, making it unusable for iterative development.
If we do:
./ct-ng list-steps
it gives a nice overview of the build steps:
Available build steps, in order:
- companion_tools_for_build
- companion_libs_for_build
- binutils_for_build
- companion_tools_for_host
- companion_libs_for_host
- binutils_for_host
- cc_core_pass_1
- kernel_headers
- libc_start_files
- cc_core_pass_2
- libc
- cc_for_build
- cc_for_host
- libc_post_cc
- companion_libs_for_target
- binutils_for_target
- debug
- test_suite
- finish
Use "<step>" as action to execute only that step.
Use "+<step>" as action to execute up to that step.
Use "<step>+" as action to execute from that step onward.
therefore, we see that there are glibc steps intertwined with several GCC steps, most notably libc_start_files
comes before cc_core_pass_2
, which is likely the most expensive step together with cc_core_pass_1
.
In order to build just one step, you must first set the "Save intermediate steps" in .config
option for the intial build:
Paths and misc options
Debug crosstool-NG
Save intermediate steps
and then you can try:
env -u LD_LIBRARY_PATH time ./ct-ng libc+ -j`nproc`
but unfortunately, the +
required as mentioned at: https://github.com/crosstool-ng/crosstool-ng/issues/1033#issuecomment-424877536
Note however that restarting at an intermediate step resets the installation directory to the state it had during that step. I.e., you will have a rebuilt libc - but no final compiler built with this libc (and hence, no compiler libraries like libstdc++ either).
and basically still makes the rebuild too slow to be feasible for development, and I don't see how to overcome this without patching crosstool-NG.
Furthermore, starting from the libc
step didn't seem to copy over the source again from Custom source location
, further making this method unusable.
A bonus if you're also interested in the C++ standard library: How to edit and re-build the GCC libstdc++ C++ standard library source?
For 32-bit systems:
fprintf(stdout, "%u\n", (unsigned)time(NULL));
For 64-bit systems:
fprintf(stdout, "%lu\n", (unsigned long)time(NULL));
If you want to change it app wide, you can add the logic to your App Delegate
class AppDelegate: UIResponder, UIApplicationDelegate {
//... truncated
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// set up your background color view
let colorView = UIView()
colorView.backgroundColor = UIColor.yellowColor()
// use UITableViewCell.appearance() to configure
// the default appearance of all UITableViewCells in your app
UITableViewCell.appearance().selectedBackgroundView = colorView
return true
}
//... truncated
}
If Cells(1, 1).Formula gives a 1004 error, like in my case, changes it to:
Cells(1, 1).FormulaLocal
We can convert ararylist to array using 3 mrthod
public Object[] toArray() - it will return array of object
Object[] array = list.toArray();
public T[] toArray(T[] a) - In this way we will create array and toArray Take it as argument then return it
String[] arr = new String[list.size()];
arr = list.toArray(arr);
Public get() method;
Iterate ararylist and one by one add element in array.
For more details for these method Visit Java Vogue
I recognized those screens, I'm using CodeFluentEntities, and I've got solution that worked for me as well.
I'm using that construction:
$.ajax({
url: path,
type: "POST",
contentType: "text/plain",
data: {"some":"some"}
}
as you can see, if I use
contentType: "",
or
contentType: "text/plain", //chrome
Everything works fine.
I'm not 100% sure that it's all that you need, cause I've also changed headers.
The JAVA_HOME should point to the JDK home rather than the JRE home if you are going to be compiling stuff, likewise - I would try and install the JDK in a directory that doesn't include a space. Even if this is not your problem now, it can cause problems in the future!
You should really prefer a solution that uses java.util.concurrent
. Find and read Josh Bloch and/or Brian Goetz on the topic.
If you are not using java.util.concurrent.*
and are taking responsibility for using Threads directly, then you should probably use join()
to know when a thread is done. Here is a super simple Callback mechanism. First extend the Runnable
interface to have a callback:
public interface CallbackRunnable extends Runnable {
public void callback();
}
Then make an Executor that will execute your runnable and call you back when it is done.
public class CallbackExecutor implements Executor {
@Override
public void execute(final Runnable r) {
final Thread runner = new Thread(r);
runner.start();
if ( r instanceof CallbackRunnable ) {
// create a thread to perform the callback
Thread callerbacker = new Thread(new Runnable() {
@Override
public void run() {
try {
// block until the running thread is done
runner.join();
((CallbackRunnable)r).callback();
}
catch ( InterruptedException e ) {
// someone doesn't want us running. ok, maybe we give up.
}
}
});
callerbacker.start();
}
}
}
The other sort-of obvious thing to add to your CallbackRunnable
interface is a means to handle any exceptions, so maybe put a public void uncaughtException(Throwable e);
line in there and in your executor, install a Thread.UncaughtExceptionHandler to send you to that interface method.
But doing all that really starts to smell like java.util.concurrent.Callable
. You should really look at using java.util.concurrent
if your project permits it.
As Alex Gray points out in a comment above, "all of the corresponding IDs are actually on the extensions page within the browser".
However, you must click the Developer Mode checkbox at top of Extensions page to see them.
You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step
geekswithblogs.net/anirugu/archive/2013/11/04/how-to-downgrade-razor-3-and-fix-the-issue-that.aspx
Using brew
First install brew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And then install wget with brew:
brew install wget
Using MacPorts
First, download and run MacPorts installer (.pkg)
And then install wget:
sudo port install wget
Go to:
res > drawable > right click > show in folder > add desired logo
Then go to android manifest, edit ICON tag under application tag, use "@drawable/nameOfImage"
Overhead is simply the more time consumption in program execution. Example ; when we call a function and its control is passed where it is defined and then its body is executed, this means that we make our CPU to run through a long process( first passing the control to other place in memory and then executing there and then passing the control back to the former position) , consequently it takes alot performance time, hence Overhead. Our goals are to reduce this overhead by using the inline during function definition and calling time, which copies the content of the function at the function call hence we dont pass the control to some other location, but continue our program in a line, hence inline.
How about:
StringBuilder builder = new StringBuilder();
for(int i=99;i>=0;i--){
builder.append(Integer.toString(i));
}
builder.toString();
OR
StringBuilder builder = new StringBuilder();
for(int i=0;i<100;i++){
builder.insert(0, Integer.toString(i));
}
builder.toString();
But with this, you are making the operation O(N^2) instead of O(N).
Snippet from java docs:
Inserts the string representation of the Object argument into this character sequence. The overall effect is exactly as if the second argument were converted to a string by the method
String.valueOf(Object)
, and the characters of that string were then inserted into this character sequence at the indicated offset.
I used the content+wrapper
approach ... but I did something different than mentioned so far: I made sure that my wrapper's boundaries did NOT line up with the content's boundaries in the direction that I wanted to be visible.
Important NOTE: It was easy enough to get the content+wrapper, same-bounds
approach to work on one browser or another depending on various css combinations of position
, overflow-*
, etc ... but I never could use that approach to get them all correct (Edge, Chrome, Safari, ...).
But when I had something like:
<div id="hack_wrapper" // created solely for this purpose
style="position:absolute; width:100%; height:100%; overflow-x:hidden;">
<div id="content_wrapper"
style="position:absolute; width:100%; height:15%; overflow:visible;">
... content with too-much horizontal content ...
</div>
</div>
... all browsers were happy.
laravel 5.8
If you don't even need an entire row, you may extract a single value from a record using the value()
method. This method will return the value of the column directly:
$first_name = DB::table('users')->where('email' ,'me@mail,com')->value('first_name');
check docs
My professor used to say something like: using global variables are okay if you use them correctly. I don't think I ever got good at using them correctly, so I rarely used them at all.
All your classes are internal
by default
Marking public
did not do the trick.
Are you sure you do not have two classes named Method, and perhaps are including the wrong Method class?
Yes. Take a look at this other thread for details: How to apply CSS to iframe?
var cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['frame1'].document.body.appendChild(cssLink);
A reboot prevents it from opening the dialog.
I had the same problem, with data that only occasionally double-quotes some text. My solution is to let the BULK LOAD import the double-quotes, then run a REPLACE on the imported data.
For example:
bulk insert CodePoint_tbl from "F:\Data\Map\CodePointOpen\Data\CSV\ab.csv" with (FIRSTROW = 1, FIELDTERMINATOR = ',', ROWTERMINATOR='\n');
update CodePoint_tbl set Postcode = replace(Postcode,'"','') where charindex('"',Postcode) > 0
To make it less painful to write the REPLACE script, just copy and paste what you need from the results of something like this:
select C.ColID, C.[name] as Columnname into #Columns
from syscolumns C
join sysobjects T on C.id = T.id
where T.[name] = 'User_tbl'
order by 1;
declare @QUOTE char(1);
set @QUOTE = Char(39);
select 'Update User_tbl set '+ColumnName+'=replace('+ColumnName+','
+ @QUOTE + '"' + @QUOTE + ',' + @QUOTE + @QUOTE + ');
GO'
from #Columns
where ColID > 2
order by ColID;
The best approach from the response of Khemraj:
App class
class App : Application() {
companion object {
lateinit var instance: Application
lateinit var resourses: Resources
}
// MARK: - Lifecycle
override fun onCreate() {
super.onCreate()
instance = this
resourses = resources
}
}
Declaration in the manifest
<application
android:name=".App"
...>
</application>
Constants class
class Localizations {
companion object {
val info = App.resourses.getString(R.string.info)
}
}
Using
textView.text = Localizations.info
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxy.somewhere.com</host>
<port>8080</port>
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
</proxy>
</proxies>
</settings>
Window > Preferences > Maven > User Settings
It is possible to achieve this without having to modify each page individually (adding a 'current' class to a specific link), but still without JS or a server-side script. This uses the :target pseudo selector, which relies on #someid
appearing in the addressbar.
<!DOCTYPE>
<html>
<head>
<title>Some Title</title>
<style>
:target {
background-color: yellow;
}
</style>
</head>
<body>
<ul>
<li><a id="news" href="news.html#news">News</a></li>
<li><a id="games" href="games.html#games">Games</a></li>
<li><a id="science" href="science.html#science">Science</a></li>
</ul>
<h1>Stuff about science</h1>
<p>lorem ipsum blah blah</p>
</body>
</html>
There are a couple of restrictions:
As long as any links to these pages include the id, and the navbar is at the top, it shouldn't be a problem.
Other in-page links (bookmarks) will also cause the colour to be lost.
Like this:
document.getElementById('myTextarea').value = '';
or like this in jQuery:
$('#myTextarea').val('');
Where you have
<textarea id="myTextarea" name="something">This text gets removed</textarea>
For all the downvoters and non-believers:
value Property: Retrieves or sets the text in the entry field of the textArea element.
value DOMString The raw value contained in the control.
SOAP is an ill-suited technology for use on Android (or mobile devices in general) because of the processing/parsing overhead that's required. A REST services is a lighter weight solution and that's what I would suggest. Android comes with a SAX parser, and it's fairly trivial to use. If you are absolutely required to handle/parse SOAP on a mobile device then I feel sorry for you, the best advice I can offer is just not to use SOAP.
Git 1.7.2 introduced the ability to cherry pick a range of commits. From the release notes:
git cherry-pick
learned to pick a range of commits (e.g.cherry-pick A..B
andcherry-pick --stdin
), so didgit revert
; these do not support the nicer sequencing controlrebase [-i]
has, though.
To cherry-pick all the commits from commit A
to commit B
(where A
is older than B
), run:
git cherry-pick A^..B
If you want to ignore A itself, run:
git cherry-pick A..B
(Credit goes to damian, J. B. Rainsberger and sschaef in the comments)
Simpler with OUT
parameters:
CREATE OR REPLACE FUNCTION get_object_fields(_school_id int
, OUT user1_id int
, OUT user1_name varchar(32)
, OUT user2_id int
, OUT user2_name varchar(32)) AS
$func$
BEGIN
SELECT INTO user1_id, user1_name
u.id, u.name
FROM users u
WHERE u.school_id = _school_id
LIMIT 1; -- make sure query returns 1 row - better in a more deterministic way?
user2_id := user1_id + 1; -- some calculation
SELECT INTO user2_name
u.name
FROM users u
WHERE u.id = user2_id;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM get_object_fields(1);
You don't need to create a type just for the sake of this plpgsql function. It may be useful if you want to bind multiple functions to the same composite type. Else, OUT
parameters do the job.
There is no RETURN
statement. OUT
parameters are returned automatically with this form that returns a single row. RETURN
is optional.
Since OUT
parameters are visible everywhere inside the function body (and can be used just like any other variable), make sure to table-qualify columns of the same name to avoid naming conflicts! (Better yet, use distinct names to begin with.)
Typically, this can be simpler and faster if queries in the function body can be combined. And you can use RETURNS TABLE()
(since Postgres 8.4, long before the question was asked) to return 0-n rows.
The example from above can be written as:
CREATE OR REPLACE FUNCTION get_object_fields2(_school_id int)
RETURNS TABLE (user1_id int
, user1_name varchar(32)
, user2_id int
, user2_name varchar(32)) AS
$func$
BEGIN
RETURN QUERY
SELECT u1.id, u1.name, u2.id, u2.name
FROM users u1
JOIN users u2 ON u2.id = u1.id + 1
WHERE u1.school_id = _school_id
LIMIT 1; -- may be optional
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM get_object_fields2(1);
RETURNS TABLE
is effectively the same as having a bunch of OUT
parameters combined with RETURNS SETOF record
, just shorter.
The major difference: this function can return 0, 1 or many rows, while the first version always returns 1 row.
Add LIMIT 1
like demonstrated to only allow 0 or 1 row.
RETURN QUERY
is simple way to return results from a query directly.
You can use multiple instances in a single function to add more rows to the output.
db<>fiddle here (demonstrating both)
If your function is supposed to dynamically return results with a different row-type depending on the input, read more here:
If you want to read CSV file with some lines, so this the solution.
while IFS=, read -ra line
do
test $i -eq 1 && ((i=i+1)) && continue
for col_val in ${line[@]}
do
echo -n "$col_val|"
done
echo
done < "$csvFile"
This is very simple script to do what you are asking for ! try this:
#!/usr/bin/env python3
def remove(string):
return string.replace(" ", "")
dict = {'a': '1',
'b': '2',
'c': '3',
'd': '4',
'e': '5',
'f': '6',
'g': '7',
'h': '8',
'i': '9',
'j': '10',
'k': '11',
'l': '12',
'm': '13',
'n': '14',
'o': '15',
'p': '16',
'q': '17',
'r': '18',
's': '19',
't': '20',
'u': '21',
'v': '22',
'w': '23',
'x': '24',
'y': '25',
'z': '26',
}
word = remove(input(''))
for x in word:
print(dict[x])
## or ##
#index = 0
#for x in word:
# print(dict[word[index]])
# index = index + 1
I was able to accomplish editing the default.aspx
page by:
By doing that I was able to remove the tagprefix causing a problem on my page.
This is the long form of the Java commands that can be run from a Windows command prompt:
"C:\Program Files\Java\jdk1.6.0_18\bin\javac.exe" -classpath "C:\Users\Scott\workspace\myproject" com\mycompany\myapp\HelloWorld.java
"C:\Program Files\Java\jdk1.6.0_18\bin\java.exe" -classpath "C:\Users\Scott\workspace\myproject" com.mycompany.myapp.HelloWorld
Notice the classpath has no slash at the end. The javac.exe commands expects the file to end with ".java". The java.exe command expects the full class name and does not end with ".class".
There are a few ways to simplify these commands:
You don't have to enter the entire classpath (ie, you can just use -classpath "."). Enter the directory you will be working in:
cd "C:\Users\Scott\workspace\myproject\"
You can use the default package (put the HelloWorld.java file directory in your working directory and don't use the Java package directive)
If you make these changes you would run something like this (and you might be able to leave out -classpath "."):
cd "C:\Users\Scott\workspace\myproject\"
javac -classpath "." HelloWorld.java
java -classpath "." HelloWorld
The second table cannot include the table name in the ORDER BY
clause.
So...
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY field1
Does not throw an exception
In addition to border-radius: 0
, add -webkit-appearance: none;
.
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()
I was able to get it to work in IE and FF with jQuery's:
$(window).bind('beforeunload', function(){
});
instead of: unload, onunload, or onbeforeunload
For occasional appends, you can use appendFile
, which creates a new file handle each time it's called:
const fs = require('fs');
fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('Saved!');
});
const fs = require('fs');
fs.appendFileSync('message.txt', 'data to append');
But if you append repeatedly to the same file, it's much better to reuse the file handle.
You could use a classmethod
or staticmethod
class Paul(object):
elems = []
@classmethod
def addelem(cls, e):
cls.elems.append(e)
@staticmethod
def addelem2(e):
Paul.elems.append(e)
Paul.addelem(1)
Paul.addelem2(2)
print(Paul.elems)
classmethod
has advantage that it would work with sub classes, if you really wanted that functionality.
module is certainly best though.
i think the setTimeout function that you write is not being run. if you use jquery, you can make it run correctly by doing this :
function alertMsg() {
//your func
}
$(document).ready(function() {
setTimeout(alertMsg,3000);
// the function you called by setTimeout must not be a string.
});
If you need to get the count of the entire result set you can take following approach:
SELECT SQL_CALC_FOUND_ROWS * FROM table_name LIMIT 5;
SELECT FOUND_ROWS();
This isn't normally faster than using COUNT
albeit one might think the opposite is the case because it's doing the calculation internally and doesn't send the data back to the user thus the performance improvement is suspected.
Doing these two queries is good for pagination for getting totals but not particularly for using WHERE
clauses.
To answer the original question:
HTMLDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(fileText);
// now use doc
Then to convert back to a string:
doc.documentElement.outerHTML;
My solution if your ng-grid depend of element parent(div, layout) :
directive
myapp.directive('sizeelement', function ($window) {
return{
scope:true,
priority: 0,
link: function (scope, element) {
scope.$watch(function(){return $(element).height(); }, function(newValue, oldValue) {
scope.height=$(element).height();
});
}}
})
sample html
<div class="portlet box grey" style="height: 100%" sizeelement>
<div class="portlet-title">
<h4><i class="icon-list"></i>Articles</h4>
</div>
<div class="portlet-body" style="height:{{height-34}}px">
<div class="gridStyle" ng-grid="gridOrderLine" ="min-height: 250px;"></div>
</div>
</div>
height-34 : 34 is fix height of my title div, you can fix other height.
It is easy directive but it work fine.
AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.
So, you really can't make stuff that expects a file accept an asset 'file'.
Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:
File f = new File(getCacheDir()+"/m1.map");
if (!f.exists()) try {
InputStream is = getAssets().open("m1.map");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
mapView.setMapFile(f.getPath());
If its simply from float64 to int, this should work
package main
import (
"fmt"
)
func main() {
nf := []float64{-1.9999, -2.0001, -2.0, 0, 1.9999, 2.0001, 2.0}
//round
fmt.Printf("Round : ")
for _, f := range nf {
fmt.Printf("%d ", round(f))
}
fmt.Printf("\n")
//rounddown ie. math.floor
fmt.Printf("RoundD: ")
for _, f := range nf {
fmt.Printf("%d ", roundD(f))
}
fmt.Printf("\n")
//roundup ie. math.ceil
fmt.Printf("RoundU: ")
for _, f := range nf {
fmt.Printf("%d ", roundU(f))
}
fmt.Printf("\n")
}
func roundU(val float64) int {
if val > 0 { return int(val+1.0) }
return int(val)
}
func roundD(val float64) int {
if val < 0 { return int(val-1.0) }
return int(val)
}
func round(val float64) int {
if val < 0 { return int(val-0.5) }
return int(val+0.5)
}
Outputs:
Round : -2 -2 -2 0 2 2 2
RoundD: -2 -3 -3 0 1 2 2
RoundU: -1 -2 -2 0 2 3 3
Here's the code in the playground - https://play.golang.org/p/HmFfM6Grqh
In my case I was using XAMPP, and there was a log that told me the error. To find it, go to the XAMPP control panel, and click "Configure" for MySQL, then click on "Open Log."
The most current data of the log is at the bottom, and the log is organized by date, time, some number, and text in brackets that may say "Note" or "Error." One that says "Error" is likely causing the issue.
For me, my error was a tablespace that was causing an issue, so I deleted the database files at the given location.
Note: The tablespace files for your installation of XAMPP may be at a different location, but they were in /opt/lampp/var/mysql
for me. I think that's typical of XAMPP on Debian-based distributions. Also, my instructions on what to click in the control panel to see the log may be a bit different for you because I'm running XAMPP on an Ubuntu-based distribution of Linux (Feren OS).
Use the command dir
to list all the directories and files in a directory; ls
is a unix command.
find /path/to/ -type f -print0 | xargs -0 file | grep -i image
This uses the file
command to try to recognize the type of file, regardless of filename (or extension).
If /path/to
or a filename contains the string image
, then the above may return bogus hits. In that case, I'd suggest
cd /path/to
find . -type f -print0 | xargs -0 file --mime-type | grep -i image/
I know the Q is not about Firefox
but I did not want to add a copy of this question to just answer it myself.
For Firefox you need to add debugger;
to be able to do what @matt-ball suggested for the script
tag.
So on your code, you add debugger
above the line you want to debug and then you can add breakpoints. If you just set the breakpoints on the browser it won't stop.
If this is not the place to add a Firefox answer given that the question is about Chrome. Don't :( minus the answer just let me know where I should post it and I'll happily move the post. :)
If you wish to see all changes made in commits that changed a particular file (rather than just the changes to the file itself), you can pass --full-diff
:
git log -p --full-diff [branch] -- <path>
Try like this:
from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
return Response(xml, mimetype='text/xml')
The actual Content-Type is based on the mimetype parameter and the charset (defaults to UTF-8).
Response (and request) objects are documented here: http://werkzeug.pocoo.org/docs/wrappers/
In order to get the value
of any input field, you should always use $element.val()
because jQuery
handles to retrieve the correct value based on the browser of the element type.
Just clear the plots and try executing the code again...It worked for me
An addition to the solution by @Rafael Teles. The syntactic sugar Collectors.mapping
does the same in one step:
//...
List<Employee> employees = persons.stream()
.filter(p -> p.getLastName().equals("l1"))
.collect(
Collectors.mapping(
p -> new Employee(p.getName(), p.getLastName(), 1000),
Collectors.toList()));
Detailed example can be found here
You can use length to see if your selector matched anything.
if ($('#MyId').length) {
// do your stuff
}
Cellpadding
is the amount of space between the outer edges of the
table cell and the content of the cell.
Cellspacing
is the amount of space in between the individual table cells.
More Details *Link 1*
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>
You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
This seems to be a good solution also, taken from a great blog post
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from lxml import html
#Take this class for granted.Just use result of rendering.
class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
url = 'http://pycoders.com/archive/'
r = Render(url)
result = r.frame.toHtml()
# This step is important.Converting QString to Ascii for lxml to process
# The following returns an lxml element tree
archive_links = html.fromstring(str(result.toAscii()))
print archive_links
# The following returns an array containing the URLs
raw_links = archive_links.xpath('//div[@class="campaign"]/a/@href')
print raw_links
TL;DR:
Using slicing:
>>> import numpy as np
>>>
>>> arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
>>>
>>> arr[0,0]
1
>>> arr[1,1]
7
>>> arr[1,0]
6
>>> arr[1,-1]
10
>>> arr[1,-2]
9
In Long:
Hopefully this helps in your understanding:
>>> import numpy as np
>>> np.array([ [1,2,3], [4,5,6] ])
array([[1, 2, 3],
[4, 5, 6]])
>>> x = np.array([ [1,2,3], [4,5,6] ])
>>> x[1][2] # 2nd row, 3rd column
6
>>> x[1,2] # Similarly
6
But to appreciate why slicing is useful, in more dimensions:
>>> np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
>>> x = np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
>>> x[1][0][2] # 2nd matrix, 1st row, 3rd column
9
>>> x[1,0,2] # Similarly
9
>>> x[1][0:2][2] # 2nd matrix, 1st row, 3rd column
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index 2 is out of bounds for axis 0 with size 2
>>> x[1, 0:2, 2] # 2nd matrix, 1st and 2nd row, 3rd column
array([ 9, 12])
>>> x[1, 0:2, 1:3] # 2nd matrix, 1st and 2nd row, 2nd and 3rd column
array([[ 8, 9],
[11, 12]])
//In .net MVC
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult FareListInfo(long id)
{
}
// In .net webform
<%@ OutputCache NoStore="true" Duration="0" VaryByParam="*" %>
Try this:
function btnClick() {
var x = document.getElementById("mytable").getElementsByTagName("td");
x[0].innerHTML = "i want to change my cell color";
x[0].style.backgroundColor = "yellow";
}
Set from JS, backgroundColor
is the equivalent of background-color
in your style-sheet.
Note also that the .cells
collection belongs to a table row, not to the table itself. To get all the cells from all rows you can instead use getElementsByTagName()
.
I know this is a bit old but I think there might be a much simpler solution that requires no additional coding:
Instead of transposing, redimming and transposing again, and if we talk about a two dimensional array, why not just store the values transposed to begin with. In that case redim preserve actually increases the right (second) dimension from the start. Or in other words, to visualise it, why not store in two rows instead of two columns if only the nr of columns can be increased with redim preserve.
the indexes would than be 00-01, 01-11, 02-12, 03-13, 04-14, 05-15 ... 0 25-1 25 etcetera instead of 00-01, 10-11, 20-21, 30-31, 40-41 etcetera.
As only the second (or last) dimension can be preserved while redimming, one could maybe argue that this is how arrays are supposed to be used to begin with. I have not seen this solution anywhere so maybe I'm overlooking something?
Change the web.config of WCF service as "endpoint address="" binding="basicHttpBinding"..." (previously binding="wsHttpBinding")After build the app, in "ServiceReferences.ClientConfig" ""configuration> has the value. Then it will work fine.
If another function needs to use a variable you pass it to the function as an argument.
Also global variables are not inherently nasty and evil. As long as they are used properly there is no problem with them.
You can redirect by this method also:
return Yii::$app->response->redirect(['user/index', 'id' => 10]);
If you want to send the Header information immediately use with send().This method adds a Location header to the current response.
return Yii::$app->response->redirect(['user/index', 'id' => 10])->send();
If you want the complete URL then use like Url::to(['user/index', 'id' => 302])
with the header of use yii\helpers\Url;
.
For more information check Here. Hope this will help someone.
If you want to do this to an inline svg that is, for example, a background image in your css:
background: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='rgba(31,159,215,1)' viewBox='...'/%3E%3C/svg%3E");
_x000D_
of course, replace the ... with your inline image code
Session class has been removed on SDK 4.0. The login magement is done through the class LoginManager. So:
mLoginManager = LoginManager.getInstance();
mLoginManager.logOut();
As the reference Upgrading to SDK 4.0 says:
Session Removed - AccessToken, LoginManager and CallbackManager classes supercede and replace functionality in the Session class.
From the docs:
urllib.quote(string[, safe])
Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'
That means passing '' for safe will solve your first issue:
>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'
About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:
>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller
By the way have a look at urlencode
The same, except replace urllib.quote
with urllib.parse.quote
.
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
$destroy
can refer to 2 things: method and event
.directive("colorTag", function(){
return {
restrict: "A",
scope: {
value: "=colorTag"
},
link: function (scope, element, attrs) {
var colors = new App.Colors();
element.css("background-color", stringToColor(scope.value));
element.css("color", contrastColor(scope.value));
// Destroy scope, because it's no longer needed.
scope.$destroy();
}
};
})
See @SunnyShah's answer.
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;
You pretty much can't set the value of found. Debugging optimized programs is rarely worth the trouble, the compiler can rearrange the code in ways that it'll in no way correspond to the source code (other than producing the same result), thus confusing debuggers to no end.
You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.
var width = $(window).width();
var height = $(window).height();
Assuming you have: JQuery framework.
First, add these hidden form inputs to store the width and height until postback.
<asp:HiddenField ID="width" runat="server" />
<asp:HiddenField ID="height" runat="server" />
Next we want to get the window (viewport) width and height. JQuery has two methods for this, aptly named width() and height().
Add the following code to your .aspx file within the head element.
<script type="text/javascript">
$(document).ready(function() {
$("#width").val() = $(window).width();
$("#height").val() = $(window).height();
});
</script>
Result
This will result in the width and height of the browser window being available on postback. Just access the hidden form inputs like this:
var TheBrowserWidth = width.Value;
var TheBrowserHeight = height.Value;
This method provides the height and width upon postback, but not on the intial page load.
Note on UpdatePanels: If you are posting back via UpdatePanels, I believe the hidden inputs need to be within the UpdatePanel.
Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.
Update for jquery 3.1.1
I had to change the JavaScript to:
$("#width").val($(window).width());
$("#height").val($(window).height());
If you know they are strings, then there's no need to check for type.
"a" == "b"
However, note that string objects will not be equal.
new String("a") == new String("a")
will return false.
Call the valueOf() method to convert it to a primitive for String objects,
new String("a").valueOf() == new String("a").valueOf()
will return true
Check your font's css file. (fontawesome.css/fontawesome.min.css), you will see like this:
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot-v=4.6.3.htm');
src: url('../fonts/fontawesome-webfont.eot#iefix-v=4.6.3') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2-v=4.6.3.htm') format('woff2'), url('../fonts/fontawesome-webfont.woff-v=4.6.3.htm') format('woff'), url('../fonts/fontawesome-webfont.ttf-v=4.6.3.htm') format('truetype'), url('../fonts/fontawesome-webfont.svg-v=4.6.3.htm#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal
}
you will see version tag after your font's file extension name. Like:
-v=4.6.3
You just need to remove this tag from your css file. After removing this, you need to go to your fonts folder, And you will see:
And, Form these font's files, you just need to remove the version tag -v=4.6.3 from the file name.
Then, The problem will be sloved.
select * from sys.dm_tcp_listener_states
Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type.
boolean b1;
Boolean b2;
b1
and b2
are not same.
In ES2015 a.k.a ES6, class
is a syntactic sugar for functions
.
If you want to force to set a context for this
you can use bind()
method. As @chetan pointed, on invocation you can set the context as well! Check the example below:
class Form extends React.Component {
constructor() {
super();
}
handleChange(e) {
switch (e.target.id) {
case 'owner':
this.setState({owner: e.target.value});
break;
default:
}
}
render() {
return (
<form onSubmit={this.handleNewCodeBlock}>
<p>Owner:</p> <input onChange={this.handleChange.bind(this)} />
</form>
);
}
}
Here we forced the context inside handleChange()
to Form
.
Here is a static class implementing Start(), Stop(), and IsStarted() for IISExpress. It is parametrized by hard-coded static properties and passes invocation information via the command-line arguments to IISExpress. It uses the Nuget package, MissingLinq.Linq2Management, which surprisingly provides information missing from System.Diagnostics.Process, specifically, the command-line arguments that can then be used to help disambiguate possible multiple instances of IISExpress processes, since I don't preserve the process Ids. I presume there is a way to accomplish the same thing with just System.Diagnostics.Process, but life is short. Enjoy.
using System.Diagnostics;
using System.IO;
using System.Threading;
using MissingLinq.Linq2Management.Context;
using MissingLinq.Linq2Management.Model.CIMv2;
public static class IisExpress
{
#region Parameters
public static string SiteFolder = @"C:\temp\UE_Soln_7\Spc.Frm.Imp";
public static uint Port = 3001;
public static int ProcessStateChangeDelay = 10 * 1000;
public static string IisExpressExe = @"C:\Program Files (x86)\IIS Express\iisexpress.exe";
#endregion
public static void Start()
{
Process.Start(InvocationInfo);
Thread.Sleep(ProcessStateChangeDelay);
}
public static void Stop()
{
var p = GetWin32Process();
if (p == null) return;
var pp = Process.GetProcessById((int)p.ProcessId);
if (pp == null) return;
pp.Kill();
Thread.Sleep(ProcessStateChangeDelay);
}
public static bool IsStarted()
{
var p = GetWin32Process();
return p != null;
}
static readonly string ProcessName = Path.GetFileName(IisExpressExe);
static string Quote(string value) { return "\"" + value.Trim() + "\""; }
static string CmdLine =
string.Format(
@"/path:{0} /port:{1}",
Quote(SiteFolder),
Port
);
static readonly ProcessStartInfo InvocationInfo =
new ProcessStartInfo()
{
FileName = IisExpressExe,
Arguments = CmdLine,
WorkingDirectory = SiteFolder,
CreateNoWindow = false,
UseShellExecute = true,
WindowStyle = ProcessWindowStyle.Minimized
};
static Win32Process GetWin32Process()
{
//the linq over ManagementObjectContext implementation is simplistic so we do foreach instead
using (var mo = new ManagementObjectContext())
foreach (var p in mo.CIMv2.Win32Processes)
if (p.Name == ProcessName && p.CommandLine.Contains(CmdLine))
return p;
return null;
}
}
The answer with highest votes (I have not enough reputation to add comment there) suggests to comment out the MVG line, but have in mind this:
CVE-2016-3714
ImageMagick supports ".svg/.mvg" files which means that attackers can craft code in a scripting language, e.g. MSL (Magick Scripting Language) and MVG (Magick Vector Graphics), upload it to a server disguised as an image file and force the software to run malicious commands on the server side as described above. For example adding the following commands in a file and uploading it to a webserver that uses a vulnerable ImageMagick version will result in running the command "ls -la" on the server.
exploit.jpg:
push graphic-context viewbox 0 0 640 480 fill 'url(https://website.com/image.png"|ls "-la)' pop graphic-context
And
Any version below 7.0.1-2 or 6.9.4-0 is potentially vulnerable and affected parties should as soon as possible upgrade to the latest ImageMagick version.
You should post a message from frame to parent, after loaded.
frame script:
$(document).ready(function() {
window.parent.postMessage("I'm loaded", "*");
});
And listen it in parent:
function listenMessage(msg) {
alert(msg);
}
if (window.addEventListener) {
window.addEventListener("message", listenMessage, false);
} else {
window.attachEvent("onmessage", listenMessage);
}
Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging
This was much less complicated for the requirements I needed. Hope this might help:
On the MainActivity:
public void dismissKeyboard(){
InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mSearchBox.getWindowToken(), 0);
mKeyboardStatus = false;
}
public void showKeyboard(){
InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
mKeyboardStatus = true;
}
private boolean isKeyboardActive(){
return mKeyboardStatus;
}
The default primative boolean value for mKeyboardStatus will be initialized to false.
Then check the value as follows, and perform an action if necessary:
mSearchBox.requestFocus();
if(!isKeyboardActive()){
showKeyboard();
}else{
dismissKeyboard();
}
This should clear your applications cache which should be where your webview cache is
File dir = getActivity().getCacheDir();
if (dir != null && dir.isDirectory()) {
try {
File[] children = dir.listFiles();
if (children.length > 0) {
for (int i = 0; i < children.length; i++) {
File[] temp = children[i].listFiles();
for (int x = 0; x < temp.length; x++) {
temp[x].delete();
}
}
}
} catch (Exception e) {
Log.e("Cache", "failed cache clean");
}
}
Here are several options for getting the "tail" items of an iterable:
Given
n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Desired Output
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Code
We get the latter output using any of the following options:
from collections import deque
import itertools
import more_itertools
# A: Slicing
iterable[-n:]
# B: Implement an itertools recipe
def tail(n, iterable):
"""Return an iterator over the last *n* items of *iterable*.
>>> t = tail(3, 'ABCDEFG')
>>> list(t)
['E', 'F', 'G']
"""
return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))
# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))
# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))
# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))
Details
iter(iterable)
. itertools
recipe. It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools
module.more_itertools
(install via > pip install more-itertools
); see more_itertools.tail
.itertools
library. Note, itertools.islice
does not support negative slicing. more_itertools
that generalizes itertools.islice
to support negative slicing; see more_itertools.islice_extended
.Which one do I use?
It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.
Null is not a 'problem'. It is an integral part of a complete modeling tool set. Software aims to model the complexity of the world and null bears its burden. Null indicates 'No data' or 'Unknown' in Java and the like. So it is appropriate to use nulls for these purposes. I don't prefer the 'Null object' pattern; I think it rise the 'who will guard
the guardians' problem.
If you ask me what is the name of my girlfriend I'll tell you that I have no girlfriend. In the Java language I'll return null.
An alternative would be to throw meaningful exception to indicate some problem that can't be (or don't want to be) solved right there and delegate it somewhere higher in the stack to retry or report data access error to the user.
For an 'unknown question' give 'unknown answer'. (Be null-safe where this is correct from business point of view) Checking arguments for null once inside a method before usage relieves multiple callers from checking them before a call.
public Photo getPhotoOfThePerson(Person person) {
if (person == null)
return null;
// Grabbing some resources or intensive calculation
// using person object anyhow.
}
Previous leads to normal logic flow to get no photo of a non-existent girlfriend from my photo library.
getPhotoOfThePerson(me.getGirlfriend())
And it fits with new coming Java API (looking forward)
getPhotoByName(me.getGirlfriend()?.getName())
While it is rather 'normal business flow' not to find photo stored into the DB for some person, I used to use pairs like below for some other cases
public static MyEnum parseMyEnum(String value); // throws IllegalArgumentException
public static MyEnum parseMyEnumOrNull(String value);
And don't loathe to type <alt> + <shift> + <j>
(generate javadoc in Eclipse) and write three additional words for you public API. This will be more than enough for all but those who don't read documentation.
/**
* @return photo or null
*/
or
/**
* @return photo, never null
*/
This is rather theoretical case and in most cases you should prefer java null safe API (in case it will be released in another 10 years), but NullPointerException
is subclass of an Exception
. Thus it is a form of Throwable
that indicates conditions that a reasonable application might want to catch (javadoc)! To use the first most advantage of exceptions and separate error-handling code from 'regular' code (according to creators of Java) it is appropriate, as for me, to catch NullPointerException
.
public Photo getGirlfriendPhoto() {
try {
return appContext.getPhotoDataSource().getPhotoByName(me.getGirlfriend().getName());
} catch (NullPointerException e) {
return null;
}
}
Questions could arise:
Q. What if getPhotoDataSource()
returns null?
A. It is up to business logic. If I fail to find a photo album I'll show you no photos. What if appContext is not initialized? This method's business logic puts up with this. If the same logic should be more strict then throwing an exception it is part of the business logic and explicit check for null should be used (case 3). The new Java Null-safe API fits better here to specify selectively what implies and what does not imply to be initialized to be fail-fast in case of programmer errors.
Q. Redundant code could be executed and unnecessary resources could be grabbed.
A. It could take place if getPhotoByName()
would try to open a database connection, create PreparedStatement
and use the person name as an SQL parameter at last. The approach for an unknown question gives an unknown answer (case 1) works here. Before grabbing resources the method should check parameters and return 'unknown' result if needed.
Q. This approach has a performance penalty due to the try closure opening.
A. Software should be easy to understand and modify firstly. Only after this, one could think about performance, and only if needed! and where needed! (source), and many others).
PS. This approach will be as reasonable to use as the separate error-handling code from "regular" code principle is reasonable to use in some place. Consider the next example:
public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
try {
Result1 result1 = performSomeCalculation(predicate);
Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
Result3 result3 = performThirdCalculation(result2.getSomeProperty());
Result4 result4 = performLastCalculation(result3.getSomeProperty());
return result4.getSomeProperty();
} catch (NullPointerException e) {
return null;
}
}
public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
SomeValue result = null;
if (predicate != null) {
Result1 result1 = performSomeCalculation(predicate);
if (result1 != null && result1.getSomeProperty() != null) {
Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
if (result2 != null && result2.getSomeProperty() != null) {
Result3 result3 = performThirdCalculation(result2.getSomeProperty());
if (result3 != null && result3.getSomeProperty() != null) {
Result4 result4 = performLastCalculation(result3.getSomeProperty());
if (result4 != null) {
result = result4.getSomeProperty();
}
}
}
}
}
return result;
}
PPS. For those fast to downvote (and not so fast to read documentation) I would like to say that I've never caught a null-pointer exception (NPE) in my life. But this possibility was intentionally designed by the Java creators because NPE is a subclass of Exception
. We have a precedent in Java history when ThreadDeath
is an Error
not because it is actually an application error, but solely because it was not intended to be caught! How much NPE fits to be an Error
than ThreadDeath
! But it is not.
Check for 'No data' only if business logic implies it.
public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
if (personId == null)
return;
DataSource dataSource = appContext.getStuffDataSource();
Person person = dataSource.getPersonById(personId);
if (person != null) {
person.setPhoneNumber(phoneNumber);
dataSource.updatePerson(person);
} else {
Person = new Person(personId);
person.setPhoneNumber(phoneNumber);
dataSource.insertPerson(person);
}
}
and
public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
if (personId == null)
return;
DataSource dataSource = appContext.getStuffDataSource();
Person person = dataSource.getPersonById(personId);
if (person == null)
throw new SomeReasonableUserException("What are you thinking about ???");
person.setPhoneNumber(phoneNumber);
dataSource.updatePerson(person);
}
If appContext or dataSource is not initialized unhandled runtime NullPointerException will kill current thread and will be processed by Thread.defaultUncaughtExceptionHandler (for you to define and use your favorite logger or other notification mechanizm). If not set, ThreadGroup#uncaughtException will print stacktrace to system err. One should monitor application error log and open Jira issue for each unhandled exception which in fact is application error. Programmer should fix bug somewhere in initialization stuff.
It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
I have tried your example and it works just fine:
var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();
$http({
url: '/api/test',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
data: {application: app, from: d1, to: d2}
});
Output:
Content-Length:91
Content-Type:application/json
Host:localhost:1234
Origin:http://localhost:1234
Referer:http://localhost:1234/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
{"application":"AirFare","from":"2013-10-10T11:47:50.681Z","to":"2013-10-10T11:47:50.681Z"}
Are you using the latest version of AngularJS?
Now I solved this issue in this way,
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.OutputStream;
// Create a trust manager that does not validate certificate chains like the
default TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//No need to implement.
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
System.out.println(e);
}
.reduce((o,v,i)=>(o[i]=v,o), {})
[docs]
or more verbose
var trAr2Obj = function (arr) {return arr.reduce((o,v,i)=>(o[i]=v,o), {});}
or
var transposeAr2Obj = arr=>arr.reduce((o,v,i)=>(o[i]=v,o), {})
shortest one with vanilla JS
JSON.stringify([["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[i]=v,o}, {}))
=> "{"0":["a","X"],"1":["b","Y"]}"
some more complex example
[["a", "X"], ["b", "Y"]].reduce((o,v,i)=>{return o[v[0]]=v.slice(1)[0],o}, {})
=> Object {a: "X", b: "Y"}
even shorter (by using function(e) {console.log(e); return e;}
=== (e)=>(console.log(e),e)
)
? nodejs
> [[1, 2, 3], [3,4,5]].reduce((o,v,i)=>(o[v[0]]=v.slice(1),o), {})
{ '1': [ 2, 3 ], '3': [ 4, 5 ] }
[/docs]
As david mentions, DIVs do wrap words by default.
If you are referring to really long strings of text without spaces, what I do is process the string server-side and insert empty spans:
thisIsAreallyLongStringThatIWantTo<span></span>BreakToFitInsideAGivenSpace
It's not exact as there are issues with font-sizing and such. The span option works if the container is variable in size. If it's a fixed width container, you could just go ahead and insert line breaks.
Code for clearing up the text field when clicked
<EditText android:onClick="TextFieldClicked"/>
public void TextFieldClicked(View view){
if(view.getId()==R.id.editText1);
text.setText("");
}
You could simply have: var result = (str == "true")
.
'T'
and 'Z'
are considered here as constants. You need to pass Z
without the quotes. Moreover you need to specify the timezone in the input string.
Example : 2013-09-29T18:46:19-0700
And the format as "yyyy-MM-dd'T'HH:mm:ssZ"
you want something like:
SELECT count(id), SUM(hour) as totHour, SUM(kind=1) as countKindOne;
Note that your second example was close, but the IF() function always takes three arguments, so it would have had to be COUNT(IF(kind=1,1,NULL))
. I prefer the SUM() syntax shown above because it's concise.
The %s
specifier converts the object using str()
, and %r
converts it using repr()
.
For some objects such as integers, they yield the same result, but repr()
is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.
Here's an example, using a date:
>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'
Types for which repr()
doesn't produce Python syntax include those that point to external resources such as a file
, which you can't guarantee to recreate in a different context.
You can change background of a page by simply using:
document.body.style.background = #000000; //I used black as color code
However the below script will change the background of the page after every 3 seconds using setTimeout() function:
$(function() {
var colors = ["#0099cc","#c0c0c0","#587b2e","#990000","#000000","#1C8200","#987baa","#981890","#AA8971","#1987FC","#99081E"];
setInterval(function() {
var bodybgarrayno = Math.floor(Math.random() * colors.length);
var selectedcolor = colors[bodybgarrayno];
$("body").css("background",selectedcolor);
}, 3000);
})
You use uninstall the app and change the sharedPreferences name then run this application. I think it will resolve the issue.
A sample code to retrieve values from sharedPreferences you can use the following set of code,
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyValue, ""));
This code seems completely unnecessary:
String serverURLS = getRecipientURL(message);
serverURLS = "https:\\\\abc.my.domain.com:55555\\update";
if (serverURLS != null){
serverURL = new URL(serverURLS);
}
serverURLS
is assigned the result of getRecipientURL(message)
serverURLS
, making the previous statement a dead storeif (serverURLS != null)
evaluates to true
, since you just assigned the variable a value in the preceding statement, you assign a value to serverURL
. It is impossible for if (serverURLS != null)
to evaluate to false
!serverURLS
beyond the previous line of code.You could replace all of this with just:
serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");
the best way for it
<input type="file" id="file">
<label for="file" class="file-trigger">Click Me</label>
And you can style your "label" element
#file {
display: none;
}
.file-trigger {
/* your style */
}
Use a O/R framework such as hibernate
JSON.parse()
is used to convert String to Object.
JSON.stringify()
is used to convert Object to String.
You can refer this too...
<script type="text/javascript">
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open("GET", "JSON/mylist.json", true);
hr.setRequestHeader("Content-type", "application/json",true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
/* var return_data = hr.responseText; */
var data=JSON.parse(hr.responseText);
var status=document.getElementById("status");
status.innerHTML = "";
/* status.innerHTML=data.u1.country; */
for(var obj in data)
{
status.innerHTML+=data[obj].uname+" is in "+data[obj].country+"<br/>";
}
}
}
hr.send(null);
status.innerHTML = "requesting...";
}
</script>
I assume that you want to read input from the console. If so, use Read-Host
.
Try the require_all gem:
It lets you simply:
require_all 'path/to/directory'
well, simpler than isolating the column with awk, if you need to remove everything with a certain value for a given file, why not just do grep -v:
e.g. to delete everything with the value "col2" in the second place line: col1,col2,col3,col4
grep -v ',col2,' file > file_minus_offending_lines
If this isn't good enough, because some lines may get improperly stripped by possibly having the matching value show up in a different column, you can do something like this:
awk to isolate the offending column: e.g.
awk -F, '{print $2 "|" $line}'
the -F sets the field delimited to ",", $2 means column 2, followed by some custom delimiter and then the entire line. You can then filter by removing lines that begin with the offending value:
awk -F, '{print $2 "|" $line}' | grep -v ^BAD_VALUE
and then strip out the stuff before the delimiter:
awk -F, '{print $2 "|" $line}' | grep -v ^BAD_VALUE | sed 's/.*|//g'
(note -the sed command is sloppy because it doesn't include escaping values. Also the sed pattern should really be something like "[^|]+" (i.e. anything not the delimiter). But hopefully this is clear enough.
Build from source and install, this is fixed in the latest release (10.3+):
mkdir -p /tmp/install/netifaces/
cd /tmp/install/netifaces && wget -O "netifaces-0.10.4.tar.gz" "https://pypi.python.org/packages/source/n/netifaces/netifaces-0.10.4.tar.gz#md5=36da76e2cfadd24cc7510c2c0012eb1e"
tar xvzf netifaces-0.10.4.tar.gz
cd netifaces-0.10.4 && python setup.py install
Actually its pretty easy to make integration between Csharp (VS) and Python with IronPython. It's not that much complex... As Chris Dunaway already said in answer section I started to build this inegration for my own project. N its pretty simple. Just follow these steps N you will get your results.
step 1 : Open VS and create new empty ConsoleApp project.
step 2 : Go to tools --> NuGet Package Manager --> Package Manager Console.
step 3 : After this open this link in your browser and copy the NuGet Command. Link: https://www.nuget.org/packages/IronPython/2.7.9
step 4 : After opening the above link copy the PM>Install-Package IronPython -Version 2.7.9 command and paste it in NuGet Console in VS. It will install the supportive packages.
step 5 : This is my code that I have used to run a .py file stored in my Python.exe directory.
using IronPython.Hosting;//for DLHE
using Microsoft.Scripting.Hosting;//provides scripting abilities comparable to batch files
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Hi
{
private static void Main(string []args)
{
Process process = new Process(); //to make a process call
ScriptEngine engine = Python.CreateEngine(); //For Engine to initiate the script
engine.ExecuteFile(@"C:\Users\daulmalik\AppData\Local\Programs\Python\Python37\p1.py");//Path of my .py file that I would like to see running in console after running my .cs file from VS.//process.StandardInput.Flush();
process.StandardInput.Close();//to close
process.WaitForExit();//to hold the process i.e. cmd screen as output
}
}
step 6 : save and execute the code
<?php
phpinfo();
?>
Look under Configuration in the apache2handler in the Loaded Modules row.
This is simple and works.
<?php foreach( apache_get_modules() as $module ) echo "$module<br />"; ?>
Have you tried to set isUserInteractionEnabled
to true
on the tripDetails
label? This should work.
You can try more system indeppended method: system("pause");
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
My case it solved i was using
@Html.DropDownList(model => model.TypeId ...)
using
@Html.DropDownListFor(model => model.TypeId ...)
will solve it
Works only on Windows:
import winreg
import itertools
def serial_ports() -> list:
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
ports = []
for i in itertools.count():
try:
ports.append(winreg.EnumValue(key, i)[1])
except EnvironmentError:
break
return ports
if __name__ == "__main__":
ports = serial_ports()
If you are using Json.Net attribute [JsonIgnore]
will simply ignore the field/property while serializing or deserialising.
public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details
How about: if(($counter % $display) == 0)
Dictionary<string, string> source
//
//functional programming - do not modify state - only create new state
Dictionary<string, string> result = source
.Where(kvp => string.Compare(kvp.Value, "two", true) != 0)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
//
// or you could modify state
List<string> keys = source
.Where(kvp => string.Compare(kvp.Value, "two", true) == 0)
.Select(kvp => kvp.Key)
.ToList();
foreach(string theKey in keys)
{
source.Remove(theKey);
}
Install the plugin-proposal-class-properties
npm install @babel/plugin-proposal-class-properties --save-dev
Update your webpack.config.js by adding
'plugins': ['@babel/plugin-proposal-class-properties']}]
<?php
echo date('d - m - Y',strtotime('2013-01-19 01:23:42'));
?>
Out put : 19 - 01 - 2013
Another solution is to use the query method:
import pandas as pd
from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
'B': [randint(1, 9) * 10 for x in xrange(10)],
'C': [randint(1, 9) * 100 for x in xrange(10)]})
print df
A B C
0 7 20 300
1 7 80 700
2 4 90 100
3 4 30 900
4 7 80 200
5 7 60 800
6 3 80 900
7 9 40 100
8 6 40 100
9 3 10 600
print df.query('B > 50 and C != 900')
A B C
1 7 80 700
2 4 90 100
4 7 80 200
5 7 60 800
Now if you want to change the returned values in column A you can save their index:
my_query_index = df.query('B > 50 & C != 900').index
....and use .iloc
to change them i.e:
df.iloc[my_query_index, 0] = 5000
print df
A B C
0 7 20 300
1 5000 80 700
2 5000 90 100
3 4 30 900
4 5000 80 200
5 5000 60 800
6 3 80 900
7 9 40 100
8 6 40 100
9 3 10 600
File -> Invalidate Caches & Restart...
Build -> Build signed APK -> check the path in the dialog
From ggplot2 2.0.0
you can use the margin =
argument of element_text()
to change the distance between the axis title and the numbers. Set the values of the margin
on t
op, r
ight, b
ottom, and l
eft side of the element.
ggplot(mpg, aes(cty, hwy)) + geom_point()+
theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
margin
can also be used for other element_text
elements (see ?theme
), such as axis.text.x
, axis.text.y
and title
.
addition
in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top")
, you'll need a different theme setting - e.g. axis.title.x.top
. See https://github.com/tidyverse/ggplot2/issues/4343.
Based on the answer by Thomas which was adapted from an answer by Marc I've turned the reflecting property changed code into a base class:
public abstract class PropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
protected void OnPropertyChanged<T>(Expression<Func<T>> selectorExpression)
{
if (selectorExpression == null)
throw new ArgumentNullException("selectorExpression");
var me = selectorExpression.Body as MemberExpression;
// Nullable properties can be nested inside of a convert function
if (me == null)
{
var ue = selectorExpression.Body as UnaryExpression;
if (ue != null)
me = ue.Operand as MemberExpression;
}
if (me == null)
throw new ArgumentException("The body must be a member expression");
OnPropertyChanged(me.Member.Name);
}
protected void SetField<T>(ref T field, T value, Expression<Func<T>> selectorExpression, params Expression<Func<object>>[] additonal)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return;
field = value;
OnPropertyChanged(selectorExpression);
foreach (var item in additonal)
OnPropertyChanged(item);
}
}
Usage is the same as Thomas' answer except that you can pass additional properties to notify for. This was necessary to handle calculated columns which need to be refreshed in a grid.
private int _quantity;
private int _price;
public int Quantity
{
get { return _quantity; }
set { SetField(ref _quantity, value, () => Quantity, () => Total); }
}
public int Price
{
get { return _price; }
set { SetField(ref _price, value, () => Price, () => Total); }
}
public int Total { get { return _price * _quantity; } }
I have this driving a collection of items stored in a BindingList exposed via a DataGridView. It has eliminated the need for me to do manual Refresh() calls to the grid.
Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:
just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens
that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)
an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants
I don't have PHP experience, but I have an understanding of the Python standard library.
For your purposes, Python has several methods:
logging module;
Object serialization module which is called pickle. You may write your own wrapper of the pickle module.
If your using var_dump
for testing, Python has its own doctest and unittest modules. It's very simple and fast for design.
Ok i had this issue with uLaw compression algorithm with PCM wav file type. And what i've found out is that two's complement is kinda making a negative value of some binary number as can be seen here.And after consulting with wikipedia i deemed it true.
The guy explained it as finding least significant bit
and flipping all after it. I must say that all these solutions above didn't help me much. When i tried on 0x67ff
it gave me some off result instead of -26623
. Now solutions may have worked if someone knew the least significant bit
is scanning list of data but i didn't knew since data in PCM varies. So here is my answer:
max_data = b'\xff\x67' #maximum value i've got from uLaw data chunk to test
def twos_compliment(short_byte): # 2 bytes
short_byte = signedShort(short_byte) # converting binary string to integer from struct.unpack i've just shortened it.
valid_nibble = min([ x*4 for x in range(4) if (short_byte>>(x*4))&0xf ])
bit_shift = valid_nibble + min( [ x for x in [1,2,4,8] if ( ( short_byte>>valid_nibble )&0xf )&x ] )
return (~short_byte)^( 2**bit_shift-1 )
data = 0x67ff
bit4 = '{0:04b}'.format
bit16 = lambda x: ' '.join( map( bit4, reversed([ x&0xf, (x>>4)&0xf, (x>>8)&0xf, (x>>12)&0xf ]) ) )
# print( bit16(0x67ff) , ' : ', bit16( twos_compliment( b'\xff\x67' ) ) )
# print( bit16(0x67f0) , ' : ', bit16( twos_compliment( b'\xf0\x67' ) ) )
# print( bit16(0x6700) , ' : ', bit16( twos_compliment( b'\x00\x67' ) ) )
# print( bit16(0x6000) , ' : ', bit16( twos_compliment( b'\x00\x60' ) ) )
print( data, twos_compliment(max_data) )
Now since code is unreadable i will walk you through the idea.
## example data, for testing... in general unknown
data = 0x67ff # 26623 or 0110 0111 1111 1111
This is just any hexadecimal value, i needed test to be sure but in general it could be anything in range of int. So not to loop over whole bunch of 65535 values short integer
can have i decided to split it by nibbles ( 4 bits ). It could be done like this if you haven't used bitwise operators
before.
nibble_mask = 0xf # 1111
valid_nibble = []
for x in range(4): #0,1,2,3 aka places of bit value
# for individual bits you could go 1<<x as you will see later
# x*4 is because we are shifting bit places , so 0xFA>>4 = 0xF
# so 0x67ff>>0*4 = 0x67ff
# so 0x67ff>>1*4 = 0x67f
# so 0x67ff>>2*4 = 0x67
# so 0x67ff>>3*4 = 0x6
# and nibble mask just makes it confided to 1 nibble so 0xFA&0xF=0xA
if (data>>(x*4))&nibble_mask: valid_nibble.append(x*4) # to avoid multiplying it with 4 later
So we are searching for least significant bit
so here the min(valid_nibble )
will suffice. Here we've gotten the place where first active (with setted bit) nibble is. Now we just need is to find where in desired nibble is our first setted bit.
bit_shift = min(valid_nibble)
for x in range(4):
# in my example above [1,2,4,8] i did this to spare python calculating
ver_data = data>>min(bit_shift ) # shifting from 0xFABA to lets say 0xFA
ver_data &= nibble_mask # from 0xFA to 0xA
if ver_data&(1<<x):
bit_shift += (1<<x)
break
Now here i need to clarify somethings since seeing ~
and ^
can confuse people who aren't used to this:
XOR
: ^
: 2 numbers are necesery
This operation is kinda illogical, for each 2 bits it scans if both are either 1 or 0 it will be 0, for everything else 1.
0b10110
^0b11100
---------
0b01010
And another example:
0b10110
^0b11111
---------
0b01001
1's complement
: ~
- doesn't need any other number
This operation flips every bit in a number. It is very similar to what we are after but it doesn't leave the least significant bit.
0b10110
~
0b01001
And as we can see here 1's compliment is same as number XOR full set bits.
Now that we've understood each other, we will getting two's complement
by restoring all bites to least significant bit in one's complement.
data = ~data # one's complement of data
This unfortunately flipped all bits in our number, so we just need to find a way to flip back the numbers we want. We can do that with bit_shift
since it is bit position of our bit we need to keep. So when calculating number of data some number of bits can hold we can do that with 2**n
and for nibble we get 16 since we are calculating 0 in values of bits.
2**4 = 16 # in binary 1 0000
But we need the bytes after the 1
so we can use that to diminish the value by 1 and we can get.
2**4 -1 = 15 # in binary 0 1111
So lets see the logic in concrete example:
0b110110
lsb = 2 # binary 10
~0b110110
----------
0b001001 # here is that 01 we don't like
0b001001
^0b000011 # 2**2 = 4 ; 4-1 = 3 in binary 0b11
---------
0b001010
I hope this help'd you or any newbie that had this same problem and researched their a** off finding the solution. Have in mind this code i wrote is frankenstein code , that i why i had to explain it. It could be done more prettier, if anyone wants to make my code pretty please be my guest.
You could use a pseudo element for this, and have your image on a hover:
.image {_x000D_
position: relative;_x000D_
height: 300px;_x000D_
width: 300px;_x000D_
background: url(http://lorempixel.com/300/300);_x000D_
}_x000D_
.image:before {_x000D_
content: "";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
transition: all 0.8s;_x000D_
opacity: 0;_x000D_
background: url(http://lorempixel.com/300/200);_x000D_
background-size: 100% 100%;_x000D_
}_x000D_
.image:hover:before {_x000D_
opacity: 0.8;_x000D_
}
_x000D_
<div class="image"></div>
_x000D_
You can position both the image and the text with position:absolute
or position:relative
. Then the z-index property will work. E.g.
#sometext {
position:absolute;
z-index:1;
}
image.center {
position:absolute;
z-index:0;
}
Use whatever method you like to center it.
Another option/hack is to make the image the background, either on the whole page or just within the text box.
For me the most compact and compliant solution to the request is
$ a='1 2\t \t3 4 5 6 7 \t 8\t ';
$ echo -e "$a" | awk -v n=3 '{while (i<n) {i++; sub($1 FS"*", "")}; print $0}'
And if you have more lines to process as for instance file foo.txt, don't forget to reset i to 0:
$ awk -v n=3 '{i=0; while (i<n) {i++; sub($1 FS"*", "")}; print $0}' foo.txt
Thanks your forum.
Is there any advantage in creating a temporary file in a more careful way
The temporary files are usually created in the temporary directory (such as /tmp
) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask
) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren't unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).
You could use the following approach to create the temporary directory:
TMPDIR=".${0##*/}-$$" && mkdir -v "$TMPDIR"
or temporary file:
TMPFILE=".${0##*/}-$$" && touch "$TMPFILE"
However it is still predictable and not considered safe.
As per man mktemp
, we can read:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.
So to be safe, it is recommended to use mktemp
command to create unique temporary file or directory (-d
).
To well understand the behaviour, you can run this code:
#include <iostream>
class MyClass
{
public:
MyClass() { std::cout << "run constructor MyClass::MyClass()" << std::endl; }
~MyClass() { std::cout << "run destructor MyClass::~MyClass()" << std::endl; }
MyClass(const MyClass& x) { std::cout << "run copy constructor MyClass::MyClass(const MyClass&)" << std::endl; }
MyClass& operator = (const MyClass& x) { std::cout << "run assignation MyClass::operator=(const MyClass&)" << std::endl; }
};
MyClass my_function()
{
std::cout << "run my_function()" << std::endl;
MyClass a;
std::cout << "my_function is going to return a..." << std::endl;
return a;
}
int main(int argc, char** argv)
{
MyClass b = my_function();
MyClass c;
c = my_function();
return 0;
}
The output is the following:
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run constructor MyClass::MyClass()
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run assignation MyClass::operator=(const MyClass&)
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
Note that this example was provided in C++03 context, it could be improved for C++ >= 11
<VirtualHost *:80>
DocumentRoot /var/www/app1
ServerName app1.example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/wildcard
ServerName other.example.com
ServerAlias *.example.com
</VirtualHost>
Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.
When setting http_proxy and https_proxy, you are also probably going to need no_proxy for URLs on the same side of the proxy. https://msdn.microsoft.com/en-us/library/hh272656(v=vs.120).aspx
#include <sstream>
....
std::stringstream ss;
ss << a_long_int; // or any other type
std::string result=ss.str(); // use .str() to get a string back
You're right MacOSX has Objective-C in the core.
Windows C++
Linux C
About the scripting languages, no, they pretty much high level.
Sometimes when you uninstall the application from android device it does not get uninstalled completely. It goes to disabled state. To fix this, Go to Settings -> Apps -> Disabled Apps -> Select your app and uninstall.
Then go to android studio and run the app. The isssue is resolved.
A simple way but dangerous way to do this would be to use eval()
. eval()
executes the string passed to it as code. The dangerous thing about this is that if this string is gained from user input, they could maliciously execute code that could break the computer. I would get the input, check it with a regex, and then execute it if you determine if it's OK. If it's only going to be in the format "number operation number", then you could use a simple regex:
import re
s = raw_input('What is your math problem? ')
if re.findall('\d+? *?\+ *?\d+?', s):
print eval(s)
else:
print "Try entering a math problem"
Otherwise, you would have to come up with something a bit stricter than this. You could also do it conversely, using a regex to find if certain things are not in it, such as numbers and operations. Also you could check to see if the input contains certain commands.
We have used both and we like Bootstrap for its simplicity and the pace at which it's being developed and enhanced. The problem with jQuery UI is that it's moving at a snail's pace. It's taking years to roll out common features like Menubar, Tree control and DataGrid which are in planning/development stage for ever. We waited waited waited and finally given up and used other libraries like ExtJS for our product http://dblite.com.
Bootstrap has come up with quite a comprehensive set of features in a very short period of time and I am sure it will outpace jQuery UI pretty soon.
So I see no point in using something that will eventually be outdated...
You can check your all defined function by
$arr = get_defined_functions();
print_r($arr);
this will give you array of all functions in if your function exist in it you can use it like:
{{ user.myfunction({{parameter}}) }}
The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.
What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!
I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.
So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;
// create and initialize an object
public static JSONObject buildObject( final SimpleEntry... entries ) {
JSONObject object = new JSONObject();
for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
return object;
}
// nest a list of objects inside another
public static void putObjects( final JSONObject parentObject, final String key,
final JSONObject... objects ) {
List objectList = new ArrayList<JSONObject>();
for( JSONObject o : objects ) objectList.add( o );
parentObject.put( key, objectList );
}
Implementation example:
JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
buildObject(
new SimpleEntry( "child1Key1", "someValue" )
, new SimpleEntry( "child1Key2", "someValue" )
)
, buildObject(
new SimpleEntry( "child2Key1", "someValue" )
, new SimpleEntry( "child2Key2", "someValue" )
)
);
When trying the accepted answer, I was getting an installation error: A failure was detected for a previous installation, patch, or repair blah, blah, blah...
To fix this, in my registry, I changed all DWORD values to 1 in the following Keys: (As always be careful modifying the registry and create a backup of the key before changing anything)
HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\100\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSAS10_50.MSSQLSERVER\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.SQLEXPRESS\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\ConfigurationState
See my full post about Fixing Intellisense issue in SSMS.
In my case, I had the .eslintrc.json
file inside the .vscode
folder. Once I moved it out to the root folder, ESLint started working correctly.
What you need to add is a custom HostnameVerifier
class bypasses certificate verification and returns true
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
This needs to be placed appropriately in your code.
Tenary Operator helps keep it short and simple.
echo (isset($_SERVER['HTTPS']) ? 'http' : 'https' ). "://" . $_SERVER['SERVER_NAME'] ;
I was been getting that error in mobile safari when using ASP.NET MVC to return a FileResult with the overload that returns a file with a different file name than the original. So,
return File(returnFilePath, contentType, fileName);
would give the error in mobile safari, where as
return File(returnFilePath, contentType);
would not.
I don't even remember why I thought what I was doing was a good idea. Trying to be clever I guess.
On submitting, you would get an array as if created like this:
$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );
However, I would suggest changing your form names to this format instead:
name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...
Using that format, it's much easier to loop through the values.
if ( isset( $_POST['diameters'] ) )
{
echo '<table>';
foreach ( $_POST['diameters'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['top'], '</td>';
echo ' <td>', $diam['bottom'], '</td>';
echo '</tr>';
}
echo '</table>';
}
The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.
According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:
git tag <tagname>
, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).git tag -a <tagname>
, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.git tag -a -m <msg> <tagname>
, Git will tag the commit and annotate it with the provided message.git tag -m <msg> <tagname>
, Git will behave as if you passed the -a flag for annotation and use the provided message.Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.
Addition:
When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()
[1])
In this case, use an additional cast to binary:
SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;
Otherwise, the SELECT
statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.
Change the user to postgres :
su - postgres
Create User for Postgres
$ createuser testuser
Create Database
$ createdb testdb
Acces the postgres Shell
psql ( enter the password for postgressql)
Provide the privileges to the postgres user
$ alter user testuser with encrypted password 'qwerty';
$ grant all privileges on database testdb to testuser;
It's only supposed to send the information to the server. The reason that it must preceed the file field is that it has to come before the file payload in the request for the server to be able to use it to check the size of the upload.
How the value is used on the server depends on what you use to take care of the upload. The code is supposedly intended for a specific upload component that specifically looks for that value.
It seems that the built in upload support in PHP is one to use this field value.
I'm not entirely certain that this applies to Scala but, in Java, I solved the NotSerializableException
by refactoring my code so that the closure did not access a non-serializable final
field.
Achieve this by using the toolbar
like this :
<android.support.v7.widget.Toolbar
android:id="@+id/base_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:
years_dict = dict()
for line in list:
if line[0] in years_dict:
# append the new number to the existing array at this slot
years_dict[line[0]].append(line[1])
else:
# create a new array in this slot
years_dict[line[0]] = [line[1]]
What you should end up with in years_dict is a dictionary that looks like the following:
{
"2010": [2],
"2009": [4,7],
"1989": [8]
}
In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.
I have Visual Studio Code version 1.27.2 and can do this:
Sometimes, you don't have two files but want to copy text from somewhere and do a quick diff without having to save the contents to files first. Then you can do this:
Here are some very basic appearance customization that you can apply app wide:
UINavigationBar.appearance().backgroundColor = UIColor.greenColor()
UIBarButtonItem.appearance().tintColor = UIColor.magentaColor()
//Since iOS 7.0 UITextAttributeTextColor was replaced by NSForegroundColorAttributeName
UINavigationBar.appearance().titleTextAttributes = [UITextAttributeTextColor: UIColor.blueColor()]
UITabBar.appearance().backgroundColor = UIColor.yellowColor();
More about UIAppearance
API in Swift you can read here: https://developer.apple.com/documentation/uikit/uiappearance
Hey seems like you run in to reference issues when you're trying to copy an object then deleting a property. Somewhere you have to assign primitive variables so javascript makes a new value.
Simple trick (may be horrendous) I used was this
var obj = {"key1":"value1","key2":"value2","key3":"value3"};
// assign it as a new variable for javascript to cache
var copy = JSON.stringify(obj);
// reconstitute as an object
copy = JSON.parse(copy);
// now you can safely run delete on the copy with completely new values
delete copy.key2
console.log(obj)
// output: {key1: "value1", key2: "value2", key3: "value3"}
console.log(copy)
// output: {key1: "value1", key3: "value3"}
<div class="col-md-4 offset-md-4">
put your form here
</div>
You can use the iterator that is returned by the begin() method of the map template:
std::map<K,V> myMap;
std::pair<K,V> firstEntry = *myMap.begin()
But remember that the std::map container stores its content in an ordered way. So the first entry is not always the first entry that has been added.
These are the options currently documented in the tests: ctrl, shift, enter and escape. These are some valid examples of key bindings:
keydown.control.shift.enter
keydown.control.esc
You can track this here while no official docs exist, but they should be out soon.
No way to do that other than validate file extension with JavaScript when input path is populated by the file picker. To implement anything fancier you need to write your own component for whichever browser you want (activeX or XUL)
There's an "accept" attribute in HTML4.01 but I'm not aware of any browser supporting it - e.g. accept="image/gif,image/jpeg
- so it's a neat but impractical spec
try:
Activity parentActivity = this.getParent();
if (parentActivity != null)
{
View landmarkEditNameView = (EditText) parentActivity.findViewById(R.id. landmark_name_dialog_edit);
}
Removing the web.config
-file from the IIS Directory Folder solves the problem.
The filename should be a string. In other names it should be within quotes.
f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
thisline = i.split(" ");
You can also open the file using with
with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
lines = f.readlines()
for i in lines:
thisline = i.split(" ");
There is no need to add the semicolon(;
) in python. It's ugly.
I had the same issue. I published the angular/core application on iis.
To change the Identity of the application pool solved my issue. Now the Identity is LocalSystem
There are already too many answers but nothing worked for me apart from this
inputMethodManager.showSoftInput(emailET,InputMethodManager.SHOW_FORCED);
I used showSoftInput
with SHOW_FORCED
And my activity has
android:windowSoftInputMode="stateVisible|adjustResize"
hope this helps someone
Hibernate has a built-in "yes_no" type that would do what you want. It maps to a CHAR(1) column in the database.
Basic mapping: <property name="some_flag" type="yes_no"/>
Annotation mapping (Hibernate extensions):
@Type(type="yes_no")
public boolean getFlag();
See How to create and apply a patch with Git. (From the wording of your question, I assumed that this other repository is for an entirely different codebase. If it's a repository for the same code base, you should add it as a remote as suggested by @CharlesB. Even if it is for another code base, I guess you could still add it as a remote, but you might not want to get the entire branch into your repository...)
Read this (supplementary) answer (that is sometimes the answer) to understand where this is going and why some people in this thread complain that "it is still not working"
I wrote exactly same code as one of the answers here. But I still had an issue. I placed break point on
var mi = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance );
It executed but mi == null
And it continued behavior like this until I did "re-build" on all projects involved. I was unit testing one assembly while the reflection method was sitting in third assembly. It was totally confusing but I used Immediate Window to discover methods and I found that a private method I tried to unit test had old name (I renamed it). This told me that old assembly or PDB is still out there even if unit test project builds - for some reason project it tests didn't built. "rebuild" worked
Why has no one mentioned glob
? glob
lets you use Unix-style pathname expansion, and is my go to function for almost everything that needs to find more than one path name. It makes it very easy:
from glob import glob
paths = glob('*/')
Note that glob
will return the directory with the final slash (as unix would) while most path
based solutions will omit the final slash.
Use this
$("input[name='nameOfYourRadioButton']").attr("checked", false);
Watch out for other paths ending in \ too. I had this:
...bin;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files\nodejs\
and changed it to this:
bin;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files\nodejs
removing the final \, but it still didn't work. The previous path, for the Web Platform Installer, had a trailing \ too. Removing that fixed the problem.
After trying the simple pip install
route for eyeD3, pytaglib, and ID3 modules recommended here, I found this fourth option was the only one to work. The rest had import errors with missing dependencies in C++ or something magic or some other library that pip
missed. So go with this one for basic reading of ID3 tags (all versions):
https://pypi.python.org/pypi/tinytag/0.18.0
from tinytag import TinyTag
tag = TinyTag.get('/some/music.mp3')
List of possible attributes you can get with TinyTag:
tag.album # album as string
tag.albumartist # album artist as string
tag.artist # artist name as string
tag.audio_offset # number of bytes before audio data begins
tag.bitrate # bitrate in kBits/s
tag.disc # disc number
tag.disc_total # the total number of discs
tag.duration # duration of the song in seconds
tag.filesize # file size in bytes
tag.genre # genre as string
tag.samplerate # samples per second
tag.title # title of the song
tag.track # track number as string
tag.track_total # total number of tracks as string
tag.year # year or data as string
It was tiny and self-contained, as advertised.
There isn't a direct way to do this like you've attempted.
The usual approach is to use "varargs" and check against the number of arguments. Something like:
function f(arg1, arg2, arg3)
if nargin < 3
arg3 = 'some default'
end
end
There are a few fancier things you can do with isempty
, etc., and you might want to look at Matlab central for some packages that bundle these sorts of things.
You might have a look at varargin
, nargchk
, etc. They're useful functions for this sort of thing. varargs allow you to leave a variable number of final arguments, but this doesn't get you around the problem of default values for some/all of them.
Whats you are looking for is jQuery Ajax. And then just setup a php page to process the request.
LENGTH()
returns the length of the string measured in bytes.
CHAR_LENGTH()
returns the length of the string measured in characters.
This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:
select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1
As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC
in UTF-8) even though it's only one character.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class DoSomethingInAThread implements Runnable
{
public static void main(String[] args) throws ExecutionException, InterruptedException
{
//limit the number of actual threads
int poolSize = 10;
ExecutorService service = Executors.newFixedThreadPool(poolSize);
List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();
for (int n = 0; n < 1000; n++)
{
Future f = service.submit(new DoSomethingInAThread());
futures.add(f);
}
// wait for all tasks to complete before continuing
for (Future<Runnable> f : futures)
{
f.get();
}
//shut down the executor service so that this thread can exit
service.shutdownNow();
}
public void run()
{
// do something here
}
}
The concept behind classes and objects is to encapsulate logic into single programming unit. Classes are the blueprints of which objects are created.
Here an example of a class representing a Car:
public class Car {
int currentSpeed;
String name;
public void accelerate() {
}
public void park() {
}
public void printCurrentSpeed() {
}
}
You can create instances of the object Car like this:
Car audi = new Car();
Car toyota = new Car();
I have taken the example from this tutorial
I'm going to put in a vote for np.vectorize. It allows you to just shoot over x number of columns and not deal with the dataframe in the function, so it's great for functions you don't control or doing something like sending 2 columns and a constant into a function (i.e. col_1, col_2, 'foo').
import numpy as np
import pandas as pd
df = pd.DataFrame({'ID':['1','2','3'], 'col_1': [0,2,3], 'col_2':[1,4,5]})
mylist = ['a','b','c','d','e','f']
def get_sublist(sta,end):
return mylist[sta:end+1]
#df['col_3'] = df[['col_1','col_2']].apply(get_sublist,axis=1)
# expect above to output df as below
df.loc[:,'col_3'] = np.vectorize(get_sublist, otypes=["O"]) (df['col_1'], df['col_2'])
df
ID col_1 col_2 col_3
0 1 0 1 [a, b]
1 2 2 4 [c, d, e]
2 3 3 5 [d, e, f]
import sys
sys.path.append('your certain directory')
Basically sys.path is a list with all the search paths for python modules. It is initialized by the interpreter. The content of PYTHONPATH is automatically added to the end of that list.
Just to clarify: from within your app, you can simply refer to the emulator as 'localhost' or 127.0.0.1.
Web traffic is routed through your development machine, so the emulator's external IP is whatever IP has been assigned to that machine by your provider. The development machine can always be reached from your device at 10.0.2.2.
Since you were asking only about the emulator's IP, what is it you're trying to do?
Access the json array like you would any other array.
for(var i =0;i < itemData.length-1;i++)
{
var item = itemData[i];
alert(item.Test1 + item.Test2 + item.Test3);
}
This thread is old but was the first one to come up so I thought id share my solution too. Apart from having named routes in your routes.php file. This error can also occur when you have duplicate URLs in your routes file, but with different names, the error can be misleading in this scenario. Example
Route::any('official/form/reject-form', 'FormStatus@rejectForm')->name('reject-form');
Route::any('official/form/accept-form', 'FormStatus@acceptForm')->name('accept-form');
Changing one of the names solves the problem. Copy pasting and fatigue will get you to this problem :).
Written a simplest extension that works for us. If anyone looks for it...
public static class DateTimeExtensions
{
public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp)
{
return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;
}
}
The various overloads of Runtime.getRuntime().exec(...)
take either an array of strings or a single string. The single-string overloads of exec()
will tokenise the string into an array of arguments, before passing the string array onto one of the exec()
overloads that takes a string array. The ProcessBuilder
constructors, on the other hand, only take a varargs array of strings or a List
of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.
So, for example, on Windows,
Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2");
will run a DoStuff.exe
program with the two given arguments. In this case, the command-line gets tokenised and put back together. However,
ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2");
will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2
in C:\
. This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use
ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");
or alternatively
List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);
pgBadger is another option - also listed here: https://github.com/dhamaniasad/awesome-postgres#utilities
Requires some additional setup in advance to capture the necessary data in the postgres logs though, see the official website.
Here's example with simple object exporting.
var MyScreen = {
/* ... */
width : function (percent){
return window.innerWidth / 100 * percent
}
height : function (percent){
return window.innerHeight / 100 * percent
}
};
export default MyScreen
In main file (Use when you don't want and don't need to create new instance) and it is not global you will import this only when it needed :
import MyScreen from "./module/screen";
console.log( MyScreen.width(100) );
Matt's answer is definitely the right answer. However, here's an alternative solution for comic relief purposes:
do.call(paste, c(as.list(sdata), sep = ""))
You have to be very careful on formatting and line spacing in go, everything counts and here is a working sample, try it https://play.golang.org/p/c0zeXKYlmF
package main
import "fmt"
func main() {
testLine := `This is a test line 1
This is a test line 2`
fmt.Println(testLine)
}
The easiest way to pass additional data is to add the data to the existing ViewData for the view as @Joel Martinez notes. However, if you don't want to pollute your ViewData, RenderPartial has a method that takes three arguments as well as the two-argument version you show. The third argument is a ViewDataDictionary. You can construct a separate ViewDataDictionary just for your partial containing just the extra data that you want to pass in.
Using white-space: pre-line
allows you to input the text directly in the HTML with line breaks without having to use \n
If you use the innerText
property of the element via JavaScript on a non-pre element e.g. a <div>
, the \n
values will be replaced with <br>
in the DOM by default
innerText
: replaces \n
with <br>
innerHTML
, textContent
: require the use of styling white-space
It depends on how your applying the text, but there are a number of options
const node = document.createElement('div');
node.innerText = '\n Test \n One '
I guess you are using an IDE (like Netbeans) which allows you to run the code even if certain classes are not compilable. During the application's runtime, if you access this class it would lead to this exception.
I guess you want
last_index = len(list1) - 1
which would store 3 in last_index
.
You can use this:
comment = Comment.objects.filter(pk=comment_id)
If you are not sure which commit you want to branch from in advance you can check commits out and examine their code (see source, compile, test) by
git checkout <sha1-of-commit>
once you find the commit you want to branch from you can do that from within the commit (i.e. without going back to the master first) just by creating a branch in the usual way:
git checkout -b <branch_name>
I faced with the same issue. I just added credentials config:
aws_access_key_id = your_aws_access_key_id
aws_secret_access_key = your_aws_secret_access_key
into "~/.aws/credentials" + restart terminal for default profile.
In the case of multi profiles --profile arg needs to be added:
aws s3 sync ./localDir s3://bucketName --profile=${PROFILE_NAME}
where PROFILE_NAME:
.bash_profile ( or .bashrc) -> export PROFILE_NAME="yourProfileName"
More info about how to config credentials and multi profiles can be found here
SELECT * FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
Update : for better performance and faster query its good to add e1
before *
SELECT e1.* FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;