You can use IIF for a similar result.
Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html
SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer
FROM MyTable;
This works:
switch (true) {
case liCount == 0:
setLayoutState('start');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=5 && liCount>0:
setLayoutState('upload1Row');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount<=10 && liCount>5:
setLayoutState('upload2Rows');
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
case liCount>10:
var api = $('#UploadList').data('jsp');
api.reinitialise();
break;
}
A previous version of this answer considered the parentheses to be the culprit. In truth, the parentheses are irrelevant here - the only thing necessary is switch(true){...}
and for your case expressions to evaluate to booleans.
It works because, the value we give to the switch is used as the basis to compare against. Consequently, the case expressions, also evaluating to booleans will determine which case is run. Could also turn this around, and pass switch(false){..}
and have the desired expressions evaluate to false instead of true.. but personally prefer dealing with conditions that evaluate to truthyness. However, it does work too, so worth keeping in mind to understand what it is doing.
Eg: if liCount is 3, the first comparison is true === (liCount == 0)
, meaning the first case is false. The switch then moves on to the next case true === (liCount<=5 && liCount>0)
. This expression evaluates to true, meaning this case is run, and terminates at the break
. I've added parentheses here to make it clearer, but they are optional, depending on the complexity of your expression.
It's pretty simple, and a neat way (if it fits with what you are trying to do) of handling a long series of conditions, where perhaps a long series of ìf() ... else if() ... else if () ...
might introduce a lot of visual noise or fragility.
Use with caution, because it is a non-standard pattern, despite being valid code.
Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
ROWS UNBOUNDED PRECEDING
is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY
it defines the window on which the result is calculated.
Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.
Starting and ending rows might be fixed or relative to the current row based on the following keywords:
Possible kinds of calculation include:
So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING)
results in a Cumulative Sum or Running Total
11 -> 11
2 -> 11 + 2 = 13
3 -> 13 + 3 (or 11+2+3) = 16
44 -> 16 + 44 (or 11+2+3+44) = 60
In BASH, you can find a user's $HOME
directory by prefixing the user's login ID with a tilde character. For example:
$ echo ~bob
This will echo out user bob
's $HOME
directory.
However, you say you want to be able to execute a script as a particular user. To do that, you need to setup sudo. This command allows you to execute particular commands as either a particular user. For example, to execute foo
as user bob
:
$ sudo -i -ubob -sfoo
This will start up a new shell, and the -i
will simulate a login with the user's default environment and shell (which means the foo
command will execute from the bob's
$HOME` directory.)
Sudo is a bit complex to setup, and you need to be a superuser just to be able to see the shudders file (usually /etc/sudoers
). However, this file usually has several examples you can use.
In this file, you can specify the commands you specify who can run a command, as which user, and whether or not that user has to enter their password before executing that command. This is normally the default (because it proves that this is the user and not someone who came by while the user was getting a Coke.) However, when you run a shell script, you usually want to disable this feature.
Similar to John Wilkey's answer I would run python2 by finding which python
, something like using /usr/bin/python
and then creating an alias in .bash_profile
:
alias python2="/usr/bin/python"
I can now run python3 by calling python
and python2 by calling python2
.
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
Each resource has references to other resources, either in hierarchy or links, so it's easy to browse around. This is an advantage to the human developing the client, saving he/she from constantly consulting the docs, and offering suggestions. It also means the server can change resource names unilaterally (as long as the client software doesn't hardcode the URLs).
You can CURL your way into any part of the API or use the web browser to navigate resources. Makes debugging and testing integration much easier.
Allows you to specify actions without having to hunt the correct wording. Imagine if OOP getters and setters weren't standardized, and some people used retrieve
and define
instead. You would have to memorize the correct verb for each individual access point. Knowing there's only a handful of verbs available counters that problem.
If you GET
a resource that doesn't exist, you can be sure to get a 404
error in a RESTful API. Contrast it with a non-RESTful API, which may return {error: "Not found"}
wrapped in God knows how many layers. If you need the extra space to write a message to the developer on the other side, you can always use the body of the response.
Imagine two APIs with the same functionality, one following REST and the other not. Now imagine the following clients for those APIs:
RESTful:
GET /products/1052/reviews
POST /products/1052/reviews "5 stars"
DELETE /products/1052/reviews/10
GET /products/1052/reviews/10
HTTP:
GET /reviews?product_id=1052
POST /post_review?product_id=1052 "5 stars"
POST /remove_review?product_id=1052&review_id=10
GET /reviews?product_id=1052&review=10
Now think of the following questions:
If the first call of each client worked, how sure can you be the rest will work too?
There was a major update to the API that may or may not have changed those access points. How much of the docs will you have to re-read?
Can you predict the return of the last query?
You have to edit the review posted (before deleting it). Can you do so without checking the docs?
I would expect that the JVM gracefully interrupts (thread.interrupt()
) all the running threads created by the application, at least for signals SIGINT (kill -2)
and SIGTERM (kill -15)
.
This way, the signal will be forwarded to them, allowing a gracefully thread cancellation and resource finalization in the standard ways.
But this is not the case (at least in my JVM implementation: Java(TM) SE Runtime Environment (build 1.8.0_25-b17), Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
.
As other users commented, the usage of shutdown hooks seems mandatory.
So, how do I would handle it?
Well first, I do not care about it in all programs, only in those where I want to keep track of user cancellations and unexpected ends. For example, imagine that your java program is a process managed by other. You may want to differentiate whether it has been terminated gracefully (SIGTERM
from the manager process) or a shutdown has occurred (in order to relaunch automatically the job on startup).
As a basis, I always make my long-running threads periodically aware of interrupted status and throw an InterruptedException
if they interrupted. This enables execution finalization in way controlled by the developer (also producing the same outcome as standard blocking operations). Then, at the top level of the thread stack, InterruptedException
is captured and appropriate clean-up performed. These threads are coded to known how to respond to an interruption request. High cohesion design.
So, in these cases, I add a shutdown hook, that does what I think the JVM should do by default: interrupt all the non-daemon threads created by my application that are still running:
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Interrupting threads");
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
for (Thread th : runningThreads) {
if (th != Thread.currentThread()
&& !th.isDaemon()
&& th.getClass().getName().startsWith("org.brutusin")) {
System.out.println("Interrupting '" + th.getClass() + "' termination");
th.interrupt();
}
}
for (Thread th : runningThreads) {
try {
if (th != Thread.currentThread()
&& !th.isDaemon()
&& th.isInterrupted()) {
System.out.println("Waiting '" + th.getName() + "' termination");
th.join();
}
} catch (InterruptedException ex) {
System.out.println("Shutdown interrupted");
}
}
System.out.println("Shutdown finished");
}
});
Complete test application at github: https://github.com/idelvall/kill-test
commit: adding changes to the local repository
push: to transfer the last commit(s) to a remote server
As checking for members of a collection is a general problem, here is an abstracted version of Tim's answer:
Function Contains(objCollection As Object, strName as String) As Boolean Dim o as Object On Error Resume Next set o = objCollection(strName) Contains = (Err.Number = 0) Err.Clear End Function
This function can be used with any collection like object (Shapes
, Range
, Names
, Workbooks
, etc.).
To check for the existence of a sheet, use If Contains(Sheets, "SheetName") ...
<style>
p{
width: 70%
word-wrap: break-word;
}
</style>
This wasn't working in my case. It worked fine after adding following style.
<style>
p{
width: 70%
word-break: break-all;
}
</style>
This is what I had to do to get started with a Less compiler to avoid issues as mentionned in the OP:
sudo npm install npm -g
sudo npm install -g less
(the sudo makes all the difference)/usr/local/bin/lessc
Johnsyweb's answer didn't work for me, but it works for me with Mutt:
echo "Message body" | mutt -s "Message subject" -a myfile.txt [email protected]
You can non-interactively remove B and C in your example with:
git rebase --onto HEAD~5 HEAD~3 HEAD
or symbolically,
git rebase --onto A C HEAD
Note that the changes in B and C will not be in D; they will be gone.
I have a project in which I have the following TextView
:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/app_name"
android:layout_gravity="center"
/>
So, I'm guessing you need to use android:textStyle
I'm using the following sql to find entries in all_synonyms where there is no corresponding object for the object_name (in user_objects):
select *
from all_synonyms
where table_owner = 'SCOTT'
and synonym_name not like '%/%'
and table_name not in (
select object_name from user_objects
where object_type in (
'TABLE', 'VIEW', 'PACKAGE', 'SEQUENCE',
'PROCEDURE', 'FUNCTION', 'TYPE'
)
);
You can use "translateX"
<div class="box">
<div class="absolute-right"></div>
</div>
<style type="text/css">
.box{
text-align: right;
}
.absolute-right{
display: inline-block;
position: absolute;
}
/*The magic:*/
.absolute-right{
-moz-transform: translateX(-100%);
-ms-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
-o-transform: translateX(-100%);
transform: translateX(-100%);
}
</style>
2-D Array Dynamic Memory Allocation
int **a,i;
// for any number of rows & columns this will work
a = (int **)malloc(rows*sizeof(int *));
for(i=0;i<rows;i++)
*(a+i) = (int *)malloc(cols*sizeof(int));
First decrements the value and then print it -
awk ' { print $(--NF)}' file
OR
rev file|cut -d ' ' -f2|rev
To answer the part of your question,
what is the use of
\r
?
Many Internet protocols, such as FTP, HTTP and SMTP, are specified in terms of lines delimited by carriage return and newline. So, for example, when sending an email, you might have code such as:
fprintf(socket, "RCPT TO: %s\r\n", recipients);
Or, when a FTP server replies with a permission-denied error:
fprintf(client, "550 Permission denied\r\n");
$( "#dialogueForm" ).dialog({
autoOpen: false,
height: "auto",
width: "auto",
modal: true,
my: "center",
at: "center",
of: window,
close : function(){
// functionality goes here
}
});
"close" property of dialog gives the close event for the same.
Improving the solution to detect circle with circle collision detection given within the question:
float dx = circle1.x - circle2.x,
dy = circle1.y - circle2.y,
r = circle1.r + circle2.r;
return (dx * dx + dy * dy <= r * r);
It avoids the unnecessary "if with two returns" and the use of more variables than necessary.
Doing this with POSIX is tricky:
POSIX Sed does not support \r
or \15
. Even if it did, the in place
option -i
is not POSIX
POSIX Awk does support \r
and \15
, however the -i inplace
option
is not POSIX
d2u and dos2unix are not POSIX utilities, but ex is
POSIX ex does not support \r
, \15
, \n
or \12
To remove carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\r","");print>ARGV[1]}' file
To add carriage returns:
awk 'BEGIN{RS="^$";ORS="";getline;gsub("\n","\r&");print>ARGV[1]}' file
Im working with mysql and registered with root user, the solution that work for me is the following:
mysql > SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
A backreference to the whole match value is \g<0>
, see re.sub
documentation:
The backreference
\g<0>
substitutes in the entire substring matched by the RE.
See the Python demo:
import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
As a new user to these two software packages, I experienced the exact same problem. As was also discovered above, my solution was to use the same case letters as is in the Repository path.
Here's a tip that I find helpful: In VisualSVN, you can right click on the path, then click "Copy URL to Clipboard" for pasting in Tortoise to be sure that the path is the identical case.
Try:
SqlConnection myConnection = new SqlConnection("Database=testDB;Server=Paul-PC\\SQLEXPRESS;Integrated Security=True;connect timeout = 30");
There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help. The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining. If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried. In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser. I ended up using a custom code and logic that takes advantage of both.
I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened. This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'. At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab. Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab. So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh. Instead you need to store a flag in sessionStorage at every load before increasing the tab counter. Before storing this value, you can make a check to see if it already has a value and if it doesn't, this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.
If you want to use prototype then there is a way
var p = function Person() {
this.x = 10;
this.y = 20;
}
p.prototype.counter = 0;
var person1 = new p();
person1.prototype = p.prototype;
console.log(person1.counter);
person1.prototype.counter++;
var person2 = new p();
person2.prototype = p.prototype;
console.log(person2.counter);
console.log(person1.counter);
Doing this you will be able to access the counter variable from any instance and any change in the property will be immediately reflected!!
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
Try with array_merge_recursive
$A = array('a' => 1, 'b' => 2, 'c' => 3);
$B = array('c' => 4, 'd'=> 5);
$c = array_merge_recursive($A,$B);
echo "<pre>";
print_r($c);
echo "</pre>";
will return
Array
(
[a] => 1
[b] => 2
[c] => Array
(
[0] => 3
[1] => 4
)
[d] => 5
)
It looks like this is the case when Chrome is not compliant with WebSocket standard. When the server initiates close and sends close frame to a client, Chrome considers this to be an error and reports it to JS side with code 1006 and no reason message. In my tests, Chrome never responds to server-initiated close frames (close code 1000) suggesting that code 1006 probably means that Chrome is reporting its own internal error.
P.S. Firefox v57.00 handles this case properly and successfully delivers server's reason message to JS side.
Go to view
, then appearence
. Then select move panel bottom.
For me the issue was that I was converting an existing project to maven, created the folder structures according to the documentation and it was showing the 'main' folder as part of the package. I followed the instructions similar to Jon Skeet / JWoodchuck and went into the Java build path, removed all broken build paths, and then added my build path to be 'src/main/java' and 'src/test/java', as well as the resources folders for each, and it resolved the issue.
You can do it:
var str = "Doctor Who,Fantasy,Steven Moffat,David Tennant";
var title = str.Split(',').First();
Also you can do it this way:
var index = str.IndexOf(",");
var title = index < 0 ? str : str.Substring(0, index);
Here is another faster version that handles RGBA versions:
public static int hexToIntColor(String hex){
int Alpha = Integer.valueOf(hex.substring(0, 2), 16);
int Red = Integer.valueOf(hex.substring(2, 4), 16);
int Green = Integer.valueOf(hex.substring(4, 6), 16);
int Blue = Integer.valueOf(hex.substring(6, 8), 16);
Alpha = (Alpha << 24) & 0xFF000000;
Red = (Red << 16) & 0x00FF0000;
Green = (Green << 8) & 0x0000FF00;
Blue = Blue & 0x000000FF;
return Alpha | Red | Green | Blue;
}
val.ToString("".PadLeft(length, '0'))
There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.
Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4
Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
To get a better idea, all you need are the following files
You could put everything else in the .gitignore file. All your app changes lies mostly in these files and folders. The rest you see in a basic project are gradle build files or Android Studio configuration files.
If you are using Android Studio, you can use "Import project" to successfully build the project. Alternatively you can build using command line, follow Building Android Projects with Gradle.
String.Trim()
removes all whitespace from the beginning and end of a string.
To remove whitespace inside a string, or normalize whitespace, use a Regular Expression.
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
For example Tomcat (default) expects:
spring.datasource.ourdb.url=...
and HikariCP will be happy with:
spring.datasource.ourdb.jdbc-url=...
We can satisfy both without boilerplate configuration:
spring.datasource.ourdb.jdbc-url=${spring.datasource.ourdb.url}
Take a look at source DataSourceBuilder.java
If Tomcat, HikariCP or Commons DBCP are on the classpath one of them will be selected (in that order with Tomcat first).
... so, we can easily replace connection pool provider using this maven configuration (pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
The mask makes sure you only get RRGGBB, and the %06X gives you zero-padded hex (always 6 chars long):
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
It's easier to use only one code block, then you only need one redirection.
(
echo Line1
echo Line2
...
echo Last Line
) > filename.txt
What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}
) and then use this to get the parent directory and cd
to it at the beginning of the script.
#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$parent_path"
cat ../some.text
This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh
inside dir
.
Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)
To iterate through all files and folders you can use
for /F "delims=" %%a in ('dir /b /s') do echo %%a
To iterate through all folders only not with files, then you can use
for /F "delims=" %%a in ('dir /a:d /b /s') do echo %%a
Where /s
will give all results throughout the directory tree in unlimited depth. You can skip /s
if you want to iterate through the content of that folder not their sub folder
To iterate through a particular named files and folders you can search for the name and iterate using for loop
for /F "delims=" %%a in ('dir "file or folder name" /b /s') do echo %%a
To iterate through a particular named folders/directories and not files, then use /AD
in the same command
for /F "delims=" %%a in ('dir "folder name" /b /AD /s') do echo %%a
Just to add to the correct answer above, in Vue.JS v1.0 you can write
<a v-on:click="doSomething">
So in this example it would be
v-on:change="foo"
Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:
If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"
Use getpass for this purpose.
getpass.getpass - Prompt the user for a password without echoing
About REST return codes: it is wrong to mix HTTP protocol codes and REST results.
However, I saw many implementations mixing them, and many developers may not agree with me.
HTTP return codes are related to the HTTP Request
itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.
For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:
"403 Forbidden/Access Denied" may mean:
And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...
From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.
If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the http server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as http result, right?
Instead of this you may return 200 HTTP code and simply a JSON with an empty array/object, or to use a bool result/success flag to inform about the performed operation status.
Also, some internet providers may intercept your requests and return you a 404 http code. This does not means that your data are not found, but it's something wrong at transport level.
From Wiki:
In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".
Generates a strong password of length 8 containing at least one lower case letter, one uppercase letter, one digit, and one special character. You can change the length in the code too.
function checkForCharacterCondition($string) {
return (bool) preg_match('/(?=.*([A-Z]))(?=.*([a-z]))(?=.*([0-9]))(?=.*([~`\!@#\$%\^&\*\(\)_\{\}\[\]]))/', $string);
}
$j = 1;
function generate_pass() {
global $j;
$allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_{}[]';
$pass = '';
$length = 8;
$max = mb_strlen($allowedCharacters, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$pass .= $allowedCharacters[random_int(0, $max)];
}
if (checkForCharacterCondition($pass)){
return '<br><strong>Selected password: </strong>'.$pass;
}else{
echo 'Iteration '.$j.': <strong>'.$pass.'</strong> Rejected<br>';
$j++;
return generate_pass();
}
}
echo generate_pass();
In my case,
myButton.setEnabled(false);
myButton.setEnabled(true);
is working fine and it is enabling and disabling the button as it should. But once the button state becomes disabled, it never goes back to the enabled state again, although it's clickable. I tried invalidating and refreshing the drawable state, but no luck.
myButton.invalidate();
myButton.refreshDrawableState();
If you or anyone having a similar issue, what works for me is setting the background drawable again. Works on any API Level.
myButton.setEnabled(true);
myButton.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.myButtonDrawable));
I could not find a easy way to set the margin for a single page.
My solution was to use vspace with the number of centimeters of empty space I wanted:
\vspace*{5cm}
I put this command at the beginning of the pages that I wanted to have +5cm of margin.
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] = []
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks: Same markup rules for 3 and N dimensional arrays.
You may find the following relevant as well:
Oracle SQL Developer connection to Microsoft SQL Server
In my case I had to place the ntlmauth.dll
in the sql-developer application directory itself (i.e. sql-developer\jdk\jre\bin). Why this location over the system jre/bin I have no idea. But it worked.
^\d{5}(?:[-\s]\d{4})?$
^
= Start of the string.\d{5}
= Match 5 digits (for condition 1, 2, 3)(?:…)
= Grouping[-\s]
= Match a space (for condition 3) or a hyphen (for condition 2)\d{4}
= Match 4 digits (for condition 2, 3)…?
= The pattern before it is optional (for condition 1)$
= End of the string.You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.
Use this to list your image ids:
$ docker images
Then tag away:
$ docker tag 9f676bd305a4 ubuntu:13.10
$ docker tag 9f676bd305a4 ubuntu:saucy
$ docker tag eb601b8965b8 ubuntu:raring
...
I solved this by adding .to_json
and some heading information
@result = HTTParty.post(@urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.
I think you're looking for something like "URL encoding" - encoding a URL so that it's "safe" to use on the web:
Here's a reference for that. If you don't want any special characters, just remove any that require URL encoding:
The images are stored in /var/lib/docker/graph/<id>/layer
.
Note that images are just diffs from the parent image. The parent ID is stored with the image's metadata /var/lib/docker/graph/<id>/json
.
When you docker run
an image. AUFS will 'merge' all layers into one usable file system.
Data in jQuery ajax()
function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:
dataString = {key: 'val', key2: 'val2'};
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
cache: false,
success: function(){
alert("OK");
}
});
You may also write POST/GET query on your own, like key=val&key2=val2
, but you'd have to handle escaping yourself which is impractical.
Try this
var URL = "scratch.mit.edu/projects";
var mainURL = window.location.pathname;
if (mainURL == URL) {
mainURL += ( mainURL.match( /[\?]/g ) ? '&' : '#' ) + '_bypasssharerestrictions_';
console.log(mainURL)
}
I should be able to accomplish this through standard java string manipulation, nothing Android or TextView specific.
Something like:
String upperString = myString.substring(0, 1).toUpperCase() + myString.substring(1).toLowerCase();
Although there are probably a million ways to accomplish this. See String documentation.
EDITED
I added the .toLowerCase()
I got the same exception also, but it was previously running fine in another machine. Anyway above solution didn't worked for me. What i did to resolve it?
Done :) Hope it helps.
I'm wondering why nobody just gave the most simple of answers:
val array: Array<Int> = [1, 2, 3]
As per one of the comments to my original answer, I realized this only works when used in annotations arguments (which was really unexpected for me).
Looks like Kotlin doesn't allow to create array literals outside annotations.
For instance, look at this code using @Option from args4j library:
@Option( name = "-h", aliases = ["--help", "-?"], usage = "Show this help" ) var help: Boolean = false
The option argument "aliases" is of type Array<String>
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);
function applyDataMask(field) {
var mask = field.dataset.mask.split('');
// For now, this just strips everything that's not a number
function stripMask(maskedData) {
function isDigit(char) {
return /\d/.test(char);
}
return maskedData.split('').filter(isDigit);
}
// Replace `_` characters with characters from `data`
function applyMask(data) {
return mask.map(function(char) {
if (char != '_') return char;
if (data.length == 0) return char;
return data.shift();
}).join('')
}
function reapplyMask(data) {
return applyMask(stripMask(data));
}
function changed() {
var oldStart = field.selectionStart;
var oldEnd = field.selectionEnd;
field.value = reapplyMask(field.value);
field.selectionStart = oldStart;
field.selectionEnd = oldEnd;
}
field.addEventListener('click', changed)
field.addEventListener('keyup', changed)
}
Date: <input type="text" value="__-__-____" data-mask="__-__-____"/><br/>
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>
To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described here:
private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
URL url = new URL(thisUrl);
builder = new Uri.Builder()
.scheme(url.getProtocol())
.authority(url.getAuthority())
.appendPath(url.getPath());
return builder.build();
}
All necessary git bash commands to push and pull into Github:
git status
git pull
git add filefullpath
git commit -m "comments for checkin file"
git push origin branch/master
git remote -v
git log -2
If you want to edit a file then:
edit filename.*
To see all branches and their commits:
git show-branch
You can create table script along with its data using following steps:
For more information, see Eric Johnson's blog.
Try this:
window.open(url, '_blank');
This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)
On Linux, you can use ldconfig
, which maintains the ld.so configuration and cache, to print out the directories search by ld.so
with
ldconfig -v 2>/dev/null | grep -v ^$'\t'
ldconfig -v
prints out the directories search by the linker (without a leading tab) and the shared libraries found in those directories (with a leading tab); the grep
gets the directories. On my machine, this line prints out
/usr/lib64/atlas:
/usr/lib/llvm:
/usr/lib64/llvm:
/usr/lib64/mysql:
/usr/lib64/nvidia:
/usr/lib64/tracker-0.12:
/usr/lib/wine:
/usr/lib64/wine:
/usr/lib64/xulrunner-2:
/lib:
/lib64:
/usr/lib:
/usr/lib64:
/usr/lib64/nvidia/tls: (hwcap: 0x8000000000000000)
/lib/i686: (hwcap: 0x0008000000000000)
/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib/sse2: (hwcap: 0x0000000004000000)
/usr/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib64/sse2: (hwcap: 0x0000000004000000)
The first paths, without hwcap
in the line, are either built-in or read from /etc/ld.so.conf.
The linker can then search additional directories under the basic library search path, with names like sse2
corresponding to additional CPU capabilities.
These paths, with hwcap
in the line, can contain additional libraries tailored for these CPU capabilities.
One final note: using -p
instead of -v
above searches the ld.so
cache instead.
With Commons.Lang, you could simply use
ArrayUtils.reverse(int[] array)
Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.
If you need access to your VPN from anywhere in the world you need to register a domain name and have it point to the public ip address of your VPN/network gateway. You could also use a Dynamic DNS service to connect a hostname to your public ip.
If you only need to ssh from your Mac to your Raspberry inside your local network, do this: On your Mac, edit /etc/hosts
. Assuming the Raspberry has hostname "berry" and ip "172.16.0.100", add one line:
# ip hostname
172.16.0.100 berry
Now: ssh user@berry
should work.
Use Nullable<DateTime>
if possible.
Earlier for almost 3hrs I did:
Here is how solve this:
If need to find nested in some dirs:
find / -type f -wholename "*dirname/filename"
Or connected dirs:
find / -type d -wholename "*foo/bar"
Try npm install --production
and then npm start
.
That is a Python bug between "*" and special characters.
Instead of
re.compile(r"\w*")
Try:
re.compile(r"[a-zA-Z0-9]*")
It works, however does not make the same regular expression.
This bug seems to have been fixed between 2.7.5 and 2.7.6.
If you want to set the column you filter on as a new index, you could also consider to use .filter
; if you want to keep it as a separate column then str.contains
is the way to go.
Let's say you have
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})
ids vals
0 aball 1
1 bball 2
2 cnut 3
3 fball 4
4 ballxyz 5
and your plan is to filter all rows in which ids
contains ball
AND set ids
as new index, you can do
df.set_index('ids').filter(like='ball', axis=0)
which gives
vals
ids
aball 1
bball 2
fball 4
ballxyz 5
But filter
also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball
. In this case you use
df.set_index('ids').filter(regex='ball$', axis=0)
vals
ids
aball 1
bball 2
fball 4
Note that now the entry with ballxyz
is not included as it starts with ball
and does not end with it.
If you want to get all entries that start with ball
you can simple use
df.set_index('ids').filter(regex='^ball', axis=0)
yielding
vals
ids
ballxyz 5
The same works with columns; all you then need to change is the axis=0
part. If you filter based on columns, it would be axis=1
.
Adding this script to my code fixed the dropdown menu.
<script>
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html ) can.
Here is a macro to do a find/replace on a var:
<macrodef name="replaceVarText">
<attribute name="varName" />
<attribute name="from" />
<attribute name="to" />
<sequential>
<local name="replacedText"/>
<local name="textToReplace"/>
<local name="fromProp"/>
<local name="toProp"/>
<property name="textToReplace" value = "${@{varName}}"/>
<property name="fromProp" value = "@{from}"/>
<property name="toProp" value = "@{to}"/>
<script language="javascript">
project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
</script>
<ac:var name="@{varName}" value = "${replacedText}"/>
</sequential>
</macrodef>
Then call the macro like:
<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>
Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.
Firefox (Win and Mac)
If the Web Dev Toolbar is installed, people can use this keyboard shortcuts: Command + Shift + S (Mac) and Control + Shift + S (Win)
I realize this is an old question and has been answered but this could help someone.
In your activity
private ScheduledExecutorService scheduleTaskExecutor;
In onCreate
scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
//Schedule a task to run every 5 seconds (or however long you want)
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// Do stuff here!
runOnUiThread(new Runnable() {
@Override
public void run() {
// Do stuff to update UI here!
Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
}
});
}
}, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.
Garbage collection refers to the process of automatically freeing memory on the heap by deleting objects that are no longer reachable in your program. The heap is a memory which is referred to as the free store, represents a large pool of unused memory allocated to your Java application.
Do you have a Windows machine or a Linux machine?
Under Windows cron is called 'Scheduled Tasks'. It's located in the Control Panel. You can set several scripts to run at specified times in the control panel. Use the wizard to define the scheduled times. Be sure that PHP is callable in your PATH.
Under Linux you can create a crontab for your current user by typing:
crontab -e [username]
If this command fails, it's likely that cron is not installed. If you use a Debian based system (Debian, Ubuntu), try the following commands first:
sudo apt-get update
sudo apt-get install cron
If the command runs properly, a text editor will appear. Now you can add command lines to the crontab file. To run something every five minutes:
*/5 * * * * /home/user/test.pl
The syntax is basically this:
.---------------- minute (0 - 59)
| .------------- hour (0 - 23)
| | .---------- day of month (1 - 31)
| | | .------- month (1 - 12) OR jan,feb,mar,apr ...
| | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | |
* * * * * command to be executed
Read more about it on the following pages: Wikipedia: crontab
First of all jar
creates a jar, and does not run it. Try java -jar
instead.
Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2
) and as file (com/mycomp/myproj/dir2/MainClass2.class
)?
Edit:
It seems as if java -jar
requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ...
instead. -cp
sets the jar on the classpath and enables java to look up the main class there.
Here's how I do it.
I decided to use IPrincipal instead of IIdentity because it means I don't have to implement both IIdentity and IPrincipal.
Create the interface
interface ICustomPrincipal : IPrincipal
{
int Id { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
}
CustomPrincipal
public class CustomPrincipal : ICustomPrincipal
{
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) { return false; }
public CustomPrincipal(string email)
{
this.Identity = new GenericIdentity(email);
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
CustomPrincipalSerializeModel - for serializing custom information into userdata field in FormsAuthenticationTicket object.
public class CustomPrincipalSerializeModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
LogIn method - setting up a cookie with custom information
if (Membership.ValidateUser(viewModel.Email, viewModel.Password))
{
var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First();
CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
serializeModel.Id = user.Id;
serializeModel.FirstName = user.FirstName;
serializeModel.LastName = user.LastName;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(serializeModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
viewModel.Email,
DateTime.Now,
DateTime.Now.AddMinutes(15),
false,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Response.Cookies.Add(faCookie);
return RedirectToAction("Index", "Home");
}
Global.asax.cs - Reading cookie and replacing HttpContext.User object, this is done by overriding PostAuthenticateRequest
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
newUser.Id = serializeModel.Id;
newUser.FirstName = serializeModel.FirstName;
newUser.LastName = serializeModel.LastName;
HttpContext.Current.User = newUser;
}
}
Access in Razor views
@((User as CustomPrincipal).Id)
@((User as CustomPrincipal).FirstName)
@((User as CustomPrincipal).LastName)
and in code:
(User as CustomPrincipal).Id
(User as CustomPrincipal).FirstName
(User as CustomPrincipal).LastName
I think the code is self-explanatory. If it isn't, let me know.
Additionally to make the access even easier you can create a base controller and override the returned User object (HttpContext.User):
public class BaseController : Controller
{
protected virtual new CustomPrincipal User
{
get { return HttpContext.User as CustomPrincipal; }
}
}
and then, for each controller:
public class AccountController : BaseController
{
// ...
}
which will allow you to access custom fields in code like this:
User.Id
User.FirstName
User.LastName
But this will not work inside views. For that you would need to create a custom WebViewPage implementation:
public abstract class BaseViewPage : WebViewPage
{
public virtual new CustomPrincipal User
{
get { return base.User as CustomPrincipal; }
}
}
public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
{
public virtual new CustomPrincipal User
{
get { return base.User as CustomPrincipal; }
}
}
Make it a default page type in Views/web.config:
<pages pageBaseType="Your.Namespace.BaseViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
and in views, you can access it like this:
@User.FirstName
@User.LastName
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
As addition to the other answers, in a cpanel installation, the mysql root password is stored in a file named /root/.my.cnf
. (and the cpanel service resets it back on change, so the other answers here won't help)
Double check your text with the Hex Editor Plug-in. In your case there may have been some control characters which have crept into your text. Usually you'll look at the white-space, and it will say 32 32 32 32, or for Unicode 32 00 32 00 32 00 32 00. You may find the problem this way, providing there isn't masses of code.
Download the Hex Plugin from here; http://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/
I suggest:
var minutes = data.getMinutes();
minutes = minutes > 9 ? minutes : '0' + minutes;
it is one function call fewer. It is always good to think about performance. It is short as well;
Here's one explanation:
Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.
If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.
insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)
There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:
CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int
AS
If you want to know what the ID of the newly inserted record is add
SELECT @@IDENTITY
to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx
You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.
P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.
For bootstrap 4 this works for me.
$(document).on('click', function(e) {
$('[data-toggle="popover"],[data-original-title]').each(function() {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
$(this).popover('hide')
}
});
});
working demo on jsfiddle link: https://jsfiddle.net/LabibMuhammadJamal/jys10nez/9/
The root of the problem is that Spring (via ResponseEntity, RestController, and/or ResponseBody) will use the contents of the string as the raw response value, rather than treating the string as JSON value to be encoded. This is true even when the controller method uses produces = MediaType.APPLICATION_JSON_VALUE
, as in the question here.
It's essentially like the difference between the following:
// yields: This is a String
System.out.println("This is a String");
// yields: "This is a String"
System.out.println("\"This is a String\"");
The first output cannot be parsed as JSON, but the second output can.
Something like '"'+myString+'"'
is probably not a good idea however, as that won't handle proper escaping of double-quotes within the string and will not produce valid JSON for any such string.
One way to handle this would be to embed your string inside an object or list, so that you're not passing a raw string to Spring. However, that changes the format of your output, and really there's no good reason not to be able to return a properly-encoded JSON string if that's what you want to do. If that's what you want, the best way to handle it is via a JSON formatter such as Json or Google Gson. Here's how it might look with Gson:
import com.google.gson.Gson;
@RestController
public class MyController
private static final Gson gson = new Gson();
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> so() {
return ResponseEntity.ok(gson.toJson("This is a String"));
}
}
<Link to="/page">
<Box sx={{ display: 'inline-block' }}>
<PLink variant="primary">Page</PLink>
</Box>
</Link>
In some cases when using another component inside the Gatsby <Link>
component, adding a div
with display: 'inline-block'
around the inner component, prevents underlining (of 'Page' in the example).
SELECT @var = col1,
@var2 = col2
FROM Table
Here is some interesting information about SET / SELECT
- SET is the ANSI standard for variable assignment, SELECT is not.
- SET can only assign one variable at a time, SELECT can make multiple assignments at once.
- If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
- When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
- As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.
There is a clean way to get the current URL from a Razor page or PageModel class. That is:
Url.PageLink()
Please note that I meant, the "ASP.NET Core Razor Pages", not the MVC.
I use this method when I want to print the canonical URL meta tag in the ASP.NET Core razor pages. But there is a catch. It will give you the URL which is supposed to be the right URL for that page. Let me explain.
Say, you have defined a route named "id" for your page and therefore, your URL should look like
http://example.com/product?id=34
The Url.PageLink() will give you exactly that URL as shown above.
Now, if the user adds anything extra on that URL, say,
http://example.com/product?id=34&somethingElse
Then, you will not get that "somethingElse" from this method. And that is why it is exactly good for printing canonical URL meta tag in the HTML page.
Github has a great boilerplate .gitignore
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Rope
.ropeproject
# Django stuff:
*.log
*.pot
# Sphinx documentation
docs/_build/
If you're using typing (introduced in Python 3.5) you can use typing.Optional
, where Optional[X]
is equivalent to Union[X, None]
. It is used to signal that the explicit value of None
is allowed . From typing.Optional:
def foo(arg: Optional[int] = None) -> None:
...
I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.
Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.
One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.
If you were using Cygwin, you might install the ca-certificates package with apt-cyg:
wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /usr/local/bin
apt-cyg install ca-certificates
Try to call your proc in this way:
DECLARE @UserIDout int
EXEC YOURPROC @EmailAddress = 'sdfds', @NickName = 'sdfdsfs', ..., @UserId = @UserIDout OUTPUT
SELECT @UserIDout
One solution is to implement an OnScrollListener
and make changes (like adding items, etc.) to the ListAdapter
at a convenient state in its onScroll
method.
The following ListActivity
shows a list of integers, starting with 40, adding items when the user scrolls to the end of the list.
public class Test extends ListActivity implements OnScrollListener {
Aleph0 adapter = new Aleph0();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(adapter);
getListView().setOnScrollListener(this);
}
public void onScroll(AbsListView view,
int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v, int s) { }
class Aleph0 extends BaseAdapter {
int count = 40; /* starting amount */
public int getCount() { return count; }
public Object getItem(int pos) { return pos; }
public long getItemId(int pos) { return pos; }
public View getView(int pos, View v, ViewGroup p) {
TextView view = new TextView(Test.this);
view.setText("entry " + pos);
return view;
}
}
}
You should obviously use separate threads for long running actions (like loading web-data) and might want to indicate progress in the last list item (like the market or gmail apps do).
Store a reference to the meter instance as a member in Production:
public class Production {
//The other members, properties etc...
private Meter m;
Production(Meter m) {
this.m = m;
}
}
And then in the Meter-class:
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
}
}
Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.
In my case it worked great just by doing the following:
[HttpPost]
public ActionResult DoSomething(int custNum)
{
// Some magic code here...
}
<form id="frmSomething" method="post">
<div>
<!-- Some magic html here... -->
</div>
<button id="btnSubmit" type="submit">Submit</button>
</form>
var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;
btnSubmit.click(function()
{
frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);
btnSubmit.submit();
});
Hope this helps vatos!
The gradle included with Android Studio is located in /Applications/Android Studio.app/plugins/gradle/lib
To go into the Android Studio.app directory I did cd "Android Studio.app"
or you could just do cd /Applications/Android\ Studio.app/plugins/gradle/lib
An array length
is not the number of elements in a array, it is the highest index + 1
. length
property will report correct element count only if there are valid elements in consecutive indices.
var a = [];
a[23] = 'foo';
a.length; // 24
Saying that, there is no way to exclude undefined elements from count without using any form of a loop.
Yes! Abstract classes can have constructors!
Yes, when we define a class to be an Abstract Class it cannot be instantiated but that does not mean an Abstract class cannot have a constructor. Each abstract class must have a concrete subclass which will implement the abstract methods of that abstract class.
When we create an object of any subclass all the constructors in the corresponding inheritance tree are invoked in the top to bottom approach. The same case applies to abstract classes. Though we cannot create an object of an abstract class, when we create an object of a class which is concrete and subclass of the abstract class, the constructor of the abstract class is automatically invoked. Hence we can have a constructor in abstract classes.
Note: A non-abstract class cannot have abstract methods but an abstract class can have a non-abstract method. Reason is similar to that of constructors, difference being instead of getting invoked automatically we can call super(). Also, there is nothing like an abstract constructor as it makes no sense at all.
You are trying to use it as a CSS file, probably by using
<link rel=stylesheet href=ABCD.html>
or
<style>
@import url("ABCD.html");
</style>
This works for me:
moment({minutes: 150}).format('HH:mm') // 01:30
Firstly, it will help if you set the headers of your PHP to serve JSON:
header('Content-type: application/json');
Secondly, it will help to adjust your ajax call:
$.ajax({
url: "main.php",
type: "POST",
dataType: "json",
data: {"action": "loadall", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.
NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).
To solve your other problem, where you need to set scrolled
if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:
var timer = 0;
$(window).scroll(function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
scrolled = $(window).scrollTop();
}, 250);
});
If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").
.each()
should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map
.
var newArray = $(array).map(function(i) {
return $('#event' + i, response).html();
});
Edit: I removed the adding of the prepended 0 since it is suggested to not use that.
If you must have it use
var newArray = $(array).map(function(i) {
var number = '' + i;
if (number.length == 1) {
number = '0' + number;
}
return $('#event' + number, response).html();
});
The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
int[,] list = new int[4,4] {
{1,2,3,4},
{5,6,7,8},
{1,3,2,1},
{5,4,3,2}};
You could also do
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4,4] {
{list1[0],list1[1],list1[2],list1[3]},
{list2[0],list2[1],list2[2],list2[3]},
etc...};
For the sake of completeness of this popular question, since version 1.0.0 of dplyr
, parameter .groups controls the grouping structure of the summarise
function after group_by
summarise help.
With .groups = "drop_last"
, summarise
drops the last level of grouping. This was the only result obtained before version 1.0.0.
library(dplyr)
library(scales)
original <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n()) %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
original
#> # A tibble: 4 x 4
#> # Groups: am [2]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 78.9%
#> 2 0 4 4 21.1%
#> 3 1 4 8 61.5%
#> 4 1 5 5 38.5%
new_drop_last <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "drop_last") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
dplyr::all_equal(original, new_drop_last)
#> [1] TRUE
With .groups = "drop"
, all levels of grouping are dropped. The result is turned into an independent tibble with no trace of the previous group_by
# .groups = "drop"
new_drop <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "drop") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
new_drop
#> # A tibble: 4 x 4
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 46.9%
#> 2 0 4 4 12.5%
#> 3 1 4 8 25.0%
#> 4 1 5 5 15.6%
If .groups = "keep"
, same grouping structure as .data (mtcars, in this case). summarise
does not peel off any variable used in the group_by
.
Finally, with .groups = "rowwise"
, each row is it's own group. It is equivalent to "keep" in this situation
# .groups = "keep"
new_keep <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "keep") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
new_keep
#> # A tibble: 4 x 4
#> # Groups: am, gear [4]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 100.0%
#> 2 0 4 4 100.0%
#> 3 1 4 8 100.0%
#> 4 1 5 5 100.0%
# .groups = "rowwise"
new_rowwise <- mtcars %>%
group_by (am, gear) %>%
summarise (n=n(), .groups = "rowwise") %>%
mutate(rel.freq = scales::percent(n/sum(n), accuracy = 0.1))
dplyr::all_equal(new_keep, new_rowwise)
#> [1] TRUE
Another point that can be of interest is that sometimes, after applying group_by
and summarise
, a summary line can help.
# create a subtotal line to help readability
subtotal_am <- mtcars %>%
group_by (am) %>%
summarise (n=n()) %>%
mutate(gear = NA, rel.freq = 1)
#> `summarise()` ungrouping output (override with `.groups` argument)
mtcars %>% group_by (am, gear) %>%
summarise (n=n()) %>%
mutate(rel.freq = n/sum(n)) %>%
bind_rows(subtotal_am) %>%
arrange(am, gear) %>%
mutate(rel.freq = scales::percent(rel.freq, accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
#> # A tibble: 6 x 4
#> # Groups: am [2]
#> am gear n rel.freq
#> <dbl> <dbl> <int> <chr>
#> 1 0 3 15 78.9%
#> 2 0 4 4 21.1%
#> 3 0 NA 19 100.0%
#> 4 1 4 8 61.5%
#> 5 1 5 5 38.5%
#> 6 1 NA 13 100.0%
Created on 2020-11-09 by the reprex package (v0.3.0)
Hope you find this answer useful.
I wrote extension method
public static string ToMatrixString<T>(this T[,] matrix, string delimiter = "\t")
{
var s = new StringBuilder();
for (var i = 0; i < matrix.GetLength(0); i++)
{
for (var j = 0; j < matrix.GetLength(1); j++)
{
s.Append(matrix[i, j]).Append(delimiter);
}
s.AppendLine();
}
return s.ToString();
}
To use just call the method
results.ToMatrixString();
This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).
When you type in a command at the Unix prompt, you are interacting with the shell.
E.g., #!/bin/csh
refers to the C-shell, /bin/tcsh
the t-shell, /bin/bash
the bash shell, etc.
You can tell which interactive shell you are using the
echo $SHELL
command, or alternatively
env | grep -i shell
You can change your command shell with the chsh
command.
Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.
This page might be of interest as it "translates" between bash and tcsh commands/syntax.
Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh
shell interactively, but often run bash scripts using /bin/bash in the script file.
Aside:
This concept extends to other scripts too. For instance if you program in Python you'd put
#!/usr/bin/python
at the top of your Python program
JTextField
allows us to getText()
and setText()
these are used to get and set the contents of the text field, for example.
text = texfield.getText();
hope this helps
Here's a nice semi cross-browser way to have gradient borders that fade out half way down. Simply by setting the color-stop to rgba(0, 0, 0, 0)
.fade-out-borders {
min-height: 200px; /* for example */
-webkit-border-image: -webkit-gradient(linear, 0 0, 0 50%, from(black), to(rgba(0, 0, 0, 0))) 1 100%;
-webkit-border-image: -webkit-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
-moz-border-image: -moz-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
-o-border-image: -o-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
border-image: linear-gradient(to bottom, black, rgba(0, 0, 0, 0) 50%) 1 100%;
}
<div class="fade-out-border"></div>
Usage explained:
Formal grammar: linear-gradient( [ <angle> | to <side-or-corner> ,]? <color-stop> [, <color-stop>]+ )
\---------------------------------/ \----------------------------/
Definition of the gradient line List of color stops
More here: https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
Vanilla JDBC only supports named parameters in a CallableStatement
(e.g. setString("name", name)
), and even then, I suspect the underlying stored procedure implementation has to support it.
An example of how to use named parameters:
//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
+ "if @id is not null "
+ "select * from sysobjects where id = @id "
+ "else if @name is not null "
+ "select * from sysobjects where name = @name "
+ " end");
stmt.execute();
//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
System.out.println(rs.getString(1));
}
You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.
private void AggiornaContatore()
{
if(this.lblCounter.InvokeRequired)
{
this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});
}
else
{
this.lblCounter.Text = this.index.ToString(); ;
}
}
Please go through this chapter and more from this book to get a clear picture about threading:
http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications
Choose & memorize 1 of the following!!! :)
[\s\S]*
[\w\W]*
[\d\D]*
Explanation:
\s
: whitespace \S
: not whitespace
\w
: word \W
: not word
\d
: digit \D
: not digit
(You can exchange the *
for +
if you want 1 or MORE characters [instead of 0 or more]).
BONUS EDIT:
If you want to match everything on a single line, you can use this:
[^\n]+
Explanation:
^
: not
\n
: linebreak
+
: for 1 character or more
This is the TypeScript version to the question. It is usable after Node 11.0:
import { promises as fs } from 'fs';
async function loadMonoCounter() {
const data = await fs.readFile('monolitic.txt', 'binary');
return Buffer.from(data);
}
For IPv4 addresses, you can use VARCHAR to store them as strings, but also look into storing them as long integesrs INT(11) UNSIGNED
. You can use MySQL's INET_ATON()
function to convert them to integer representation. The benefit of this is it allows you to do easy comparisons on them, like BETWEEN
queries
This may be a little late; but someone will find it useful.
There's a Nuget Package for integrating AdminLTE - a popular Bootstrap template - to MVC5
Simply run this command in your Visual Studio Package Manager console
Install-Package AdminLteMvc
NB: It may take a while to install because it downloads all necessary files as well as create sample full and partial views (.cshtml files) that can guide you as you develop. A sample layout file _AdminLteLayout.cshtml
is also provided.
You'll find the files in ~/Views/Shared/
folder
The vblank_mode
environment variable does the trick. You should then get several hundreds FPS on modern hardware. And you are now able to compare the results with others.
$> vblank_mode=0 glxgears
If you're using a graphical tool. It shows you the schema right next to the table name. In case of DB Browser For Sqlite, click to open the database(top right corner), navigate and open your database, you'll see the information populated in the table as below.
right click on the record/table_name, click on copy create statement and there you have it.
Hope it helped some beginner who failed to work with the commandline.
If you'd like to use CSS3, you can do it pretty simply using background-size, like so:
background-size: 100%;
It is supported by all major browsers (including IE9+). If you'd like to get it working in IE8 and before, check out the answers to this question.
Try this
$.cookie('_cookieName', null, { path: '/' });
The { path: '/' } do the job for you
Activator.CreateInstance()
returns an object, which doesn't have an Output method.
It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.
Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?
If you absolutely want to load the assembly via Assembly.Load
, you will have to go via reflection to call any members on c
Something like type.GetMethod("Output").Invoke(c, null);
should do it.
If you have to check it out manually you can do int a = s.charAt(0)
If the value of a is between 65 to 90 it is upper case.
Is your goal...
Results
in one row and
all the instances of "Bob Jones" in
Archive_Results
in a separate row?Assuming it's #1 you'd want something like...
SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name
If you're into RegEx....
var newURL = testURL.match(new RegExp("[^?]+"))
Error message looks like this
Error message => ORA-00001: unique constraint (schema.unique_constraint_name) violated
ORA-00001 occurs when: "a query tries to insert a "duplicate" row in a table". It makes an unique constraint to fail, consequently query fails and row is NOT added to the table."
Solution:
Find all columns used in unique_constraint, for instance column a, column b, column c, column d collectively creates unique_constraint and then find the record from source data which is duplicate, using following queries:
-- to find <<owner of the table>> and <<name of the table>> for unique_constraint
select *
from DBA_CONSTRAINTS
where CONSTRAINT_NAME = '<unique_constraint_name>';
Then use Justin Cave's query (pasted below) to find all columns used in unique_constraint:
SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = <<name of constraint from the error message>>
AND owner = <<owner of the table>>
AND table_name = <<name of the table>>
-- to find duplicates
select column a, column b, column c, column d
from table
group by column a, column b, column c, column d
having count (<any one column used in constraint > ) > 1;
you can either delete that duplicate record from your source data (which was a select query in my particular case, as I experienced it with "Insert into select") or modify to make it unique or change the constraint.
This a transparency solution for most browsers including IE x
.transparent {
/* Required for IE 5, 6, 7 */
/* ...or something to trigger hasLayout, like zoom: 1; */
width: 100%;
/* Theoretically for IE 8 & 9 (more valid) */
/* ...but not required as filter works too */
/* should come BEFORE filter */
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
/* This works in IE 8 & 9 too */
/* ... but also 5, 6, 7 */
filter: alpha(opacity=50);
/* Older than Firefox 0.9 */
-moz-opacity:0.5;
/* Safari 1.x (pre WebKit!) */
-khtml-opacity: 0.5;
/* Modern!
/* Firefox 0.9+, Safari 2?, Chrome any?
/* Opera 9+, IE 9+ */
opacity: 0.5;
}
You can have - characters in your images. Assume you have a local image (not a local registry) named centos-base-image with tag 7.3.1611.
docker version
Client:
Version: 1.12.6
API version: 1.24
Package version: docker-common-1.12.6-16.el7.centos.x86_64
Go version: go1.7.4
Server:
Version: 1.12.6
API version: 1.24
Package version: docker-common-1.12.6-16.el7.centos.x86_64
Go version: go1.7.4
docker images
REPOSITORY TAG
centos-base-image 7.3.1611
Dockerfile
FROM centos-base-image:7.3.1611
RUN yum -y install epel-release libaio bc flex
Result
Sending build context to Docker daemon 315.9 MB
Step 1 : FROM centos-base-image:7.3.1611
---> c4d84e86782e
Step 2 : RUN yum -y install epel-release libaio bc flex
---> Running in 36d8abd0dad9
...
In the example above FROM
is fetching your local image, you can provide additional instructions to fetch an image from your custom registry (e.g. FROM localhost:5000/my-image:with.tag
). See https://docs.docker.com/engine/reference/commandline/pull/#pull-from-a-different-registry and https://docs.docker.com/registry/#tldr
Finally, if your image is not being resolved when providing a name, try adding a tag to the image when you create it
This GitHub thread describes a similar issue of not finding local images by name.
By omitting a specific tag, docker will look for an image tagged "latest", so either create an image with the :latest tag, or change your FROM
There are 2 following ways preferred to stop a thread.
Create a volatile boolean variable and change its value to false and check inside the thread.
volatile isRunning = false;
public void run() {
if(!isRunning) {return;}
}
Or you can use the interrupt() method which can be receive inside a thread.
SomeThread.interrupt();
public void run() {
if(Thread.currentThread.isInterrupted()) {return;}
}
More info... Some times .swp files might be holded by vm that was running in backgroung. You may see permission denied message when try to delete the files.
It's android:background="@android:color/transparent"
<ImageButton
android:id="@+id/imageButton"
android:src="@android:drawable/ic_menu_delete"
android:background="@android:color/transparent"
/>
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).The question as answered by Daniel is perfctly fine. I wanted to leave a note regarding NULLS. We should be carefull about using NOT IN operator when a column contains NULL values. You won't get any output if your column contains NULL values and you are using the NOT IN operator. This is how it's explained over here http://www.oraclebin.com/2013/01/beware-of-nulls.html , a very good article which I came across and thought of sharing it.
select column1 as xyz,
column2 as pqr,
.....
from TableName;
The includes
(formerly called contains
and include
) method compares objects by reference (or more precisely, with ===
). Because the two object literals of {"b": 2}
in your example represent different instances, they are not equal. Notice:
({"b": 2} === {"b": 2})
> false
However, this will work because there is only one instance of {"b": 2}
:
var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true
On the other hand, the where
(deprecated in v4) and find
methods compare objects by their properties, so they don't require reference equality. As an alternative to includes
, you might want to try some
(also aliased as any
):
_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true
You can import json as simplejson like this:
import json as simplejson
and keep backward compatibility.
You can easily verify a certificate chain with openssl. The fullchain will include the CA cert so you should see details about the CA and the certificate itself.
openssl x509 -in fullchain.pem -text -noout
int g[] = {9,8};
This declares an object of type int[2], and initializes its elements to {9,8}
int (*j) = g;
This declares an object of type int *, and initializes it with a pointer to the first element of g.
The fact that the second declaration initializes j with something other than g is pretty strange. C and C++ just have these weird rules about arrays, and this is one of them. Here the expression g
is implicitly converted from an lvalue referring to the object g into an rvalue of type int*
that points at the first element of g.
This conversion happens in several places. In fact it occurs when you do g[0]
. The array index operator doesn't actually work on arrays, only on pointers. So the statement int x = j[0];
works because g[0]
happens to do that same implicit conversion that was done when j
was initialized.
A pointer to an array is declared like this
int (*k)[2];
and you're exactly right about how this would be used
int x = (*k)[0];
(note how "declaration follows use", i.e. the syntax for declaring a variable of a type mimics the syntax for using a variable of that type.)
However one doesn't typically use a pointer to an array. The whole purpose of the special rules around arrays is so that you can use a pointer to an array element as though it were an array. So idiomatic C generally doesn't care that arrays and pointers aren't the same thing, and the rules prevent you from doing much of anything useful directly with arrays. (for example you can't copy an array like: int g[2] = {1,2}; int h[2]; h = g;
)
Examples:
void foo(int c[10]); // looks like we're taking an array by value.
// Wrong, the parameter type is 'adjusted' to be int*
int bar[3] = {1,2};
foo(bar); // compile error due to wrong types (int[3] vs. int[10])?
// No, compiles fine but you'll probably get undefined behavior at runtime
// if you want type checking, you can pass arrays by reference (or just use std::array):
void foo2(int (&c)[10]); // paramater type isn't 'adjusted'
foo2(bar); // compiler error, cannot convert int[3] to int (&)[10]
int baz()[10]; // returning an array by value?
// No, return types are prohibited from being an array.
int g[2] = {1,2};
int h[2] = g; // initializing the array? No, initializing an array requires {} syntax
h = g; // copying an array? No, assigning to arrays is prohibited
Because arrays are so inconsistent with the other types in C and C++ you should just avoid them. C++ has std::array
that is much more consistent and you should use it when you need statically sized arrays. If you need dynamically sized arrays your first option is std::vector.
The solution was to call...
$scope.$apply();
...in my jQuery event callback.
The thing you are missing is which encoding scheme is being used. There are different ways to encode binary numbers. Look into signed number representations. For 9 bits, the ranges and the amount of numbers that can be represented will differ depending on the system used.
try this:
In [110]: (df.groupby('Company Name')
.....: .agg({'Organisation Name':'count', 'Amount': 'sum'})
.....: .reset_index()
.....: .rename(columns={'Organisation Name':'Organisation Count'})
.....: )
Out[110]:
Company Name Amount Organisation Count
0 Vifor Pharma UK Ltd 4207.93 5
or if you don't want to reset index:
df.groupby('Company Name')['Amount'].agg(['sum','count'])
or
df.groupby('Company Name').agg({'Amount': ['sum','count']})
Demo:
In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
Amount
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
If you want a fairly advanced tool to do some serious poking around, look at the Memory Analyzer project at Eclipse, contributed to them by SAP.
Some of what you can do is mind-blowingly good for finding memory leaks etc -- including running a form of limited SQL (OQL) against the in-memory objects, i.e.
SELECT toString(firstName) FROM com.yourcompany.somepackage.User
Totally brilliant.
If you have only aar
or jar
file itself, or just don't want to use plugins - I've created a simple shell script. You can achieve the same with it - publishing your artifacts to Github and use it as public Maven repo.
You can also just run chrome in incognito mode, that automatically switches off all your plugins/extensions, including any add blockers. Then you can quickly see if the extensions are causing the problem.
You could just change ABI to use older builds:
defaultConfig {
...
ndk {
abiFilters 'armeabi-v7a'
}
...
}
You should also use deprecated NDK by adding this line to gradle.properties
:
android.useDeprecatedNdk=true
For Windows 7 macros are stored at C:\Users\
Username
\AppData\Roaming\Notepad++\shortcuts.xml
.
value
attribute (no CSS needed)Modern browsers will interpret the value
attribute and will display it as you expect. See MDN documentation.
<ol>_x000D_
<li value="3">This is item three.</li>_x000D_
<li value="50">This is item fifty.</li>_x000D_
<li value="100">This is item one hundred.</li>_x000D_
</ol>
_x000D_
Also have a look at the <ol>
article on MDN, especially the documentation for the start
and attribute.
app.controller('NavCtrl', function ($scope, $location, $state, $window, Post, Auth) {
$scope.post = {url: 'http://', title: ''};
$scope.createVariable = function(url) {
$window.location.href = url;
};
$scope.createFixed = function() {
$window.location.href = '/tab/newpost';
};
});
HTML
<button class="button button-icon ion-compose" ng-click="createFixed()"></button>
<button class="button button-icon ion-compose" ng-click="createVariable('/tab/newpost')"></button>
If you have a vector of names already,which there are several ways to create, you can easily use the subset function to keep or drop an object.
dat2 <- subset(dat, select = names(dat) %in% c(KEEP))
In this case KEEP is a vector of column names which is pre-created. For example:
#sample data via Brandon Bertelsen
df <- data.frame(a=rnorm(100),
b=rnorm(100),
c=rnorm(100),
d=rnorm(100),
e=rnorm(100),
f=rnorm(100),
g=rnorm(100))
#creating the initial vector of names
df1 <- as.matrix(as.character(names(df)))
#retaining only the name values you want to keep
KEEP <- as.vector(df1[c(1:3,5,6),])
#subsetting the intial dataset with the object KEEP
df3 <- subset(df, select = names(df) %in% c(KEEP))
Which results in:
> head(df)
a b c d
1 1.05526388 0.6316023 -0.04230455 -0.1486299
2 -0.52584236 0.5596705 2.26831758 0.3871873
3 1.88565261 0.9727644 0.99708383 1.8495017
4 -0.58942525 -0.3874654 0.48173439 1.4137227
5 -0.03898588 -1.5297600 0.85594964 0.7353428
6 1.58860643 -1.6878690 0.79997390 1.1935813
e f g
1 -1.42751190 0.09842343 -0.01543444
2 -0.62431091 -0.33265572 -0.15539472
3 1.15130591 0.37556903 -1.46640276
4 -1.28886526 -0.50547059 -2.20156926
5 -0.03915009 -1.38281923 0.60811360
6 -1.68024349 -1.18317733 0.42014397
> head(df3)
a b c e
1 1.05526388 0.6316023 -0.04230455 -1.42751190
2 -0.52584236 0.5596705 2.26831758 -0.62431091
3 1.88565261 0.9727644 0.99708383 1.15130591
4 -0.58942525 -0.3874654 0.48173439 -1.28886526
5 -0.03898588 -1.5297600 0.85594964 -0.03915009
6 1.58860643 -1.6878690 0.79997390 -1.68024349
f
1 0.09842343
2 -0.33265572
3 0.37556903
4 -0.50547059
5 -1.38281923
6 -1.18317733
I would not use third party libraries, I would log to an xml file.
This is a code sample that do logging to a xml file from different threads:
private static readonly object Locker = new object();
private static XmlDocument _doc = new XmlDocument();
static void Main(string[] args)
{
if (File.Exists("logs.txt"))
_doc.Load("logs.txt");
else
{
var root = _doc.CreateElement("hosts");
_doc.AppendChild(root);
}
for (int i = 0; i < 100; i++)
{
new Thread(new ThreadStart(DoSomeWork)).Start();
}
}
static void DoSomeWork()
{
/*
* Here you will build log messages
*/
Log("192.168.1.15", "alive");
}
static void Log(string hostname, string state)
{
lock (Locker)
{
var el = (XmlElement)_doc.DocumentElement.AppendChild(_doc.CreateElement("host"));
el.SetAttribute("Hostname", hostname);
el.AppendChild(_doc.CreateElement("State")).InnerText = state;
_doc.Save("logs.txt");
}
}
This option comes in curl 7.73.0:
curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg
I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.
ul li{
text-indent: -1em;
}
In jQuery 1.8, this can be done as follows:
(function($){
$.fn.disableSelection = function() {
return this
.attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
};
})(jQuery);
We encountered this error after an upgrade from 2008 to 2014 SQL Server where our some of our previous connection strings for local development had a Data Source=./ like this
<add name="MyLocalDatabase" connectionString="Data Source=./;Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>
Changing that from ./ to either (local) or localhost fixed the problem.
<add name="MyLocalDatabase" connectionString="Data Source=(local);Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>
you can use the package manager to query installed version of gitlab-ce. if it happens to be debian or ubuntu, like this:
dpkg -l | grep gitlab-ce | tr -s [:space:] | cut -d" " -f3
should work similarly with other distributions, assuming you used package manager to install.
I don't believe this is possible. Consider the following example:
>>> a = []
>>> b = a
>>> id(a)
140031712435664
>>> id(b)
140031712435664
The a
and b
point to the same object, but the object can't know what variables point to it.
Try this if you have only one Fragment
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
//TODO: Your Code Here
}
I was struggling with this for a few days until I chanced on the issue when I had to build a new Dropdown. I had several DropDownList controls and attempted to get validation working with no luck. One was databound and the other was filled from the aspx page. I needed to drop the databound one and add a second manual list. In my case Validators failed if you built a dropdown like this and looked at any value (0 or -1) for either a required or compare validator:
<asp:DropDownList ID="DDL_Reason" CssClass="inputDropDown" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>Expired</asp:ListItem>
<asp:ListItem>Lost/Stolen</asp:ListItem>
<asp:ListItem>Location Change</asp:ListItem>
</asp:DropDownList>
However adding the InitialValue like this worked instantly for a compare Validator.
<asp:ListItem Text="-- Select --" Value="-1"></asp:ListItem>
Note: Not in boolean
WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");
if(driver.getPageSource().contains("Ur message"))
{
System.out.println("Pass");
}
else
{
System.out.println("Fail");
}
While that particular idiom is common, even more common is for people to use =
when they mean ==
. The convention when you really mean the =
is to use an extra layer of parentheses:
while ((list = list->next)) { // yes, it's an assignment
The table data on the hot standby slave server is modified while a long running query is running. A solution (PostgreSQL 9.1+) to make sure the table data is not modified is to suspend the replication and resume after the query:
select pg_xlog_replay_pause(); -- suspend
select * from foo; -- your query
select pg_xlog_replay_resume(); --resume
the command posted by Milad and Sandy did not work for me with mstsc. i had to add TERMSRV to the /generic switch. i found this information here: https://gist.github.com/jdforsythe/48a022ee22c8ec912b7e
cmdkey /generic:TERMSRV/<server> /user:<username> /pass:<password>
i could then use mstsc /v:<server>
without getting prompted for the login.
git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.
git checkout <local_branch>
git merge <master>
If you are a beginner like me, here is a good article on git merge vs git rebase. https://www.atlassian.com/git/tutorials/merging-vs-rebasing
rawgit.com solves this problem nicely. For each request, it retrieves the appropriate document from GitHub and, crucially, serves it with the correct Content-Type header.
For some git-commands you can specify --verbose
,
git 'command' --verbose
or
git 'command' -v
.
Make sure the switch is after the actual git command. Otherwise - it won't work!
Also useful:
git 'command' --dry-run
To the people concerned about "boxing" in jsight's answer: there is none. String.valueOf(Object)
is used here, and no unboxing to int
is ever performed.
Whether you use Integer.toString()
or String.valueOf(Object)
depends on how you want to handle possible nulls. Do you want to throw an exception (probably), or have "null" Strings in your list (maybe). If the former, do you want to throw a NullPointerException
or some other type?
Also, one small flaw in jsight's response: List
is an interface, you can't use the new operator on it. I would probably use a java.util.ArrayList
in this case, especially since we know up front how long the list is likely to be.
Here is your simple and easy answer
Go to your class where you want to give a negative margin then copy and paste this inside the class.
Example for negative margin top
mt-n3
Example for negative margin bottom
mb-n2
Please put your related value and try this :
declare @x int, @y varchar(200),
@dt1 smalldatetime = '2014-01-21 10:00:00',
@dt2 smalldatetime = getdate()
set @x = datediff (HOUR, @dt1, @dt2)
set @y = @x * 60 - DATEDIFF(minute,@dt1, @dt2)
set @y = cast(@x as varchar(200)) + ':' + @y
Select @y
Now that bash is out for windows 10, if you want to access program files from bash, you can do it like so:
cd /mnt/c/Program\ Files
.
I guess you will get ORA-01741: illegal zero-length identifier if you use the following
SELECT "" AS Contact FROM Customers;
And if you use the following 2 statements, you will be getting the same null value populated in the column.
SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;
http://jsbin.com/qamuyajipo/3/edit?html,output
.circle {
border: 1px solid red;
background-color: #FFFFFF;
height: 100px;
-moz-border-radius:75px;
-webkit-border-radius: 75px;
width: 100px;
}
Explain only shows how the optimizer thinks the query will execute.
To show the real plan, you will need to run the sql once. Then use the same session run the following:
@yoursql
select * from table(dbms_xplan.display_cursor())
This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".
This is not a perfect solution but it sort of does work.
In the select tag, include the following attributes where 'n' is the number of dropdown rows that would be visible.
<select size="1" position="absolute" onclick="size=(size!=1)?n:1;" ...>
There are three problems with this solution. 1) There is a quick flash of all the elements shown during the first mouse click. 2) The position is set to 'absolute' 3) Even if there are less than 'n' items the dropdown box will still be for the size of 'n' items.
If the two byte arrays you mention is your entire key, the values are in the range 0-51, unique and the order within the a and b arrays is insignificant, my math tells me that there is only just about 26 million possible permutations and that you likely are trying to fill the map with values for all possible keys.
In this case, both filling and retrieving values from your data store would of course be much faster if you use an array instead of a HashMap and index it from 0 to 25989599.
the worked proposition for me is __call__
on class who create list of little numbers:
import itertools
class SmallNumbers:
def __init__(self, how_much):
self.how_much = int(how_much)
self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
start = 10
end = 100
for cmb in range(2, len(str(self.how_much)) + 1):
self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
start *= 10
end *= 10
def __call__(self, number, *args, **kwargs):
return self.generated_list[number]
def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
multi_work_list = eval(str('self.work_list,') * combinations)
nbr = 0
for subset in itertools.product(*multi_work_list):
if is_upper_then <= nbr < is_under_then:
self.generated_list.append(''.join(subset))
if self.how_much == nbr:
break
nbr += 1
and to run it:
if __name__ == '__main__':
sm = SmallNumbers(56)
print(sm.generated_list)
print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
print('The Best', sm(15), sm(55), sm(49), sm(0))
result
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0
float currentSize = textEdit.getTextSize(); // default size
float newSize = currentSize * 2.0F; // new size is twice bigger than default one
textEdit.setTextSize(newSize);
Delete the most recent commit, keeping the work you've done:
git reset --soft HEAD~1
Delete the most recent commit, destroying the work you've done:
git reset --hard HEAD~1
#define debug_print(FMT, ARGS...) do { \
if (DEBUG) \
fprintf(stderr, "%s:%d " FMT "\n", __FUNCTION__, __LINE__, ## ARGS); \
} while (0)
MongoDB will find only one matching document which matches the query criteria when you are issuing an update command, whichever document matches first happens to be get updated, even if there are more documents which matches the criteria will get ignored.
so to overcome this we can specify "MULTI" option in your update statement, meaning update all those documnets which matches the query criteria. scan for all the documnets in collection finding those which matches the criteria and update :
db.test.update({"foo":"bar"},{"$set":{"test":"success!"}}, {multi:true} )
This worked for me. Each month on X axis
str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)
It seems that Bootstrap doesn't support disabled links. Instead of trying to add a Bootstrap class, you could add a class by your own and add some styling to it, just like this:
a.disabled {_x000D_
/* Make the disabled links grayish*/_x000D_
color: gray;_x000D_
/* And disable the pointer events */_x000D_
pointer-events: none;_x000D_
}
_x000D_
<!-- Make the disabled links unfocusable as well -->_x000D_
<a href="#" class="disabled" tabindex="-1">Link to disable</a><br/>_x000D_
<a href="#">Non-disabled Link</a>
_x000D_
Coverting the first letter of word capital
input:
hello world
String A = hello;
String B = world;
System.out.println(A.toUpperCase().charAt(0)+A.substring(1) + " " + B.toUpperCase().charAt(0)+B.substring(1));
Output:
Hello World
You can now do this by including the sound when building a notification rather than calling the sound separately.
//Define Notification Manager
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(message)
.setSound(soundUri); //This sets the sound to play
//Display notification
notificationManager.notify(0, mBuilder.build());