Escape sequences must be interpreted by SOMETHING to be converted to color. The standard CMD.EXE used by java when started from the command line, doesn't support this so therefore Java does not.
You can use attributes from the System.ComponentModel.DataAnnotations
namespace to set validation rules. Refer Model Validation - By Mike Wasson for details.
Also refer video ASP.NET Web API, Part 5: Custom Validation - Jon Galloway
Other References
<Prefix>
&
for killing a window
<Prefix>
x
for killing a pane
If there is only one pane (i.e. the window is not split into multiple panes, <Prefix>
x
would kill the window)
As always iterated, <Prefix>
is generally CTRL+b
. (I think for beginner questions, we can just say CTRL+b
all the time, and not talk about prefix at all, but anyway :) )
An example with code, perhaps.
Here, the ConcreteRegistry is a singleton in a poker game that allows the behaviours all the way up the package tree access the few, core interfaces of the game (i.e., the facades for the model, view, controller, environment, etc.):
http://www.edmundkirwan.com/servlet/fractal/cs1/frac-cs40.html
Ed.
I have just write one and test it on gentoo in virtualbox.
// get_mac.c
#include <stdio.h> //printf
#include <string.h> //strncpy
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h> //ifreq
#include <unistd.h> //close
int main()
{
int fd;
struct ifreq ifr;
char *iface = "enp0s3";
unsigned char *mac = NULL;
memset(&ifr, 0, sizeof(ifr));
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) {
mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
//display mac address
printf("Mac : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}
close(fd);
return 0;
}
You can do:
if not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
else:
do sth. # condition is satisfied
Using a loop:
while not (u0 <= u <= u0+step):
u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied
This is how a beginner wrapped one's head around Closures like a function is wrapped inside of a functions body also known as Closures.
Definition from the book Speaking JavaScript "A closure is a function plus the connection to the scope in which the function was created" -Dr.Axel Rauschmayer
So what could that look like? Here is an example
function newCounter() {
var counter = 0;
return function increment() {
counter += 1;
}
}
var counter1 = newCounter();
var counter2 = newCounter();
counter1(); // Number of events: 1
counter1(); // Number of events: 2
counter2(); // Number of events: 1
counter1(); // Number of events: 3
newCounter closes over increment, counter can be referenced to and accessed by increment.
counter1 and counter2 will keep track of their own value.
Simple but hopefully a clear perspective of what a closure is around all these great and advanced answers.
Terminology : The difference between TRUE north and Magnetic North is known as "variation" not declination. The difference between what your compass reads and the magnetic heading is known as "deviation" and varies with heading. A compass swing identifies device errors and allows corrections to be applied if the device has correction built in. A magnetic compass will have a deviation card which describes the device error on any heading.
Declination : A term used in Astro navigation : Declination is like latitude. It reports how far a star is from the celestial equator. To find the declination of a star follow an hour circle "straight down" from the star to the celestial equator. The angle from the star to the celestial equator along the hour circle is the star's declination.
Exact way I fixed this based on feedback above since I couldn't get it to work at first:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list"
>
</ListView>
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addPreferencesFromResource(R.xml.preferences);
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:key="upgradecategory"
android:title="Upgrade" >
<Preference
android:key="download"
android:title="Get OnCall Pager Pro"
android:summary="Touch to download the Pro Version!" />
</PreferenceCategory>
</PreferenceScreen>
You have to give height and width to that image.
eg. height : 200px
and width : 200px
also give border-radius:50%;
to create circle you have to give equal height and width
if you are using bootstrap then give height and width and img-circle
class to img
Rather than implementing another method just to work around this error in a particular IDE, does the following make sense? PyCharm doesn't suggest anything with this implementation.
class Animal:
def __init__(self):
print("Animal created")
def eat(self):
not self # <-- This line here
print("I am eating")
my_animal = Animal()
Here is another light JavaScript Slider that seems to fit your needs.
Use the % instead of the / when you divide. This will return the remainder for you. So in your case
26 % 7 = 5
I think you want
output <- do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))
i.e. combining @BlueMagister's use of do.call(rbind,...)
with an lapply
statement to convert the individual list elements into 11*10 matrices ...
Benchmarks (showing @flodel's unlist
solution is 5x faster than mine, and 230x faster than the original approach ...)
n <- 1000
z <- replicate(n,matrix(1:110,ncol=10,byrow=TRUE),simplify=FALSE)
library(rbenchmark)
origfn <- function(z) {
output <- NULL
for(i in 1:length(z))
output<- rbind(output,matrix(z[[i]],ncol=10,byrow=TRUE))
}
rbindfn <- function(z) do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))
unlistfn <- function(z) matrix(unlist(z), ncol = 10, byrow = TRUE)
## test replications elapsed relative user.self sys.self
## 1 origfn(z) 100 36.467 230.804 34.834 1.540
## 2 rbindfn(z) 100 0.713 4.513 0.708 0.012
## 3 unlistfn(z) 100 0.158 1.000 0.144 0.008
If this scales appropriately (i.e. you don't run into memory problems), the full problem would take about 130*0.2 seconds = 26 seconds on a comparable machine (I did this on a 2-year-old MacBook Pro).
Per this comment (and I checked that this is true), rado's answer is very close but leaves git in a detached head state. Instead, remove HEAD
and use this to remove <commit-id>
from the branch you're on:
git rebase --onto <commit-id>^ <commit-id>
Please try CURRENT_TIME()
or now()
functions
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"
OR
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"
OR you could try with PHP date
function here:
$date = date("Y-m-d H:i:s");
I use this method:
public static String getURL(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
// Reconstruct original requesting URL
StringBuilder url = new StringBuilder();
url.append(scheme).append("://").append(serverName);
if (serverPort != 80 && serverPort != 443) {
url.append(":").append(serverPort);
}
url.append(contextPath).append(servletPath);
if (pathInfo != null) {
url.append(pathInfo);
}
if (queryString != null) {
url.append("?").append(queryString);
}
return url.toString();
}
It depends on what you mean by stop. If it's in a function that can return void then:
if(a && b) {
// do something
}else{
// "stop"
return;
}
You need both a value and a field to assign it to. The value is TableField + 1
, so the assignment is:
SET TableField = TableField + 1
It's built in from Sublime Editor 2 at least. Just press the following and it balances the HTML-tag
Shortcut (Mac): Shift + Command + A
Shortcut (Windows): Control + Alt + A
I think it's a better way to bind on the service itself instead of the attributes on it.
Here's why:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<body ng-app="BindToService">
<div ng-controller="BindToServiceCtrl as ctrl">
ArrService.arrOne: <span ng-repeat="v in ArrService.arrOne">{{v}}</span>
<br />
ArrService.arrTwo: <span ng-repeat="v in ArrService.arrTwo">{{v}}</span>
<br />
<br />
<!-- This is empty since $scope.arrOne never changes -->
arrOne: <span ng-repeat="v in arrOne">{{v}}</span>
<br />
<!-- This is not empty since $scope.arrTwo === ArrService.arrTwo -->
<!-- Both of them point the memory space modified by the `push` function below -->
arrTwo: <span ng-repeat="v in arrTwo">{{v}}</span>
</div>
<script type="text/javascript">
var app = angular.module("BindToService", []);
app.controller("BindToServiceCtrl", function ($scope, ArrService) {
$scope.ArrService = ArrService;
$scope.arrOne = ArrService.arrOne;
$scope.arrTwo = ArrService.arrTwo;
});
app.service("ArrService", function ($interval) {
var that = this,
i = 0;
this.arrOne = [];
that.arrTwo = [];
$interval(function () {
// This will change arrOne (the pointer).
// However, $scope.arrOne is still same as the original arrOne.
that.arrOne = that.arrOne.concat([i]);
// This line changes the memory block pointed by arrTwo.
// And arrTwo (the pointer) itself never changes.
that.arrTwo.push(i);
i += 1;
}, 1000);
});
</script>
</body>
You can play it on this plunker.
UPDATE R
SET R.status = '0'
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P
ON R.pid = P.id
WHERE R.id = '17190'
AND P.shopkeeper = '89137';
If using function onclick DIV and then want to disable click it again you can use this :
for (var i=0;i<document.getElementsByClassName('ads').length;i++){
document.getElementsByClassName('ads')[i].onclick = false;
}
Example :
HTML
<div id='mybutton'>Click Me</div>
Javascript
document.getElementById('mybutton').onclick = function () {
alert('You clicked');
this.onclick = false;
}
RFC7231:
" URIs are intended to be shared, not secured, even when they identify secure resources. URIs are often shown on displays, added to templates when a page is printed, and stored in a variety of unprotected bookmark lists. It is therefore unwise to include information within a URI that is sensitive, personally identifiable, or a risk to disclose.
Authors of services ought to avoid GET-based forms for the submission of sensitive data because that data will be placed in the request-target. Many existing servers, proxies, and user agents log or display the request-target in places where it might be visible to third parties. Such services ought to use POST-based form submission instead."
This RFC clearly states that sensitive data should not be submitted using GET. Because of this remark, some implementors might not handle data obtained from the query portion of a GET request with the same care. I'm working on a protocol myself that ensures integrity of data. According to this spec I shouldn't have to guarantee integrity of the GET data (which I will because nobody adheres to these specs)
however, there are still cases where you need the service locator pattern. for example, i have a controller bean, this controller might have some default service beans, which can be dependency injected by configuration. while there could also be many additional or new services this controller can invoke now or later, which then need the service locator to retrieve the service beans.
One-liner:
$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))"
You can use /* tslint:disable-next-line */
to locally disable tslint. However, as this is a compiler error disabling tslint might not help.
You can always temporarily cast $
to any
:
delete ($ as any).summernote.options.keyMap.pc.TAB
which will allow you to access whatever properties you want.
Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:
if (false) {
// @ts-ignore: Unreachable code error
console.log("hello");
}
Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any
instead as that better expresses intent.
i don't like the idea of using Reflection for that.
Not only dangerous for missing it in some refactoring, but it can also be denied by SecurityManager
.
FutureTask
is a good option as the other options from the java.util.concurrent package.
My favorite for simple tasks:
Executors.newSingleThreadExecutor().submit(task);
little bit shorter than creating a Thread (task is a Callable or a Runnable)
defaultdict
means that if a key is not found in the dictionary, then instead of a KeyError
being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.
For example:
somedict = {}
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0
Using a shebang line to invoke the appropriate interpreter is not just for BASH. You can use the shebang for any interpreted language on your system such as Perl, Python, PHP (CLI) and many others. By the way, the shebang
#!/bin/sh -
(it can also be two dashes, i.e. --
) ends bash options everything after will be treated as filenames and arguments.
Using the env
command makes your script portable and allows you to setup custom environments for your script hence portable scripts should use
#!/usr/bin/env bash
Or for whatever the language such as for Perl
#!/usr/bin/env perl
Be sure to look at the man
pages for bash
:
man bash
and env
:
man env
Note: On Debian and Debian-based systems, like Ubuntu, sh
is linked to dash
not bash
. As all system scripts use sh
. This allows bash to grow and the system to stay stable, according to Debian.
Also, to keep invocation *nix like I never use file extensions on shebang invoked scripts, as you cannot omit the extension on invocation on executables as you can on Windows. The file command can identify it as a script.
Splendid answer from Ben. However I'm surprised that the Affinity Propagation (AP) method has been here suggested just to find the number of cluster for the k-means method, where in general AP do a better job clustering the data. Please see the scientific paper supporting this method in Science here:
Frey, Brendan J., and Delbert Dueck. "Clustering by passing messages between data points." science 315.5814 (2007): 972-976.
So if you are not biased toward k-means I suggest to use AP directly, which will cluster the data without requiring knowing the number of clusters:
library(apcluster)
apclus = apcluster(negDistMat(r=2), data)
show(apclus)
If negative euclidean distances are not appropriate, then you can use another similarity measures provided in the same package. For example, for similarities based on Spearman correlations, this is what you need:
sim = corSimMat(data, method="spearman")
apclus = apcluster(s=sim)
Please note that those functions for similarities in the AP package are just provided for simplicity. In fact, apcluster() function in R will accept any matrix of correlations. The same before with corSimMat() can be done with this:
sim = cor(data, method="spearman")
or
sim = cor(t(data), method="spearman")
depending on what you want to cluster on your matrix (rows or cols).
First, a clarification, Java is not fully static-compiled and linked in the way C++. It is compiled into bytecode, which is then interpreted by a JVM. The JVM can go and do just-in-time compilation to the native machine language, but doesn't have to do it.
More to the point: I think interactivity is the main practical difference. Since everything is interpreted, you can take a small excerpt of code, parse and run it against the current state of the environment. Thus, if you had already executed code that initialized a variable, you would have access to that variable, etc. It really lends itself way to things like the functional style.
Interpretation, however, costs a lot, especially when you have a large system with a lot of references and context. By definition, it is wasteful because identical code may have to be interpreted and optimized twice (although most runtimes have some caching and optimizations for that). Still, you pay a runtime cost and often need a runtime environment. You are also less likely to see complex interprocedural optimizations because at present their performance is not sufficiently interactive.
Therefore, for large systems that are not going to change much, and for certain languages, it makes more sense to precompile and prelink everything, do all the optimizations that you can do. This ends up with a very lean runtime that is already optimized for the target machine.
As for generating executables, that has little to do with it, IMHO. You can often create an executable from a compiled language. But you can also create an executable from an interpreted language, except that the interpreter and runtime is already packaged in the exectuable and hidden from you. This means that you generally still pay the runtime costs (although I am sure that for some language there are ways to translate everything to a tree executable).
I disagree that all languages could be made interactive. Certain languages, like C, are so tied to the machine and the entire link structure that I'm not sure you can build a meaningful fully-fledged interactive version
This is valid YAML:
jobs:
- name: A
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
- name: B
schedule: "0 0/5 * 1/1 * ? *"
type: mongodb.cluster
config:
host: mongodb://localhost:27017/admin?replicaSet=rs
minSecondaries: 2
minOplogHours: 100
maxSecondaryDelay: 120
Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.
In my case, the problem was a folder in the project directory containing 300k+ files totaling 11Gb. This was just a temporary folder with images results of some computation. After moving this folder out of the project structure, the slowness disappeared. I hope this can help someone, please check your project structure to see if there is anything that is not necessary.
"How do I do that? I explored PHPMyAdmin, and I can't find a "change engine" functionality."
In direct response to this part of your question, you can issue an ALTER TABLE tbl engine=InnoDB;
and it'll recreate the table in the proper engine.
run the following command by creating a virtual enviroment using python 3 and run
pip3 install opencv-python
to check it has installed correctly run
python3 -c "import cv2"
It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.
I did it and my problem solved.
Expanding on scrappedocola/renergy's idea, you can turn the JavaScript into a bookmarklet that executes against the javascript:
uri so the code can be re-used easily across multiple pages without having to open up the dev tools or keep anything on your clipboard.
Just run the following snippet and drag the link to your bookmarks/favorites bar:
<a href="javascript: var el = document.querySelectorAll('style,link');_x000D_
for (var i=0; i<el.length; i++) {_x000D_
el[i].parentNode.removeChild(el[i]); _x000D_
};">_x000D_
Remove Styles _x000D_
</a>
_x000D_
getElementsByTagName('*')
and have to check and act on each individually.$('style,link[rel="stylesheet"]').remove()
when the extra javascript is not overwhelmingly cumbersome.If you are using Primefaces, you should insert inside the the .xhtml file so it converts correctly to java integer. For example:
<p:selectCheckboxMenu
id="frameSelect"
widgetVar="frameSelectBox"
filter="true"
filterMatchMode="contains"
label="#{messages['frame']}"
value="#{platform.frameBean.selectedFramesTypesList}"
converter="javax.faces.Integer">
<f:selectItems
value="#{platform.frameBean.framesTypesList}"
var="area"
itemLabel="#{area}"
itemValue="#{area}" />
</p:selectCheckboxMenu>
Hadley's tidyr
just got this amazing function drop_na
library(tidyr)
DF %>% drop_na(y)
x y z
1 1 0 NA
2 2 10 33
The query below will give you a list of all users and their permissions on the table in a schema.
select a.schemaname, a.tablename, b.usename,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'select') as has_select,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'insert') as has_insert,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'update') as has_update,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'delete') as has_delete,
HAS_TABLE_PRIVILEGE(usename, quote_ident(schemaname) || '.' || quote_ident(tablename), 'references') as has_references
from pg_tables a, pg_user b
where a.schemaname = 'your_schema_name' and a.tablename='your_table_name';
More details on has_table_privilages
can be found here.
process.cwd()
returns directory where command has been executed (not directory of the node package) if it's has not been changed by 'process.chdir' inside of application.__filename
returns absolute path to file where it is placed.__dirname
returns absolute path to directory of __filename
.If you need to load files from your module directory you need to use relative paths.
require('../lib/test');
instead of
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
require(lib + '/test');
It's always relative to file where it called from and don't depend on current work dir.
You can use both with relatively few issues. Twitter Bootstrap uses jQuery 1.7.1 (as of this writing), and I can't think of any reasons why you cannot integrate additional Jquery UI components into your HTML templates.
I've been using a combination of HTML5 Boilerplate & Twitter Bootstrap built at Initializr.com. This combines two awesome starter templates into one great starter project. Check out the details at http://html5boilerplate.com/ and http://www.initializr.com/ Or to get started right away, go to http://www.initializr.com/, click the "Bootstrap 2" button, and click "Download It". This will give you all the js and css you need to get started.
And don't be scared off by HTML5 and CSS3. Initializr and HTML5 Boilerplate include polyfills and IE specific code that will allow all features to work in IE 6, 7 8, and 9.
The use of LESS in Twitter Bootstrap is also optional. They use LESS to compile all the CSS that is used by Bootstrap, but if you just want to override or add your own styles, they provide an empty css file for that purpose.
There is also a blank js file (script.js) for you to add custom code. This is where you would add your handlers or selectors for additional jQueryUI components.
If you have another list that contains all the items you would like to add you can do arList.addAll(otherList)
. Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll()
method, with something like
Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
arList.addAll(Arrays.asList(otherList));
or, if you don't want to create that unnecessary array:
arList.addAll(Arrays.asList(1, 2, 3, 4, 5));
Otherwise you will have to have some sort of loop that adds the values to the list individually.
HTML
<div id="dash">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed ipsum a urna ac
quam.</p>
</div>
jQuery
var p = $('#dash p');
var ks = $('#dash').height();
while ($(p).outerHeight() > ks) {
$(p).text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
CSS
#dash {
width: 400px;
height: 60px;
overflow: hidden;
}
#dash p {
padding: 10px;
margin: 0;
}
RESULT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et...
You can bind a single click event to a page for all elements, no matter if they are already on that page or if they will arrive at some future time, like that:
$(document).bind('click', function (e) {
var target = $(e.target);
if (target.is('.myclass')) {
e.preventDefault(); // if you want to cancel the event flow
// do something
} else if (target.is('.myotherclass')) {
e.preventDefault();
// do something else
}
});
Been using it for a while. Works like a charm.
In jQuery 1.7 and later, it is recommended to use .on()
in place of bind or any other event delegation method, but .bind()
still works.
by using cat
and -A
you can see new lines as $
, tabs as ^I
cat -A myfile
Isn't the difference between your declaration of USERID the problem
JOB: UserID is Varchar
USER: UserID is Number?
after running different aforementioned functions for factorial, by different people, turns out that math.factorial is the fastest to calculate the factorial.
find running times for different functions in the attached image
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
var a= [1, 2, 3, '3'];
var b = [1, 2, 3];
var c = a.filter(function (i) { return ! ~b.indexOf(i); });
alert(c.length);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();
this will work as you asked without CHAR(38):
update t set country = 'Trinidad and Tobago' where country = 'trinidad & '|| 'tobago';
create table table99(col1 varchar(40));
insert into table99 values('Trinidad &' || ' Tobago');
insert into table99 values('Trinidad &' || ' Tobago');
insert into table99 values('Trinidad &' || ' Tobago');
insert into table99 values('Trinidad &' || ' Tobago');
SELECT * FROM table99;
update table99 set col1 = 'Trinidad and Tobago' where col1 = 'Trinidad &'||' Tobago';
If you've already pushed, first find the commit you want to be at HEAD ($GIT_COMMIT_HASH_HERE), then run the following:
git reset --hard $GIT_COMMIT_HASH_HERE
git push origin HEAD --force
Then each place the repo has been cloned, run:
git reset --hard origin/master
%08x
means that every number should be printed at least 8 characters wide with filling all missing digits with zeros, e.g. for '1' output will be 00000001
How to get the last N rows of a pandas DataFrame?
If you are slicing by position, __getitem__
(i.e., slicing with[]
) works well, and is the most succinct solution I've found for this problem.
pd.__version__
# '0.24.2'
df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df
A B
0 a 1
1 a 2
2 a 3
3 b 4
4 b 5
5 b 6
6 b 7
7 c 8
df[-3:]
A B
5 b 6
6 b 7
7 c 8
This is the same as calling df.iloc[-3:]
, for instance (iloc
internally delegates to __getitem__
).
As an aside, if you want to find the last N rows for each group, use groupby
and GroupBy.tail
:
df.groupby('A').tail(2)
A B
1 a 2
2 a 3
5 b 6
6 b 7
7 c 8
import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
$sess = session_status();
if ($sess == PHP_SESSION_NONE) {
session_start();
}
} else {
if (!$_SESSION) {
session_start();
}
}
Actually, it is now too late to explain it here anyway as its been solved. This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order. The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.
Just an another ussage example for Notepad++ (regular expression search mode)
Find: (g|c|u|d)(et|reate|pdate|elete)_(.)([^\s (]+)
Replace: \U\1\E$2\U\3\E$4
Example:
get_user -> GetUser
create_user -> CreateUser
update_user -> UpdateUser
delete_user -> DeleteUser
<?php echo substr("abcabcabc", 0, -3); ?>
memdump
There is a memcdump
(sometimes memdump
) command for that (part of libmemcached-tools
), e.g.:
memcdump --servers=localhost
which will return all the keys.
memcached-tool
In the recent version of memcached
there is also memcached-tool
command, e.g.
memcached-tool localhost:11211 dump | less
which dumps all keys and values.
See also:
Just stick in a file and call it "ServiceModelSamples.bat" or something.
You could add "@echo off" as line one, so the command doesn't get printed to the screen:
@echo off
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service
Add Nuget package - Microsoft.EntityFrameworkCore.Relational
using Microsoft.EntityFrameworkCore;
...
await YourContext.Database.ExecuteSqlCommandAsync("... @p0, @p1", param1, param2 ..)
This will return the row numbers as an int
Maybe try something like:
import matplotlib.pyplot as plt
import numpy
from scipy import stats
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = stats.kde.gaussian_kde(data)
x = numpy.arange(0., 8, .1)
plt.plot(x, density(x))
plt.show()
You can easily replace gaussian_kde()
by a different kernel density estimate.
I was facing a problem like this, and had the idea of simply changing the innerHTML of the problematic object's children.
adiv.innerHTML = "<div...> the original html that js uses </div>";
Seems dirty, but it saved my life, as it works!
In case someone is still struggling with this issue:
I faced similar issue where 2 requests were hitting the server at the same time. There was no situation like below:
T1:
BEGIN TRANSACTION
INSERT TABLE A
INSERT TABLE B
END TRANSACTION
T2:
BEGIN TRANSACTION
INSERT TABLE B
INSERT TABLE A
END TRANSACTION
So, I was puzzled why deadlock is happening.
Then I found that there was parent child relation ship between 2 tables because of foreign key. When I was inserting a record in child table, the transaction was acquiring a lock on parent table's row. Immediately after that I was trying to update the parent row which was triggering elevation of lock to EXCLUSIVE one. As 2nd concurrent transaction was already holding a SHARED lock, it was causing deadlock.
Refer to: https://blog.tekenlight.com/2019/02/21/database-deadlock-mysql.html
I have been having the same issue and tried everything written here but it was still giving me the same error. Turned out to be NULL value in the column which I was trying to convert.
Removing the NULL value solved my issue.
Cheers, Ahmed
As taken from here;
ROOT_DIR:=$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
Shows up as;
$ cd /home/user/
$ make -f test/Makefile
/home/user/test
$ cd test; make Makefile
/home/user/test
Hope this helps
display PDF file into WinForms
Displaying a pdf file from Winform.
displaying a pdf on a windows form?
How to display PDF or Word's DOC/DOCX inside WinForms window?
$(document).ready(function(){_x000D_
$('.cliked').click(function() {_x000D_
$(".cliked").removeClass("liactive");_x000D_
$(this).addClass("liactive");_x000D_
});_x000D_
});
_x000D_
.liactive {_x000D_
background: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul_x000D_
className="sidebar-nav position-fixed "_x000D_
style="height:450px;overflow:scroll"_x000D_
>_x000D_
<li>_x000D_
<a className="cliked liactive" href="#">_x000D_
check Kyc Status_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Investments_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My SIP_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Tax Savers Fund_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Transaction History_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Invest Now_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
My Profile_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
FAQ`s_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Suggestion Portfolio_x000D_
</a>_x000D_
</li>_x000D_
<li>_x000D_
<a className="cliked" href="#">_x000D_
Bluk Lumpsum / Bulk SIP_x000D_
</a>_x000D_
</li>_x000D_
</ul>;
_x000D_
In this case a relatively simple GROUP BY
can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER()
:
Runnable example (Wofkflow20 error in original data corrected)
;WITH partitioned AS (
SELECT company
,workflow
,date
,other_columns
,ROW_NUMBER() OVER(PARTITION BY company, workflow
ORDER BY date) AS seq
FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1
A much simpler alternative is to get the information from the connection object itself. For example:
IDbConnection connection = new SqlConnection(connectionString);
var dbName = connection.Database;
Similarly you can get the server name as well from the connection object.
DbConnection connection = new SqlConnection(connectionString);
var server = connection.DataSource;
In Access, you will probably find a Join is quicker unless your tables are very small:
SELECT DISTINCT Table1.Column1
FROM Table1
LEFT JOIN Table2
ON Table1.Column1 = Table2.Column1
WHERE Table2.Column1 Is Null
This will exclude from the list all records with a match in Table2.
This method seems to do what you want:
$('#email-field-only').valid();
Through SSMS, I created a new schema by:
I found this post to change the schema, but was also getting the same permissions error when trying to change to the new schema. I have several databases listed in my SSMS, so I just tried specifying the database and it worked:
USE (yourservername)
ALTER SCHEMA exe TRANSFER dbo.Employees
This query:
SELECT ROW_NUMBER() OVER(ORDER BY UserId) From Users WHERE UserName='Joe'
will return all rows where the UserName
is 'Joe'
UNLESS you have no UserName='Joe'
They will be listed in order of UserID
and the row_number
field will start with 1 and increment however many rows contain UserName='Joe'
If it does not work for you then your WHERE
command has an issue OR there is no UserID
in the table. Check spelling for both fields UserID
and UserName
.
Unique Keys: The columns in which no two rows are similar
Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.
Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.
As far as I can tell, two things:
You can also use the transform: scale("")
option.
You may check good article here:
http://blog.magalter.com/magento-database-size
It has instructions how to check database size, truncate some tables and how to configure automatic table cleaning.
On the side note, here is how the various plyr
functions correspond to the base *apply
functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)
Base function Input Output plyr function
---------------------------------------
aggregate d d ddply + colwise
apply a a/l aaply / alply
by d l dlply
lapply l l llply
mapply a a/l maply / mlply
replicate r a/l raply / rlply
sapply l a laply
One of the goals of plyr
is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply()
is easily passable to ldply()
to produce useful output, etc.
Conceptually, learning plyr
is no more difficult than understanding the base *apply
functions.
plyr
and reshape
functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:
Related functions
tapply
andsweep
have no corresponding function inplyr
, and remain useful.merge
is useful for combining summaries with the original data.
Here I found the easiest solution. check out this..
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// view.loadUrl("about:blank");
mWebView.stopLoading();
if (!mUtils.isInterentConnection()) {
Toast.makeText(ReportingActivity.this, "Please Check Internet Connection!", Toast.LENGTH_SHORT).show();
}
super.onReceivedError(view, errorCode, description, failingUrl);
}
And here is isInterentConnection() method...
public boolean isInterentConnection() {
ConnectivityManager manager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager != null) {
NetworkInfo info[] = manager.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
$text = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"
$text.split(';')[1].split(' ')
Another common mistake is to still have or have upgraded an older Rails app to Rails 5+ and be putting require 'spec_helper'
at the top of each test file. This should changed to require 'rails_helper'
. If you are seeing different behavior between the rake task (rake spec
) and when you run a single spec (rspec path/to/spec.rb
), this is a common reason
the best solution is to
1) make sure you are using require 'rails_helper'
at the top of each of your spec files — not the older-style require 'spec_helper'
2) use the rake spec SPEC=path/to/spec.rb
syntax
the older-style rspec path/to/spec.rb
I think should be considered out-of-vogue by the community at this time in 2020 (but of course you will get it to work, other considerations aside)
sty is similar to colorama, but it's less verbose, supports 8-bit and 24-bit (RGB) colors, supports all effects (bold, underline, etc.) allows you to register your own styles, is fully typed, supports muting, is really flexible, well documented and more...
Examples:
from sty import fg, bg, ef, rs
foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs
# Add custom colors:
from sty import Style, RgbFg
fg.orange = Style(RgbFg(255, 150, 50))
buf = fg.orange + 'Yay, Im orange.' + fg.rs
print(foo, bar, baz, qux, qui, buf, sep='\n')
prints:
Demo:
I did this;
In controller:
public ActionResult Index()
{
var invoices = db.Invoices;
var categories = db.Categories.ToList();
ViewData["MyData"] = categories; // Send this list to the view
return View(invoices.ToList());
}
In view:
@model IEnumerable<abc.Models.Invoice>
@{
ViewBag.Title = "Invoices";
}
@{
var categories = (List<Category>) ViewData["MyData"]; // Cast the list
}
@foreach (var c in @categories) // Print the list
{
@Html.Label(c.Name);
}
<table>
...
@foreach (var item in Model)
{
...
}
</table>
Hope it helps
Instead of using onload, use Angular's ng-init
.
<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">
Note: This requires that myFunction is a property of the CinemaCtrl
scope.
0 is, by definition, a magic number. EXIT_SUCCESS is almost universally equal to 0, happily enough. So why not just return/exit 0?
exit(EXIT_SUCCESS); is abundantly clear in meaning.
exit(0); on the other hand, is counterintuitive in some ways. Someone not familiar with shell behavior might assume that 0 == false == bad, just like every other usage of 0 in C. But no - in this one special case, 0 == success == good. For most experienced devs, not going to be a problem. But why trip up the new guy for absolutely no reason?
tl;dr - if there's a defined constant for your magic number, there's almost never a reason not to used the constant in the first place. It's more searchable, often clearer, etc. and it doesn't cost you anything.
Accepted solution to this question is, while correct in summing up how to create a custom view engine, does not answer the question correctly. Issue here is that Pino is incorrectly specifying his default route. Particularly his "area" definition is incorrect. "Area" is checked via DataTokens collection and should be added as such:
var defaultRoute = new Route("",new RouteValueDictionary(){{"controller","Default"},{"action","Index"}},null/*constraints*/,new RouteValueDictionary(){{"area","Admin"}},new MvcRouteHandler());
defaultRoute.DataTokens.Add("Namespaces","MyProject.Web.Admin.Controller");
routes.Add(defaultRoute);
Specified "area" in defaults object will be ignored. Code above creates a default route, which catches on requests to your site's root and then calls Default controller, Index action in Admin area. Please also note "Namespaces" key being added to DataTokens, this is only required if you have multiple controllers with same name. This solution is verified with Mvc2 and Mvc3 .NET 3.5/4.0
You should use style instead of background color. Try searching holoeverywhere then I think this one will help you solve your problem
just change some of the 9patch resources to customize the edittext look and feel.
Try this it may help you:
private void changeFragment(Fragment targetFragment){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
I needed a fat static lib for JsonKit so created a static lib project in Xcode and then ran this bash script in the project directory. So long as you've configured the xcode project with "Build active configuration only" turned off, you should get all architectures in one lib.
#!/bin/bash
xcodebuild -sdk iphoneos
xcodebuild -sdk iphonesimulator
lipo -create -output libJsonKit.a build/Release-iphoneos/libJsonKit.a build/Release-iphonesimulator/libJsonKit.a
Javascript doesn't have "associative arrays" the way you're thinking of them. Instead, you simply have the ability to set object properties using array-like syntax (as in your example), plus the ability to iterate over an object's properties.
The upshot of this is that there is no guarantee as to the order in which you iterate over the properties, so there is nothing like a sort for them. Instead, you'll need to convert your object properties into a "true" array (which does guarantee order). Here's a code snippet for converting an object into an array of two-tuples (two-element arrays), sorting it as you describe, then iterating over it:
var tuples = [];
for (var key in obj) tuples.push([key, obj[key]]);
tuples.sort(function(a, b) {
a = a[1];
b = b[1];
return a < b ? -1 : (a > b ? 1 : 0);
});
for (var i = 0; i < tuples.length; i++) {
var key = tuples[i][0];
var value = tuples[i][1];
// do something with key and value
}
You may find it more natural to wrap this in a function which takes a callback:
function bySortedValue(obj, callback, context) {_x000D_
var tuples = [];_x000D_
_x000D_
for (var key in obj) tuples.push([key, obj[key]]);_x000D_
_x000D_
tuples.sort(function(a, b) {_x000D_
return a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0_x000D_
});_x000D_
_x000D_
var length = tuples.length;_x000D_
while (length--) callback.call(context, tuples[length][0], tuples[length][1]);_x000D_
}_x000D_
_x000D_
bySortedValue({_x000D_
foo: 1,_x000D_
bar: 7,_x000D_
baz: 3_x000D_
}, function(key, value) {_x000D_
document.getElementById('res').innerHTML += `${key}: ${value}<br>`_x000D_
});
_x000D_
<p id='res'>Result:<br/><br/><p>
_x000D_
Which version do you use?
Here is the documentation on credential caching, for the latest (1.6 as of writing).
On Windows, the Subversion client stores passwords in the %APPDATA%/Subversion/auth/ directory. On Windows 2000 and later, the standard Windows cryptography services are used to encrypt the password on disk. Because the encryption key is managed by Windows and is tied to the user's own login credentials, only the user can decrypt the cached password. (Note that if the user's Windows account password is reset by an administrator, all of the cached passwords become undecipherable. The Subversion client will behave as though they don't exist, prompting for passwords when required.)
Also, be aware that a few changes occurred in version 1.6 regarding password storage.
Following is for MySQL versions equal to or higher than 5.5.
Add to /etc/mysql/my.cnf
[mysqld]
...
character-set-server=utf8
collation-server=utf8_bin
...
All other collations I tried seemed to be case-insensitive, only "utf8_bin" worked.
Do not forget to restart mysql after this:
sudo service mysql restart
According to http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html there is also a "latin1_bin".
The "utf8_general_cs" was not accepted by mysql startup. (I read "_cs" as "case-sensitive" - ???).
Simply write to file string.Empty
, when append is set to false in StreamWriter. I think this one is easiest to understand for beginner.
private void ClearFile()
{
if (!File.Exists("TextFile.txt"))
File.Create("TextFile.txt");
TextWriter tw = new StreamWriter("TextFile.txt", false);
tw.Write(string.Empty);
tw.Close();
}
This works well. It's a manager I've made to handle hold events. Has events for hold, and for when you let go.
function onUserHold(element, func, hold, clearfunc) {
//var holdTime = 0;
var holdTimeout;
element.addEventListener('mousedown', function(e) {
holdTimeout = setTimeout(function() {
func();
clearTimeout(holdTimeout);
holdTime = 0;
}, hold);
//alert('UU');
});
element.addEventListener('mouseup', clearTime);
element.addEventListener('mouseout', clearTime);
function clearTime() {
clearTimeout(holdTimeout);
holdTime = 0;
if(clearfunc) {
clearfunc();
}
}
}
The element parameter is the one which you hold. The func parameter fires when it holds for a number of milliseconds specified by the parameter hold. The clearfunc param is optional and if it is given, it will get fired if the user lets go or leaves the element. You can also do some work-arounds to get the features you want. Enjoy! :)
You can cast your timestamp to a date by suffixing it with ::date
. Here, in psql, is a timestamp:
# select '2010-01-01 12:00:00'::timestamp;
timestamp
---------------------
2010-01-01 12:00:00
Now we'll cast it to a date:
wconrad=# select '2010-01-01 12:00:00'::timestamp::date;
date
------------
2010-01-01
On the other hand you can use date_trunc
function. The difference between them is that the latter returns the same data type like timestamptz
keeping your time zone intact (if you need it).
=> select date_trunc('day', now());
date_trunc
------------------------
2015-12-15 00:00:00+02
(1 row)
dis
is your friend if the source code is not available:
>>> import dis
>>> def foo(arg1,arg2):
... #do something with args
... a = arg1 + arg2
... return a
...
>>> dis.dis(foo)
3 0 LOAD_FAST 0 (arg1)
3 LOAD_FAST 1 (arg2)
6 BINARY_ADD
7 STORE_FAST 2 (a)
4 10 LOAD_FAST 2 (a)
13 RETURN_VALUE
@Matanya - have you looked at your server logs to see WHAT the error 500 actually is? It could be any number of things
@Aladin - white screen of death (WSOD) can be diagnosed in three ways with Laravel 4.
Option 1: Go to your Laravel logs (app/storage/logs) and see if the error is contained in there.
Option 2: Go to you PHP server logs, and look for the PHP error that is causing the WSOD
Option 3: Good old debugging skills - add a die('hello') command at the start of your routes file - then keep moving it deeper and deeper into your application until you no longer see the 'hello' message. Using this you will be able to narrow down the line that is causing your WSOD and fix the problem.
This is an example of "if else" with actions.
>>> def fun(num):
print 'This is %d' % num
>>> fun(10) if 10 > 0 else fun(2)
this is 10
OR
>>> fun(10) if 10 < 0 else 1
1
Tagname you should mentioned like that "option", if text with space we can use this method it should work.
WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
if("Germany".equals(option.getText().trim()))
option.click();
}
In the interest of adding another idea to the wiki pool, but what about AngularJS' value
and constant
modules? I'm only just starting to use them myself, but it sounds to me like these are probably the best options here.
Note: as of the time of writing, Angular 1.3.7 is the latest stable, I believe these were added in 1.2.0, haven't confirmed this with the changelog though.
Depending on how many you need to define, you might want to create a separate file for them. But I generally define these just before my app's .config()
block for easy access. Because these are still effectively modules, you'll need to rely on dependency injection to use them, but they are considered "global" to your app module.
For example:
angular.module('myApp', [])
.value('debug', true)
.constant('ENVIRONMENT', 'development')
.config({...})
Then inside any controller:
angular.module('myApp')
.controller('MainCtrl', function(debug, ENVIRONMENT), {
// here you can access `debug` and `ENVIRONMENT` as straight variables
})
From the initial question is actually sounds like static properties are required here anyway, either as mutable (value) or final (constant). It's more my personal opinion than anything else, but I find placing runtime configuration items on the $rootScope
gets too messy, too quickly.
Check that doPost()
method of servlet is called from the jsp form and remove conn.commit
.
Here is the solution I used for Report Server 2008 R2
It should work regardless of what the Report Server will output for use for in its "id" attribute of the table. I don't think you can always assume it will be "ctl31_fixedTable"
I used a mix of the suggestion above and some ways to dynamically load jquery libraries into a page from javascript file found here
On the server go to the directory: C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js
Copy the jquery library jquery-1.6.2.min.js into the directory
Create a backup copy of the file ReportingServices.js Edit the file. And append this to the bottom of it:
var jQueryScriptOutputted = false;
function initJQuery() {
//if the jQuery object isn't available
if (typeof(jQuery) == 'undefined') {
if (! jQueryScriptOutputted) {
//only output the script once..
jQueryScriptOutputted = true;
//output the script
document.write("<scr" + "ipt type=\"text/javascript\" src=\"../js/jquery-1.6.2.min.js\"></scr" + "ipt>");
}
setTimeout("initJQuery()", 50);
} else {
$(function() {
// Bug-fix on Chrome and Safari etc (webkit)
if ($.browser.webkit) {
// Start timer to make sure overflow is set to visible
setInterval(function () {
var div = $('table[id*=_fixedTable] > tbody > tr:last > td:last > div')
div.css('overflow', 'visible');
}, 1000);
}
});
}
}
initJQuery();
Yes that's the correct method to do it with a GET request.
However, please remember that multiple query string parameters should be separated with &
eg. ?variable1=value1&variable2=value2
or in the .htaccess file
AddOutputFilter DEFLATE css js
ExpiresActive On
ExpiresByType application/x-javascript A2592000
Yes, that's usually happens after 1440s (24 minutes)
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
there one more option that allows to get "select" size with joins, and table size as option too
-- 1
EXPLAIN PLAN
FOR
SELECT
Scheme.Table_name.table_column1 AS "column1",
Scheme.Table_name.table_column2 AS "column2",
Scheme.Table_name.table_column3 AS "column3",
FROM Scheme.Table_name
WHERE ;
SELECT * FROM TABLE (DBMS_XPLAN.display);
If you can use psql you can use \gexec
meta command to execute query output;
SELECT
format('TRUNCATE TABLE %I.%I', ns.nspname, c.relname)
FROM pg_namespace ns
JOIN pg_class c ON ns.oid = c.relnamespace
JOIN pg_roles r ON r.oid = c.relowner
WHERE
ns.nspname = 'table schema' AND -- add table schema criteria
r.rolname = 'table owner' AND -- add table owner criteria
ns.nspname NOT IN ('pg_catalog', 'information_schema') AND -- exclude system schemas
c.relkind = 'r' AND -- tables only
has_table_privilege(c.oid, 'TRUNCATE') -- check current user has truncate privilege
\gexec
Note that \gexec
is introduced into the version 9.6
Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync
Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods
Few examples found in previous responses done with SetupAsync extension:
mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());
I would not change the constraints, instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.
Then you can remove the initial primary key row with id_no =7008255601088.
Three steps include:
I have had problems with @JodaStephen's implementation on JBoss EAP 6. So, I rewrote the conversion following Oracle's Java Tutorial in http://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html.
Date input = new Date();
GregorianCalendar gregorianCalendar = (GregorianCalendar) Calendar.getInstance();
gregorianCalendar.setTime(input);
ZonedDateTime zonedDateTime = gregorianCalendar.toZonedDateTime();
zonedDateTime.toLocalDate();
After the first iteration your're returning a number and then trying to get property x
of it to add to the next object which is undefined
and maths involving undefined
results in NaN
.
try returning an object contain an x
property with the sum of the x properties of the parameters:
var arr = [{x:1},{x:2},{x:4}];
arr.reduce(function (a, b) {
return {x: a.x + b.x}; // returns object with property x
})
// ES6
arr.reduce((a, b) => ({x: a.x + b.x}));
// -> {x: 7}
Explanation added from comments:
The return value of each iteration of [].reduce
used as the a
variable in the next iteration.
Iteration 1: a = {x:1}
, b = {x:2}
, {x: 3}
assigned to a
in Iteration 2
Iteration 2: a = {x:3}
, b = {x:4}
.
The problem with your example is that you're returning a number literal.
function (a, b) {
return a.x + b.x; // returns number literal
}
Iteration 1: a = {x:1}
, b = {x:2}
, // returns 3
as a
in next iteration
Iteration 2: a = 3
, b = {x:2}
returns NaN
A number literal 3
does not (typically) have a property called x
so it's undefined
and undefined + b.x
returns NaN
and NaN + <anything>
is always NaN
Clarification: I prefer my method over the other top answer in this thread as I disagree with the idea that passing an optional parameter to reduce with a magic number to get out a number primitive is cleaner. It may result in fewer lines written but imo it is less readable.
Accepted answer's $('iframe').load
will now produce a.indexOf is not a function
error. Can be updated to:
$('iframe').on('load', function() {
// ...
});
Few others similar to .load
deprecated since jQuery 1.8: "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project
You can do it this way also:
import pandas as pd
import os
new_df = pd.DataFrame()
for r, d, f in os.walk(csv_folder_path):
for file in f:
complete_file_path = csv_folder_path+file
read_file = pd.read_csv(complete_file_path)
new_df = new_df.append(read_file, ignore_index=True)
new_df.shape
I'm not Reputable enough to upvote or comment yet, but LukeH's answer was spot on for me.
As AES encryption is the standard to use now, it produces a base64 string (at least all the encrypt/decrypt implementations I've seen). This string has a length in multiples of 4 (string.length % 4 = 0)
The strings I was getting contained + and = on the beginning or end, and when you just concatenate that into a URL's querystring, it will look right (for instance, in an email you generate), but when the the link is followed and the .NET page recieves it and puts it into this.Page.Request.QueryString, those special characters will be gone and your string length will not be in a multiple of 4.
As the are special characters at the FRONT of the string (ex: +), as well as = at the end, you can't just add some = to make up the difference as you are altering the cypher text in a way that doesn't match what was actually in the original querystring.
So, wrapping the cypher text with HttpUtility.URLEncode (not HtmlEncode) transforms the non-alphanumeric characters in a way that ensures .NET parses them back into their original state when it is intepreted into the querystring collection.
The good thing is, we only need to do the URLEncode when generating the querystring for the URL. On the incoming side, it's automatically translated back into the original string value.
Here's some example code
string cryptostring = MyAESEncrypt(MySecretString);
string URL = WebFunctions.ToAbsoluteUrl("~/ResetPassword.aspx?RPC=" + HttpUtility.UrlEncode(cryptostring));
What exactly do you want to know?
The shared library soname? That's part of the filename, libstdc++.so.6
, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname
.
The minor revision number? You should be able to get that by simply checking what the symlink points to:
$ ls -l /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16
That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6
version, which corresponds to the GLIBCXX_3.4.16
symbol versions.
Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++
and libstdc++.so
you can get that from:
$ g++ -dumpversion
4.6.3
Or, on most distros, you can just ask the package manager. On my Fedora host that's
$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686
As other answers have said, you can map releases to library versions by checking the ABI docs
You can simply show your actual image directory(less secure). By just 2 line of code.
$dir = base_url()."photos/";
echo"<a href=".$dir.">Photo Directory</a>";
create a divider class as follows:
.divider{
width:5px;
height:auto;
display:inline-block;
}
Then attach this to a div between the two buttons
<div style="text-align: center">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
<div class="divider"/>
<asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
</div>
This is the best way as it avoids the box model, which can be a pain on older browsers, and doesn't add any extra characters that would be picked up by a screen reader, so it is better for readability.
It's good to have a number of these types of divs for certain scenarios (my most used one is vert5spacer, similar to this but puts a block div with height 5 and width auto for spacing out items in a form etc.
For those that do know the width, you could do something like
div {
max-width: ???px; //px,%
margin-left:auto;
margin-right:auto;
}
I also agree about not setting text-align:center on the body because it can mess up the rest of your code and you might have to individually set text-align:left on a lot of things either then or in the future.
For Android Studio (or IntelliJ IDEA),
If everything looks OK in your project and that you're still receiving the error in all your layouts, try to 'Invalidate caches & restart'.
Wait until Android Studio has finished to create all the caches & indexes.
def letter_to_int(letter):
alphabet = list('abcdefghijklmnopqrstuvwxyz')
return alphabet.index(letter) + 1
here, the index (x) function returns the position value of x if the list contains x.
Using axes objects is a great approach for this. It helps if you want to interact with multiple figures and sub-plots. To add and manipulate the axes objects directly:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,9))
signal_axes = fig.add_subplot(211)
signal_axes.plot(xs,rawsignal)
fft_axes = fig.add_subplot(212)
fft_axes.set_title("FFT")
fft_axes.set_autoscaley_on(False)
fft_axes.set_ylim([0,1000])
fft = scipy.fft(rawsignal)
fft_axes.plot(abs(fft))
plt.show()
Or a 1-liner:
perl -p -i -e 's/\r\n$/\n/g' file1.txt file2.txt ... filen.txt
Without destructuring, you can create a defaults params and pass it in
interface Name {
firstName: string;
lastName: string;
}
export const defaultName extends Omit<Name, 'firstName'> {
lastName: 'Smith'
}
sayName({ ...defaultName, firstName: 'Bob' })
jQuery is not necessary, you can use only javascript.
<table id="table">
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
......
<tr>...</tr>
</table>
The table object has a collection of all rows.
var myTable = document.getElementById('table');
var rows = myTable.rows;
var firstRow = rows[0];
This works better for me:
Simple:
ApplicationController.helpers.my_helper_method
Advance:
class HelperProxy < ActionView::Base
include ApplicationController.master_helper_module
def current_user
#let helpers act like we're a guest
nil
end
def self.instance
@instance ||= new
end
end
Source: http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model
This works with integers and decimal numbers. It doesn't match if the number has the coma thousand separator ,
"^-?\\d*(\\.\\d+)?$"
some strings that matches with this:
894
923.21
76876876
.32
-894
-923.21
-76876876
-.32
some strings that doesn't:
hello
9bye
hello9bye
888,323
5,434.3
-8,336.09
87078.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
As mentioned, you can use:
=Format(Fields!Price.Value, "C")
A digit after the "C" will specify precision:
=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")
You can also use Excel-style masks like this:
=Format(Fields!Price.Value, "#,##0.00")
Haven't tested the last one, but there's the idea. Also works with dates:
=Format(Fields!Date.Value, "yyyy-MM-dd")
do like
<input name="name" id="name" type="text" value="Name"
onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>
and js
function fillField(input,val) {
if(input.value == "")
input.value=val;
};
function clearField(input,val) {
if(input.value == val)
input.value="";
};
here is a demo fiddle of the same
To build on Paul Lammertsma's answer, this command will print the names and signatures of all APKs in the current dir (I'm using sh because later I need to pipe the output to grep):
find . -name "*.apk" -exec echo "APK: {}" \; -exec sh -c 'keytool -printcert -jarfile "{}"' \;
Sample output:
APK: ./com.google.android.youtube-10.39.54-107954130-minAPI15.apk
Signer #1:
Signature:
Owner: CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
Issuer: CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
Serial number: 4934987e
Valid from: Mon Dec 01 18:07:58 PST 2008 until: Fri Apr 18 19:07:58 PDT 2036
Certificate fingerprints:
MD5: D0:46:FC:5D:1F:C3:CD:0E:57:C5:44:40:97:CD:54:49
SHA1: 24:BB:24:C0:5E:47:E0:AE:FA:68:A5:8A:76:61:79:D9:B6:13:A6:00
SHA256: 3D:7A:12:23:01:9A:A3:9D:9E:A0:E3:43:6A:B7:C0:89:6B:FB:4F:B6:79:F4:DE:5F:E7:C2:3F:32:6C:8F:99:4A
Signature algorithm name: MD5withRSA
Version: 1
APK: ./com.google.android.youtube_10.40.56-108056134_minAPI15_maxAPI22(armeabi-v7a)(480dpi).apk
Signer #1:
Signature:
Owner: CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
Issuer: CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
Serial number: 4934987e
Valid from: Mon Dec 01 18:07:58 PST 2008 until: Fri Apr 18 19:07:58 PDT 2036
Certificate fingerprints:
MD5: D0:46:FC:5D:1F:C3:CD:0E:57:C5:44:40:97:CD:54:49
SHA1: 24:BB:24:C0:5E:47:E0:AE:FA:68:A5:8A:76:61:79:D9:B6:13:A6:00
SHA256: 3D:7A:12:23:01:9A:A3:9D:9E:A0:E3:43:6A:B7:C0:89:6B:FB:4F:B6:79:F4:DE:5F:E7:C2:3F:32:6C:8F:99:4A
Signature algorithm name: MD5withRSA
Version: 1
Or if you just care about SHA1:
find . -name "*.apk" -exec echo "APK: {}" \; -exec sh -c 'keytool -printcert -jarfile "{}" | grep SHA1' \;
Sample output:
APK: ./com.google.android.youtube-10.39.54-107954130-minAPI15.apk
SHA1: 24:BB:24:C0:5E:47:E0:AE:FA:68:A5:8A:76:61:79:D9:B6:13:A6:00
APK: ./com.google.android.youtube_10.40.56-108056134_minAPI15_maxAPI22(armeabi-v7a)(480dpi).apk
SHA1: 24:BB:24:C0:5E:47:E0:AE:FA:68:A5:8A:76:61:79:D9:B6:13:A6:00
Always use with
when working with files as it handles everything for you:
with open('filename', 'r') as f:
for line in reversed(f.readlines()):
print line
Or in Python 3:
with open('filename', 'r') as f:
for line in reversed(list(f.readlines())):
print(line)
In Ultra Edit and Crimson (or Emerald) Editor you can enable/disable the column mode with Alt + C
The better way is:
url = "http://xxx.xxxx.xx"
data = {
"cardno": "6248889874650987",
"systemIdentify": "s08",
"sourceChannel": 12
}
resp = requests.post(url, json=data)
Old thread but it's missing a simple js solution:
let a = document.createElement('a')
a.href = item.url
a.download = item.url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
Use the Take(int n)
method:
var q = query.Take(10);
You can store and read string information in a cookie.
If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.
However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
Then in each page you need this session Id you can read the cookie, with a function like:
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return '';
}
The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.
To store the id:
var sId = 's234543245';
writeCookie('sessionId', sId, 3);
To read the id:
var sId = readCookie('sessionId')
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
Here is a working version of the "build defs". This is similar to my previous answer but I figured out the build month. (You just can't compute build month in a #if
statement, but you can use a ternary expression that will be compiled down to a constant.)
Also, according to the documentation, if the compiler cannot get the time of day it will give you question marks for these strings. So I added tests for this case, and made the various macros return an obviously wrong value (99) if this happens.
#ifndef BUILD_DEFS_H
#define BUILD_DEFS_H
// Example of __DATE__ string: "Jul 27 2012"
// Example of __TIME__ string: "21:06:19"
#define COMPUTE_BUILD_YEAR \
( \
(__DATE__[ 7] - '0') * 1000 + \
(__DATE__[ 8] - '0') * 100 + \
(__DATE__[ 9] - '0') * 10 + \
(__DATE__[10] - '0') \
)
#define COMPUTE_BUILD_DAY \
( \
((__DATE__[4] >= '0') ? (__DATE__[4] - '0') * 10 : 0) + \
(__DATE__[5] - '0') \
)
#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')
#define COMPUTE_BUILD_MONTH \
( \
(BUILD_MONTH_IS_JAN) ? 1 : \
(BUILD_MONTH_IS_FEB) ? 2 : \
(BUILD_MONTH_IS_MAR) ? 3 : \
(BUILD_MONTH_IS_APR) ? 4 : \
(BUILD_MONTH_IS_MAY) ? 5 : \
(BUILD_MONTH_IS_JUN) ? 6 : \
(BUILD_MONTH_IS_JUL) ? 7 : \
(BUILD_MONTH_IS_AUG) ? 8 : \
(BUILD_MONTH_IS_SEP) ? 9 : \
(BUILD_MONTH_IS_OCT) ? 10 : \
(BUILD_MONTH_IS_NOV) ? 11 : \
(BUILD_MONTH_IS_DEC) ? 12 : \
/* error default */ 99 \
)
#define COMPUTE_BUILD_HOUR ((__TIME__[0] - '0') * 10 + __TIME__[1] - '0')
#define COMPUTE_BUILD_MIN ((__TIME__[3] - '0') * 10 + __TIME__[4] - '0')
#define COMPUTE_BUILD_SEC ((__TIME__[6] - '0') * 10 + __TIME__[7] - '0')
#define BUILD_DATE_IS_BAD (__DATE__[0] == '?')
#define BUILD_YEAR ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_YEAR)
#define BUILD_MONTH ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_MONTH)
#define BUILD_DAY ((BUILD_DATE_IS_BAD) ? 99 : COMPUTE_BUILD_DAY)
#define BUILD_TIME_IS_BAD (__TIME__[0] == '?')
#define BUILD_HOUR ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_HOUR)
#define BUILD_MIN ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_MIN)
#define BUILD_SEC ((BUILD_TIME_IS_BAD) ? 99 : COMPUTE_BUILD_SEC)
#endif // BUILD_DEFS_H
With the following test code, the above works great:
printf("%04d-%02d-%02dT%02d:%02d:%02d\n", BUILD_YEAR, BUILD_MONTH, BUILD_DAY, BUILD_HOUR, BUILD_MIN, BUILD_SEC);
However, when I try to use those macros with your stringizing macro, it stringizes the literal expression! I don't know of any way to get the compiler to reduce the expression to a literal integer value and then stringize.
Also, if you try to statically initialize an array of values using these macros, the compiler complains with an error: initializer element is not constant
message. So you cannot do what you want with these macros.
At this point I'm thinking that your best bet is the Python script that just generates a new include file for you. You can pre-compute anything you want in any format you want. If you don't want Python we can write an AWK script or even a C program.
you can either use
echo '<a href="'.$link_address.'">Link</a>';
or
echo "<a href=\"$link_address\">Link</a>';
if you use double quotes you can insert the variable into the string and it will be parsed.
I believe tuple()
takes a list as an argument
For example,
tuple([1,2,3]) # returns (1,2,3)
see what happens if you wrap your array with brackets
.p12
and .pfx
are both PKCS #12 files. Am I missing something?
Have you tried renaming the exported .pfx
file to have a .p12
extension?
nohup some_command > /dev/null 2>&1&
That's all you need to do!
cd sdk/platform-tools/
and then use ./adb devices
instead
I think it suffices to hand the data over directly:
$("#inputhidden").select2("data", data, true);
Note that the second parameter seems to indicate that a refresh is desired.
Thanks to @Bergi for help with this.
If that doesn't automatically update you could either try calling it's updateResults method directly.
$("#inputhidden").select2("updateResults");
Or trigger it indirectly by sending a trigger to the "input.select2-input" like so:
var search = $("#inputhidden input.select2-input");
search.trigger("input");
Solved this by adding following
RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
As an interesting side note, WPF's binding handles marshaling automatically so you can bind the UI to object properties that are modified on background threads without having to do anything special. This has proven to be a great timesaver for me.
In XAML:
<TextBox Text="{Binding Path=Name}"/>
Based on the first sentence of the question: "I'm trying to write out a Byte[] array representing a complete file to a file."
The path of least resistance would be:
File.WriteAllBytes(string path, byte[] bytes)
Documented here:
Have a look at Docotic.Pdf library. It does not require you to make source code of your application open (like iTextSharp with viral AGPL 3 license, for example).
Docotic.Pdf can be used to read PDF files and extract text with or without formatting. Please have a look at the article that shows how to extract text from PDFs.
Disclaimer: I work for Bit Miracle, vendor of the library.
I did not get the size of the list using length
but rather size
as one the answer above suggested it because of the issue reported here.
val list = List("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
list.groupBy(x=>x).map(t => (t._1, t._2.size))
HTMLUNIT is the package if you're a java developer. http://htmlunit.sourceforge.net/apidocs/index.html
This can happen with a 401 http response if using NSURLConnection.
See NSURLConnection returning error instead of response for 401
If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.
If you are looking to avoid the callbacks you can take advantage of the sdk .promise() function like this:
const s3 = new AWS.S3();
const params = {Bucket: 'myBucket', Key: 'myKey.csv'}
const response = await s3.getObject(params).promise() // await the promise
const fileContent = getObjectResult.Body.toString('utf-8'); // can also do 'base64' here if desired
I'm sure the other ways mentioned here have their advantages but this works great for me. Sourced from this thread (see the last response from AWS): https://forums.aws.amazon.com/thread.jspa?threadID=116788
JAVA HOME
is used for setting up the environment variable for JAVA. It means that you are providing a path for compiling a JAVA program and also running the same. So, if you do not set the JAVA HOME( PATH ) and try to run a java or any dependent program in the command prompt.
You will deal with an error as
javac : not recognized as internal or external command
.
Now to set this, Just open your Java jdk then open bin folder then copy the PATH of that bin folder.
Now, go to My computer right click on it----> select properties-----> select Advanced system settings----->Click on Environment Variables------>select New----->give a name in the text box Variable Name and then paste the path in Value.
That's All!!
Since Git 2.13 (Q2 2017), you can stash individual files, with git stash push
:
git stash push [-m <message>] [--] [<pathspec>...]
When
pathspec
is given to 'git stash push
', the new stash records the modified states only for the files that match the pathspec See "Stash changes to specific files" for more.
Simplified example:
git stash push path/to/file
The test case for this feature shows a few more options off:
test_expect_success 'stash with multiple pathspec arguments' '
>foo &&
>bar &&
>extra &&
git add foo bar extra &&
git stash push -- foo bar &&
test_path_is_missing bar &&
test_path_is_missing foo &&
test_path_is_file extra &&
git stash pop &&
test_path_is_file foo &&
test_path_is_file bar &&
test_path_is_file extra
The original answer (below, June 2010) was about manually selecting what you want to stash.
Casebash comments:
This (the
stash --patch
original solution) is nice, but often I've modified a lot of files so using patch is annoying
bukzor's answer (upvoted, November 2011) suggests a more practical solution, based on
git add
+ git stash --keep-index
.
Go see and upvote his answer, which should be the official one (instead of mine).
About that option, chhh points out an alternative workflow in the comments:
you should "
git reset --soft
" after such a stash to get your clear staging back:
In order to get to the original state - which is a clear staging area and with only some select un-staged modifications, one could softly reset the index to get (without committing anything like you - bukzor - did).
(Original answer June 2010: manual stash)
Yet, git stash save --patch
could allows you to achieve the partial stashing you are after:
With
--patch
, you can interactively select hunks from in the diff between HEAD and the working tree to be stashed.
The stash entry is constructed such that its index state is the same as the index state of your repository, and its worktree contains only the changes you selected interactively. The selected changes are then rolled back from your worktree.
However that will save the full index (which may not be what you want since it might include other files already indexed), and a partial worktree (which could look like the one you want to stash).
git stash --patch --no-keep-index
might be a better fit.
If --patch
doesn't work, a manual process might:
For one or several files, an intermediate solution would be to:
git stash
git stash
# this time, only the files you want are stashedgit stash pop stash@{1}
# re-apply all your files modificationsgit checkout -- afile
# reset the file to the HEAD content, before any local modificationsAt the end of that rather cumbersome process, you will have only one or several files stashed.
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
Example:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
Output:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
As an alternative to the default title
attribute tooltips, you can make your own custom CSS tooltips using :before
/:after
pseudo elements and HTML5 data-*
attributes.
Using the provided CSS, you can add a tooltip to an element using the data-tooltip
attribute.
You can also control the position of the custom tooltip using the data-tooltip-position
attribute (accepted values: top
/right
/bottom
/left
).
For instance, the following will add a tooltop positioned at the bottom of the span element.
<span data-tooltip="Custom tooltip text." data-tooltip-position="bottom">Custom bottom tooltip.</span>
You can display the custom tooltips with pseudo elements by retrieving the custom attribute values using the attr()
function.
[data-tooltip]:before {
content: attr(data-tooltip);
}
In terms of positioning the tooltip, just use the attribute selector and change the placement based on the attribute's value.
Full CSS used in the example - customize this to your needs.
[data-tooltip] {
display: inline-block;
position: relative;
cursor: help;
padding: 4px;
}
/* Tooltip styling */
[data-tooltip]:before {
content: attr(data-tooltip);
display: none;
position: absolute;
background: #000;
color: #fff;
padding: 4px 8px;
font-size: 14px;
line-height: 1.4;
min-width: 100px;
text-align: center;
border-radius: 4px;
}
/* Dynamic horizontal centering */
[data-tooltip-position="top"]:before,
[data-tooltip-position="bottom"]:before {
left: 50%;
-ms-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
/* Dynamic vertical centering */
[data-tooltip-position="right"]:before,
[data-tooltip-position="left"]:before {
top: 50%;
-ms-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
[data-tooltip-position="top"]:before {
bottom: 100%;
margin-bottom: 6px;
}
[data-tooltip-position="right"]:before {
left: 100%;
margin-left: 6px;
}
[data-tooltip-position="bottom"]:before {
top: 100%;
margin-top: 6px;
}
[data-tooltip-position="left"]:before {
right: 100%;
margin-right: 6px;
}
/* Tooltip arrow styling/placement */
[data-tooltip]:after {
content: '';
display: none;
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
/* Dynamic horizontal centering for the tooltip */
[data-tooltip-position="top"]:after,
[data-tooltip-position="bottom"]:after {
left: 50%;
margin-left: -6px;
}
/* Dynamic vertical centering for the tooltip */
[data-tooltip-position="right"]:after,
[data-tooltip-position="left"]:after {
top: 50%;
margin-top: -6px;
}
[data-tooltip-position="top"]:after {
bottom: 100%;
border-width: 6px 6px 0;
border-top-color: #000;
}
[data-tooltip-position="right"]:after {
left: 100%;
border-width: 6px 6px 6px 0;
border-right-color: #000;
}
[data-tooltip-position="bottom"]:after {
top: 100%;
border-width: 0 6px 6px;
border-bottom-color: #000;
}
[data-tooltip-position="left"]:after {
right: 100%;
border-width: 6px 0 6px 6px;
border-left-color: #000;
}
/* Show the tooltip when hovering */
[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
display: block;
z-index: 50;
}
SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).
(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).
You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.
It's embedded in a standard XML comment, and looks like this:
<!--#include virtual="top.shtml" -->
It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.
You can read more in this Wikipedia article.
If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:
parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename is not None:
print('The file name is {}'.format(args.filename))
else:
print('Oh well ; No args, no problems')
You can set padding to your view by pro grammatically throughout below code -
view.setPadding(0,1,20,3);
And, also there are different type of padding available -
These, links will refer Android Developers site. Hope this helps you lot.
Sure, you can put your constants into a separate module. For example:
const.py:
A = 12
B = 'abc'
C = 1.2
main.py:
import const
print const.A, const.B, const.C
Note that as declared above, A
, B
and C
are variables, i.e. can be changed at run time.
$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');
or
var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);
Though I'm not certain it will have an affect as it will be generated after the page is loaded
If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx
This may allow other meta tags, if you're lucky
Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx
I had a similar problem but solved changing the direction of the slash sign:
For some reason when Atom copies Paths from the project folder it does so like background-image: url(img\image.jpg\)
instead of (img/image.jpeg)
While i can see it's not the case for OP may be useful for other people (I just wasted half the morning wondering why my stylesheet wasn´t loading)
If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:
Set up your base href in your _Layout page: <head> <base href="/"> </head>
Then, add following in your angular app config : $locationProvider.html5Mode(true)
Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refreash will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all
url:
routes.MapRoute(
name: "App",
url: "{*url}",
defaults: new {
controller = "Home", action = "Index"
}
);
div {_x000D_
display: flex;_x000D_
_x000D_
width: 200px;_x000D_
height: 80px;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
a {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
text-align: center; /* only important for multiple lines */_x000D_
_x000D_
padding: 0 20px;_x000D_
background-color: silver;_x000D_
border: 2px solid blue;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">text</a>_x000D_
<a href="#">text with two lines</a>_x000D_
</div>
_x000D_
public function showstudents() {
$students = DB::table('student')->get();
return (View::make("user/regprofile", compact('student')));
}
Here is an example using a generator's send()
method:
def restartable(seq):
while True:
for item in seq:
restart = yield item
if restart:
break
else:
raise StopIteration
Example Usage:
x = [1, 2, 3, 4, 5]
total = 0
r = restartable(x)
for item in r:
if item == 5 and total < 100:
total += r.send(True)
else:
total += item
You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>()
. Try this:
@model LetLord.Models.Tenant
<div class="row-fluid">
<div class="span4 well-border">
@Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
</div>
</div>
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and _getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
I solved this error in pom.xml by adding the below code
spring-rest-demo org.apache.maven.plugins maven-war-plugin 2.6setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.
You may want to look into some basic object-oriented tutorials to see how static/instance members work.
You cannot do this on multiple fields. You can also look for this.
If you are targeting Windows XP (v140_xp
), try installing Windows XP Support for C++.
Starting with Visual Studio 2012, the default toolset (v110) dropped support for Windows XP. As a result, a Windows.h
error can occur if your project is targeting Windows XP with the default C++ packages.
Check which Windows SDK version is specified in your project's Platform Toolset. (Project ? Properties ? Configuration Properties ? General
). If your Toolset ends in _xp
, you'll need to install XP support.
Open the Visual Studio Installer and click Modify for your version of Visual Studio. Open the Individual Components tab and scroll down to Compilers, build tools, and runtimes. Near the bottom, check Windows XP support for C++ and click Modify to begin installing.
Your curtime
variable holds the number of seconds since the epoch. If you get one before and one after, the later one minus the earlier one is the elapsed time in seconds. You can subtract time_t
values just fine.
This is what I used on MAC.
Use your preferred compiler.
Compile with gcc.
gcc -lstdc++ filename.cpp -o outputName
Or Compile with clang.
clang++ filename.cpp -o outputName
After done compiling. You can run it with.
./outputFile
The solution was as simple as adding plt.show()
at the end of the code snippet:
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
The following approach is correct:
<context:component-scan base-package="x.y.z.service, x.y.z.controller" />
Note that the error complains about x.y.z.dao.daoservice.LoginDAO
, which is not in the packages mentioned above, perhaps you forgot to add it:
<context:component-scan base-package="x.y.z.service, x.y.z.controller, x.y.z.dao" />
I needed to get the form data as some sort of object. I used this:
$('#preview_form').serializeArray().reduce((function(acc, val) {
acc[val.name.replace('[', '_').replace(']', '')] = val.value;
return acc;
}), {});
I had the same problem, and I was using the following plugin for tests:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<useFile>true</useFile>
<includes>
<include>**/*Tests.java</include>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.
After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:
<parallel>methods</parallel>
<threadCount>10</threadCount>
Hope that this helps someone out!
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLACK);
String title = context.getString(R.string.agreement_popup_message);
SpannableStringBuilder ssBuilder = new SpannableStringBuilder(title);
ssBuilder.setSpan(
foregroundColorSpan,
0,
title.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(context);
alertDialogBuilderUserInput.setTitle(ssBuilder)
Also, instead of inner classes, you can use your 2 or more classes as fields.
For example:
Class Man{
private Phone ownPhone;
private DeviceInfo info;
//sets; gets
}
Class Phone{
private String phoneType;
private Long phoneNumber;
//sets; gets
}
Class DeviceInfo{
String phoneModel;
String cellPhoneOs;
String osVersion;
String phoneRam;
//sets; gets
}
So, here you have a man who can have some Phone with its number and type, also you have DeviceInfo for that Phone.
Also, it's possible is better to use DeviceInfo as a field into Phone class, like
class Phone {
DeviceInfo info;
String phoneNumber;
Stryng phoneType;
//sets; gets
}
Use the following Code:-
../css/main.css
Note: The "../" is shorthand for "The containing directory", or "Up one directory".
If you don't know the previous folder this will be very helpful..
The <hr>
should be placed inside a <div>
for proper functioning.
Place it like this to get desired width `
<div class='row'>
<div class='col-lg-8 col-lg-offset-2'>
<hr>
</div>
</div>
`
Hope this helps a future reader!
To create a self signed certificate on Windows 7 with IIS 6...
Open IIS
Select your server (top level item or your computer's name)
Under the IIS section, open "Server Certificates"
Click "Create Self-Signed Certificate"
Name it "localhost" (or something like that that is not specific)
Click "OK"
You can then bind that certificate to your website...
Right click on your website and choose "Edit bindings..."
Click "Add"
Click "OK"
Click "Close"
if (strtotime($date) > mktime(0,0,0))
should do the job.
You must take the whole directory where java is installed, in my case:
export JAVA_HOME=/usr/java/jdk1.8.0_31
First you create method in your fragment
like
public void name()
{
}
in your activity
you add this
add onCreate()
method
myfragment fragment=new myfragment()
finally call the method where you want to call add this
fragment.method_name();
try this code
The WPF RichTextBox has a Document
property for setting the content a la MSDN:
// Create a FlowDocument to contain content for the RichTextBox.
FlowDocument myFlowDoc = new FlowDocument();
// Add paragraphs to the FlowDocument.
myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 1")));
myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 2")));
myFlowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 3")));
RichTextBox myRichTextBox = new RichTextBox();
// Add initial content to the RichTextBox.
myRichTextBox.Document = myFlowDoc;
You can just use the AppendText
method though if that's all you're after.
Hope that helps.
Simple Copy this text and put on the before </body>
function disableselect(e) {
return false
}
function reEnable() {
return true
}
document.onselectstart = new Function ("return false")
if (window.sidebar) {
document.onmousedown = disableselect
document.onclick = reEnable
}
If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.
I usually use
#define INFINITY (1e999)
or
const double INFINITY = 1e999
which works at least in IEEE 754 contexts because the highest representable double value is roughly 1e308
. 1e309
would work just as well, as would 1e99999
, but three nines is sufficient and memorable. Since this is either a double literal (in the #define
case) or an actual Inf
value, it will remain infinite even if you're using 128-bit (“long double”) floats.