I had the with a newly created F# project. The solution was to uncheck "Use standard resource names" in the project properties -> Application -> Resources / Specify how application resources will be managed. If you do not see the checkbox then update your Visual Studio! I have 15.6.7 installed. In 15.3.2 this checkbox is not there.
java -version
java -showversion
Both commands work In Linux 16.04 LTS
The focus only works if the window is focused.
Use ((JavascriptExecutor)webDriver).executeScript("window.focus();");
to be sure.
I had the same problem for Winforms.
The solution for me is:
Install-Package Microsoft.ReportViewer.Runtime.Winforms
When you visited https://localhost previously at some point it not only visited this over a secure channel (https rather than http), it also told your browser, using a special HTTP header: Strict-Transport-Security (often abbreviated to HSTS), that it should ONLY use https for all future visits.
This is a security feature web servers can use to prevent people being downgraded to http (either intentionally or by some evil party).
However if you then then turn off your https server, and just want to browse http you can't (by design - that's the point of this security feature).
HSTS also does prevents you from accepting and skipping past certificate errors.
To reset this, so HSTS is no longer set for localhost, type the following in your Chrome address bar:
chrome://net-internals/#hsts
Where you will be able to delete this setting for "localhost".
You might also want to find out what was setting this to avoid this problem in future!
Note that for other sites (e.g. www.google.com) these are "preloaded" into the Chrome code and so cannot be removed. When you query them at chrome://net-internals/#hsts you will see them listed as static
HSTS entries.
And finally note that Google has started preloading HSTS for the entire .dev domain: https://ma.ttias.be/chrome-force-dev-domains-https-via-preloaded-hsts/
As "@sarnold", aptly pointed out, any process can send signal to any other process, hence, one process can send SIGABORT to other process & in that case the receiving process is unable to distinguish whether its coming because of its own tweaking of memory etc, or someone else has "unicastly", send to it.
In one of the systems I worked there is one deadlock detector which actually detects if process is coming out of some task by giving heart beat or not. If not, then it declares the process is in deadlock state and sends SIGABORT to it.
I just wanted to share this prospective with reference to question asked.
Problem with the above answer comes with files input with "./" like "./my-file.txt"
Workaround (of many):
myfile="./somefile.txt"
FOLDER="$(dirname $(readlink -f "${ARG}"))"
echo ${FOLDER}
Short answer:
int
uses up 4 bytes of memory (and it CANNOT contain a decimal), double
uses 8 bytes of memory. Just different tools for different purposes.
This is working for me: Let's say I have this dependency
<dependency>
<groupId>com.company.app</groupId>
<artifactId>my-library</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/my-library.jar</systemPath>
</dependency>
Then, add the class-path for your system dependency manually like this
<Class-Path>libs/my-library-1.0.jar</Class-Path>
Full config:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifestEntries>
<Build-Jdk>${jdk.version}</Build-Jdk>
<Implementation-Title>${project.name}</Implementation-Title>
<Implementation-Version>${project.version}</Implementation-Version>
<Specification-Title>${project.name} Library</Specification-Title>
<Specification-Version>${project.version}</Specification-Version>
<Class-Path>libs/my-library-1.0.jar</Class-Path>
</manifestEntries>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.company.app.MainClass</mainClass>
<classpathPrefix>libs/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.5.1</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
The problem with some of options above, is that if someone pushes more commits to the PR after opening the PR, they won't give you the most updated version. For me what worked best is - go to the PR, and press 'Commits', scroll to the bottom to see the most recent commit hash and then simply use git checkout, i.e.
git checkout <commit number>
in the above example
git checkout 0ba1a50
If you make all the properties animated the same, you can set each separately which will allow you to not repeat the code.
transition: all 2s;
transition-property: color, text-shadow;
There is more about it here: CSS transition shorthand with multiple properties?
I would avoid using the property all (transition-property overwrites 'all'), since you could end up with unwanted behavior and unexpected performance hits.
If you support IE, for versions of Internet Explorer 8 and above, this:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.
If you separate with semi-colon, it sets compatibility levels for different versions. For example:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
For this:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
It forces the browser the render at whatever the most recent version's standards are.
For more information, there is plenty to read about on MSDN,
You could override your object's ToString() method:
public override string ToString ()
{
return string.Format ("{0},{1},{2}", this.number, this.id, this.whatever);
}
Using Jupyter Notebook, the code can be as simple as the following.
%matplotlib inline
from IPython.display import Image
Image('your_image.png')
Sometimes you might would like to display a series of images in a for loop, in which case you might would like to combine display
and Image
to make it work.
%matplotlib inline
from IPython.display import display, Image
for your_image in your_images:
display(Image('your_image'))
I have been testing this out for my project.
Some of the other answers here inspired me to write a script for automating the mixed sequential execution of SQL tasks using SQLPLUS along with shell commands for a project, a process that was previously manually done. Maybe this (highly sanitized) example will be useful to someone else:
#!/bin/bash
acreds="user_a/supergreatpassword"
bcreds="user_b/anothergreatpassword"
hoststring='fancyoraclehoststring'
runsql () {
# param 1 is $1
sqlplus -S /nolog << EOF
CONNECT $1@$hoststring;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
$2
exit;
EOF
}
echo "TS::$(date): Starting SCHEM_A.PROC_YOU_NEED()..."
runsql "$acreds" "execute SCHEM_A.PROC_YOU_NEED();"
echo "TS::$(date): Starting superusefuljob..."
/var/scripts/superusefuljob.sh
echo "TS::$(date): Starting SCHEM_B.SECRET_B_PROC()..."
runsql "$bcreds" "execute SCHEM_B.SECRET_B_PROC();"
echo "TS::$(date): DONE"
runsql
allows you to pass a credential string as the first argument, and any SQL you need as the second argument. The variables containing the credentials are included for illustration, but for security I actually source them from another file. If you wanted to handle multiple database connections, you could easily modify the function to accept the hoststring as an additional parameter.
I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.
One solution is to style the left border like so:
li { display: inline; }
li + li {
border-left: 1px solid;
margin-left:.5em;
padding-left:.5em;
}
However, this may not give you desirable results if the entire lists wraps, like it does in your example. I.e. it would give something like:
foo | bar | baz
| bob | bill
| judy
How about:
df['new_col'] = range(1, len(df) + 1)
Alternatively if you want the index to be the ranks and store the original index as a column:
df = df.reset_index()
This fixes the box dead center on the screen:
HTML
<table class="box" border="1px">
<tr>
<td>
my content
</td>
</tr>
</table>
CSS
.box {
width:300px;
height:300px;
background-color:#d9d9d9;
position:fixed;
margin-left:-150px; /* half of width */
margin-top:-150px; /* half of height */
top:50%;
left:50%;
}
View Results
this will prevent any zoom action by the user in ios safari and also prevent the "zoom to tabs" feature:
document.addEventListener('gesturestart', function(e) {
e.preventDefault();
// special hack to prevent zoom-to-tabs gesture in safari
document.body.style.zoom = 0.99;
});
document.addEventListener('gesturechange', function(e) {
e.preventDefault();
// special hack to prevent zoom-to-tabs gesture in safari
document.body.style.zoom = 0.99;
});
document.addEventListener('gestureend', function(e) {
e.preventDefault();
// special hack to prevent zoom-to-tabs gesture in safari
document.body.style.zoom = 0.99;
});
jsfiddle: https://jsfiddle.net/vo0aqj4y/11/
Use non-greedy matching, if your engine supports it. Add the ? inside the capture.
/location="(.*?)"/
The Difference between $(document).ready()
and $(window).load()
functions is that the code included inside $(window).load()
will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
There are not difference between the above 3 codes.
They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.
jQuery.noConflict();
jQuery.ready(function($){
//Code using $ as alias to jQuery
});
This worked for me:
For the HTML, add the required
attribute to the input element
<input class="my-input-element" type="text" placeholder="" required />
For the CSS, use the :invalid
selector to target the empty input
input.my-input-element:invalid {
}
Notes:
required
from w3Schools.com:
"When present, it specifies that an input field must be filled out before submitting the form."hr {_x000D_
display: block;_x000D_
height: 1px;_x000D_
border: 0;_x000D_
border-top: 1px solid #ccc;_x000D_
margin: 1em 0;_x000D_
padding: 0;_x000D_
}
_x000D_
<div>Hello</div>_x000D_
<hr/>_x000D_
<div>World</div>
_x000D_
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
There is a special identifier that one can use in a formula to mean all the variables, it is the .
identifier.
y <- c(1,4,6)
d <- data.frame(y = y, x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
mod <- lm(y ~ ., data = d)
You can also do things like this, to use all variables but one (in this case x3 is excluded):
mod <- lm(y ~ . - x3, data = d)
Technically, .
means all variables not already mentioned in the formula. For example
lm(y ~ x1 * x2 + ., data = d)
where .
would only reference x3
as x1
and x2
are already in the formula.
you could use
line-height:35px;
You really shouldnt set a height on paragraph as its not good for accessibility (what happens if the user increase text size etc)
Instead use a Div with a hight and the p inside it with the correct line-height:
<div style="height:35px;"><p style="line-height:35px;">text</p></div>
To do it without using a JavaScript library such as jQuery, you'd do it like this:
var span = document.getElementById("myspan"),
text = document.createTextNode(''+intValue);
span.innerHTML = ''; // clear existing
span.appendChild(text);
If you do want to use jQuery, it's just this:
$("#myspan").text(''+intValue);
__getitem__
can be used to implement "lazy" dict
subclasses. The aim is to avoid instantiating a dictionary at once that either already has an inordinately large number of key-value pairs in existing containers, or has an expensive hashing process between existing containers of key-value pairs, or if the dictionary represents a single group of resources that are distributed over the internet.
As a simple example, suppose you have two lists, keys
and values
, whereby {k:v for k,v in zip(keys, values)}
is the dictionary that you need, which must be made lazy for speed or efficiency purposes:
class LazyDict(dict):
def __init__(self, keys, values):
self.keys = keys
self.values = values
super().__init__()
def __getitem__(self, key):
if key not in self:
try:
i = self.keys.index(key)
self.__setitem__(self.keys.pop(i), self.values.pop(i))
except ValueError, IndexError:
raise KeyError("No such key-value pair!!")
return super().__getitem__(key)
Usage:
>>> a = [1,2,3,4]
>>> b = [1,2,2,3]
>>> c = LazyDict(a,b)
>>> c[1]
1
>>> c[4]
3
>>> c[2]
2
>>> c[3]
2
>>> d = LazyDict(a,b)
>>> d.items()
dict_items([])
Use jQuery .siblings()
to select the matching sibling.
$(this).siblings('.bidbutton');
General algorithms for date manipulation convert dates to and from Julian Day Numbers. Here is a link to a description of such algorithms, a description of the best algorithms currently known, and the mathematical proofs of each of them: http://web.archive.org/web/20140910060704/http://mysite.verizon.net/aesir_research/date/date0.htm
You should goto the Layout folder and issue the following command:
F:\vs2017c>vs_community.exe /finalizeInstall
Then it will auto pickup cache components bypass downloading.
The method that you want to run must be a ThreadStart
Delegate. Please consult the Thread
documentation on MSDN. Note that you can sort of create your two-parameter start with a closure. Something like:
var t = new Thread(() => Startup(port, path));
Note that you may want to revisit your method accessibility. If I saw a class starting a thread on its own public method in this manner, I'd be a little surprised.
With AppleScript:
display notification "Notification text" with title "Notification Title" subtitle "Notification sub-title" sound name "Submarine"
With terminal/bash and osascript
:
osascript -e 'display notification "Notification text" with title "Notification Title" subtitle "Notification sub-title" sound name "Submarine"'
Does not take the sub-heading nor the sound tough.
With AppleScript:
display alert "Alert title" message "Your message text line here."
With terminal/bash and osascript
:
osascript -e 'display alert "Alert title" message "Your message text line here."'
Add a line in bash for playing the sound after the alert line:
afplay /System/Library/Sounds/Hero.aiff
Add same line in AppleScript, letting shell script do the work:
do shell script ("afplay /System/Library/Sounds/Hero.aiff")
List of macOS built in sounds to choose from here.
Paraphrased from a handy article on terminal and applescript notifications.
You can apply the list as separate arguments:
print(*L)
and let print()
take care of converting each element to a string. You can, as always, control the separator by setting the sep
keyword argument:
>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5
Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join()
:
joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string
Note that this requires manual conversion to strings for any non-string values in L
!
Yet another answer:
/**
* @return "ldpi", "mdpi", "hdpi", "xhdpi", "xhdpi", "xxhdpi", "xxxhdpi", "tvdpi", or "unknown".
*/
public static String getDensityBucket(Resources resources) {
switch (resources.getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
return "ldpi";
case DisplayMetrics.DENSITY_MEDIUM:
return "mdpi";
case DisplayMetrics.DENSITY_HIGH:
return "hdpi";
case DisplayMetrics.DENSITY_XHIGH:
return "xhdpi";
case DisplayMetrics.DENSITY_XXHIGH:
return "xxhdpi";
case DisplayMetrics.DENSITY_XXXHIGH:
return "xxxhdpi";
case DisplayMetrics.DENSITY_TV:
return "tvdpi";
default:
return "unknown";
}
}
It is about mathematical data transformations over time (or ignoring time).
In code this means functional purity and declarative programming.
State bugs are a huge problem in the standard imperative paradigm. Various bits of code may change some shared state at different "times" in the programs execution. This is hard to deal with.
In FRP you describe (like in declarative programming) how data transforms from one state to another and what triggers it. This allows you to ignore time because your function is simply reacting to its inputs and using their current values to create a new one. This means that the state is contained in the graph (or tree) of transformation nodes and is functionally pure.
This massively reduces complexity and debugging time.
Think of the difference between A=B+C in math and A=B+C in a program. In math you are describing a relationship that will never change. In a program, its says that "Right now" A is B+C. But the next command might be B++ in which case A is not equal to B+C. In math or declarative programming A will always be equal to B+C no matter what point in time you ask.
So by removing the complexities of shared state and changing values over time. You program is much easier to reason about.
An EventStream is an EventStream + some transformation function.
A Behaviour is an EventStream + Some value in memory.
When the event fires the value is updated by running the transformation function. The value that this produces is stored in the behaviours memory.
Behaviours can be composed to produce new behaviours that are a transformation on N other behaviours. This composed value will recalculate as the input events (behaviours) fire.
"Since observers are stateless, we often need several of them to simulate a state machine as in the drag example. We have to save the state where it is accessible to all involved observers such as in the variable path above."
Quote from - Deprecating The Observer Pattern http://infoscience.epfl.ch/record/148043/files/DeprecatingObserversTR2010.pdf
I had the same issue. As pointed out by other answers ping and nslookup use different mechanisms to lookup an ip.
Chances are you are trying to ping a machine not on the same domain. When you ping the fully qualified name of the server this should then work.
nslookup works:
PS C:\Users\Administrator> nslookup nuget
Server: ad-01.docs.com
Address: 192.168.10.20
Name: nuget.docs.com
Address: 192.168.10.17
Ping fails:
PS C:\Users\Administrator> ping nuget
Ping request could not find host nuget. Please check the name and try again.
Ping works, using FQDN:
PS C:\Users\Administrator> ping nuget.docs.com
Pinging nuget.docs.com [192.168.70.17] with 32 bytes of data:
Reply from 192.168.10.17: bytes=32 time=1ms TTL=127
Reply from 192.168.10.17: bytes=32 time=2ms TTL=127
Reply from 192.168.10.17: bytes=32 time=2ms TTL=127
Reply from 192.168.10.17: bytes=32 time=2ms TTL=127
Ping statistics for 192.168.10.17:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 1ms, Maximum = 2ms, Average = 1ms
Well I don't even understand the culprit of this problem. But in my case the problem is totally different. I've tried running netstat -o
or netstat -ab
, both show that there is not any app currently listening on port 62434 which is the one my app tries to listen on. So it's really confusing to me.
I just tried thinking of what I had made so that it stopped working (it did work before). Well then I thought of the Internet sharing I made on my Ethernet adapter with a private virtual LAN (using Hyper-v in Windows 10). I just needed to turn off the sharing and it worked just fine again.
Hope this helps someone else having the same issue. And of course if someone could explain this, please add more detail in your own answer or maybe as some comment to my answer.
From your project directory, run
react-native start
It outputs the following:
$ react-native start
+----------------------------------------------------------------------------+
¦ Running packager on port 8081. ¦
¦ ¦
¦ Keep this packager running while developing on any JS projects. Feel ¦
¦ free to close this tab and run your own packager instance if you ¦
¦ prefer. ¦
¦ ¦
¦ https://github.com/facebook/react-native ¦
¦ ¦
+----------------------------------------------------------------------------+
Looking for JS files in
/home/user/AwesomeProject
React packager ready.
[11:30:10 PM] <START> Building Dependency Graph
[11:30:10 PM] <START> Crawling File System
[11:30:16 PM] <END> Crawling File System (5869ms)
[11:30:16 PM] <START> Building in-memory fs for JavaScript
[11:30:17 PM] <END> Building in-memory fs for JavaScript (852ms)
[11:30:17 PM] <START> Building in-memory fs for Assets
[11:30:17 PM] <END> Building in-memory fs for Assets (838ms)
[11:30:17 PM] <START> Building Haste Map
[11:30:18 PM] <START> Building (deprecated) Asset Map
[11:30:18 PM] <END> Building (deprecated) Asset Map (220ms)
[11:30:18 PM] <END> Building Haste Map (759ms)
[11:30:18 PM] <END> Building Dependency Graph (8319ms)
Actually, using ZSH allows you to use special mapping of environment variables. So you can simply do:
# append
path+=('/home/david/pear/bin')
# or prepend
path=('/home/david/pear/bin' $path)
# export to sub-processes (make it inherited by child processes)
export PATH
For me that's a very neat feature which can be propagated to other variables. Example:
typeset -T LD_LIBRARY_PATH ld_library_path :
Assuming you want to throw away any changes you have, first check the output of git status
. For any file that says "unmerged" next to it, run git add <unmerged file>
. Then follow up with git reset --hard
. That will git rid of any local changes except for untracked files.
Your nav
div
is actually centered correctly. But the ul
inside is not. Give the ul
a specific width and center that as well.
If you don't like anonymous functions:
try {
DB::connection()->pdo->beginTransaction();
// database queries here
DB::connection()->pdo->commit();
} catch (\PDOException $e) {
// Woopsy
DB::connection()->pdo->rollBack();
}
Update: For laravel 4, the pdo
object isn't public anymore so:
try {
DB::beginTransaction();
// database queries here
DB::commit();
} catch (\PDOException $e) {
// Woopsy
DB::rollBack();
}
And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:
// romanNumeralDict returns map[int]string dictionary, since the return
// value is always the same it gives the pseudo-constant output, which
// can be referred to in the same map-alike fashion.
var romanNumeralDict = func() map[int]string { return map[int]string {
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I",
}
}
func printRoman(key int) {
fmt.Println(romanNumeralDict()[key])
}
func printKeyN(key, n int) {
fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
}
func main() {
printRoman(1000)
printRoman(50)
printKeyN(10, 3)
}
Comparison expressions should each be in their own brackets:
{% if (a == 'foo') or (b == 'bar') %}
...
{% endif %}
Alternative if you are inspecting a single variable and a number of possible values:
{% if a in ['foo', 'bar', 'qux'] %}
...
{% endif %}
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
If you like to keep it fixed width, for example 10 digits, do it like this
Key = i.ToString("0000000000");
Replace with as many digits as you like.
i = 123
will then result in Key = "0000000123"
.
I had the same issue, and later I figured out that I am running the application on Java version 1.4 while the application is compiled on version 6.
Actually, the reason was of having a duplicate library, one is located within the classpath and the other one is included inside a jar file that is located within the classpath.
You can use the server variables for this, for example $_SERVER['REQUEST_URI']
, or even better: $_SERVER['PHP_SELF']
.
Basically this happens when you have your Class Application in "another package". For example:
com.server
- Applicacion.class (<--this class have @ComponentScan)
com.server.config
- MongoConfig.class
com.server.repository
- UserRepository
I solve the problem with this in the Application.class
@SpringBootApplication
@ComponentScan ({"com.server", "com.server.config"})
@EnableMongoRepositories ("com.server.repository") // this fix the problem
Another less elegant way is to: put all the configuration classes in the same package.
I found Array.prototype.reverse
unsuccessful with objects, so I made a new jQuery function to use as an alternative: jQuery.eachBack()
. It iterates through as the normal jQuery.each()
would, and stores each key into an array. It then reverses that array and performs the callback on the original array/object in the order of the reversed keys.
jQuery.eachBack=function (obj, callback) {
var revKeys=[]; $.each(obj,function(rind,rval){revKeys.push(rind);});
revKeys.reverse();
$.each(revKeys,function (kind,i){
if(callback.call(obj[i], i, obj[i]) === false) { return false;}
});
return obj;
}
jQuery.fn.eachBack=function (callback,args) {
return jQuery.eachBack(this, callback, args);
}
Here is a fairly simple solution that rounds to the nearest second!
var returnElapsedTime = function(epoch) {_x000D_
//We are assuming that the epoch is in seconds_x000D_
var hours = epoch / 3600,_x000D_
minutes = (hours % 1) * 60,_x000D_
seconds = (minutes % 1) * 60;_x000D_
return Math.floor(hours) + ":" + Math.floor(minutes) + ":" + Math.round(seconds);_x000D_
}
_x000D_
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
I'm surprised that there is no answer that would mention solution with RxJava2. It is really simple and provides an easy way to setup timer in Android.
First you need to setup Gradle dependency, if you didn't do so already:
implementation "io.reactivex.rxjava2:rxjava:2.x.y"
(replace x
and y
with current version number)
Since we have just a simple, NON-REPEATING TASK, we can use Completable
object:
Completable.timer(2, TimeUnit.SECONDS, Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(() -> {
// Timer finished, do something...
});
For REPEATING TASK, you can use Observable
in a similar way:
Observable.interval(2, TimeUnit.SECONDS, Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(tick -> {
// called every 2 seconds, do something...
}, throwable -> {
// handle error
});
Schedulers.computation()
ensures that our timer is running on background thread and .observeOn(AndroidSchedulers.mainThread())
means code we run after timer finishes will be done on main thread.
To avoid unwanted memory leaks, you should ensure to unsubscribe when Activity/Fragment is destroyed.
I just found a web app i designed has this issue with iPhones and iPads, and found an article suggesting to solve it using media queries targeted at specific Apple devices.
I don't know whether I can share the code from that article here, but the address is this: http://webdesignerwall.com/tutorials/css-fix-for-ios-vh-unit-bug
Quoting the article: "just match the element height with the device height using media queries that targets the older versions of iPhone and iPad resolution."
They added just 6 media queries to adapt full height elements, and it should work as it is fully CSS implemented.
Edit pending: I'm unable to test it right now, but I will come back and report my results.
If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:
foreach ($arr_nav as $inner_array) {
echo reset($inner_array); //apple, orange, pear
echo end($inner_array); //My Apple, View All Oranges, A Pear
}
arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..
You could use the rename(1)
command:
rename 's/(.*)$/new.$1/' original.filename
Edit: If rename
isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all *.jpg
to prefix_*.jpg
in the current directory:
for filename in *.jpg; do mv "$filename" "prefix_$filename"; done;
A very simple hack is to use the json import instead of csv. For example instead of csv.writer just do the following:
fd = codecs.open(tempfilename, 'wb', 'utf-8')
for c in whatever :
fd.write( json.dumps(c) [1:-1] ) # json dumps writes ["a",..]
fd.write('\n')
fd.close()
Basically, given the list of fields in correct order, the json formatted string is identical to a csv line except for [ and ] at the start and end respectively. And json seems to be robust to utf-8 in python 2.*
As far as I understand, the question is NOT about recursion. We can easily call main
method of another class in your class. Following example illustrates static and calling by object. Note omission of word static
in Class2
class Class1{
public static void main(String[] args) {
System.out.println("this is class 1");
}
}
class Class2{
public void main(String[] args) {
System.out.println("this is class 2");
}
}
class MyInvokerClass{
public static void main(String[] args) {
System.out.println("this is MyInvokerClass");
Class2 myClass2 = new Class2();
Class1.main(args);
myClass2.main(args);
}
}
Output Should be:
this is wrapper class
this is class 1
this is class 2
I did this
~]$ export A=g
~]$ export B=!
~]$ export C=nger
curl http://<>USERNAME<>1:$A$B$C@<>URL<>/<>PATH<>/
You can center an image, both horizontally and vertically, using margin: auto
and absolute positioning. Also:
.responsive-container {_x000D_
margin: 1em auto;_x000D_
min-width: 200px; /* cap container min width */_x000D_
max-width: 500px; /* cap container max width */_x000D_
position: relative; _x000D_
overflow: hidden; /* crop if image is larger than container */_x000D_
background-color: #CCC; _x000D_
}_x000D_
.responsive-container:before {_x000D_
content: ""; /* using pseudo element for 1:1 ratio */_x000D_
display: block;_x000D_
padding-top: 100%;_x000D_
}_x000D_
.responsive-container img {_x000D_
position: absolute;_x000D_
top: -999px; /* use sufficiently large number */_x000D_
bottom: -999px;_x000D_
left: -999px;_x000D_
right: -999px;_x000D_
margin: auto; /* center horizontally and vertically */_x000D_
}
_x000D_
<p>Note: images are center-cropped on <400px screen width._x000D_
<br>Open full page demo and resize browser.</p>_x000D_
<div class="responsive-container">_x000D_
<img src="http://lorempixel.com/400/400/sports/9/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
<img src="http://lorempixel.com/400/200/sports/8/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
<img src="http://lorempixel.com/200/400/sports/7/">_x000D_
</div>_x000D_
<div class="responsive-container">_x000D_
<img src="http://lorempixel.com/200/200/sports/6/">_x000D_
</div>
_x000D_
Using standard git diff command (also good for scripting):
git diff --name-only <sha>^ <sha>
If you want also the status of the changed files:
git diff --name-status <sha>^ <sha>
This works well with merge commits.
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
As @jem suggested, it is possible to use jsoup.
With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.
import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);
It seems that in some previous release this method is not present.
If you want to return a boolean value, then you can use something like this (much faster than filter):
players.stream().anyMatch(player -> player.getName().contains(name));
You can't easily use a range here because the iterator you get from a map refers to a std::pair, where the iterators you would use to insert into a vector refers to an object of the type stored in the vector, which is (if you are discarding the key) not a pair.
I really don't think it gets much cleaner than the obvious:
#include <map>
#include <vector>
#include <string>
using namespace std;
int main() {
typedef map <string, int> MapType;
MapType m;
vector <int> v;
// populate map somehow
for( MapType::iterator it = m.begin(); it != m.end(); ++it ) {
v.push_back( it->second );
}
}
which I would probably re-write as a template function if I was going to use it more than once. Something like:
template <typename M, typename V>
void MapToVec( const M & m, V & v ) {
for( typename M::const_iterator it = m.begin(); it != m.end(); ++it ) {
v.push_back( it->second );
}
}
Here is my implementation for calculating the week number in JavaScript. corrected for summer and winter time offsets as well. I used the definition of the week from this article: ISO 8601
Weeks are from mondays to sunday, and january 4th is always in the first week of the year.
// add get week prototype functions
// weeks always start from monday to sunday
// january 4th is always in the first week of the year
Date.prototype.getWeek = function () {
year = this.getFullYear();
var currentDotw = this.getWeekDay();
if (this.getMonth() == 11 && this.getDate() - currentDotw > 28) {
// if true, the week is part of next year
return this.getWeekForYear(year + 1);
}
if (this.getMonth() == 0 && this.getDate() + 6 - currentDotw < 4) {
// if true, the week is part of previous year
return this.getWeekForYear(year - 1);
}
return this.getWeekForYear(year);
}
// returns a zero based day, where monday = 0
// all weeks start with monday
Date.prototype.getWeekDay = function () {
return (this.getDay() + 6) % 7;
}
// corrected for summer/winter time
Date.prototype.getWeekForYear = function (year) {
var currentDotw = this.getWeekDay();
var fourjan = new Date(year, 0, 4);
var firstDotw = fourjan.getWeekDay();
var dayTotal = this.getDaysDifferenceCorrected(fourjan) // the difference in days between the two dates.
// correct for the days of the week
dayTotal += firstDotw; // the difference between the current date and the first monday of the first week,
dayTotal -= currentDotw; // the difference between the first monday and the current week's monday
// day total should be a multiple of 7 now
var weeknumber = dayTotal / 7 + 1; // add one since it gives a zero based week number.
return weeknumber;
}
// corrected for timezones and offset
Date.prototype.getDaysDifferenceCorrected = function (other) {
var millisecondsDifference = (this - other);
// correct for offset difference. offsets are in minutes, the difference is in milliseconds
millisecondsDifference += (other.getTimezoneOffset()- this.getTimezoneOffset()) * 60000;
// return day total. 1 day is 86400000 milliseconds, floor the value to return only full days
return Math.floor(millisecondsDifference / 86400000);
}
for testing i used the following JavaScript tests in Qunit
var runweekcompare = function(result, expected) {
equal(result, expected,'Week nr expected value: ' + expected + ' Actual value: ' + result);
}
test('first week number test', function () {
expect(5);
var temp = new Date(2016, 0, 4); // is the monday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 4, 23, 50); // is the monday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 10, 23, 50); // is the sunday of the first week of the year
runweekcompare(temp.getWeek(), 1);
var temp = new Date(2016, 0, 11, 23, 50); // is the second week of the year
runweekcompare(temp.getWeek(), 2);
var temp = new Date(2016, 1, 29, 23, 50); // is the 9th week of the year
runweekcompare(temp.getWeek(), 9);
});
test('first day is part of last years last week', function () {
expect(2);
var temp = new Date(2016, 0, 1, 23, 50); // is the first last week of the previous year
runweekcompare(temp.getWeek(), 53);
var temp = new Date(2011, 0, 2, 23, 50); // is the first last week of the previous year
runweekcompare(temp.getWeek(), 52);
});
test('last day is part of next years first week', function () {
var temp = new Date(2013, 11, 30); // is part of the first week of 2014
runweekcompare(temp.getWeek(), 1);
});
test('summer winter time change', function () {
expect(2);
var temp = new Date(2000, 2, 26);
runweekcompare(temp.getWeek(), 12);
var temp = new Date(2000, 2, 27);
runweekcompare(temp.getWeek(), 13);
});
test('full 20 year test', function () {
//expect(20 * 12 * 28 * 2);
for (i = 2000; i < 2020; i++) {
for (month = 0; month < 12; month++) {
for (day = 1; day < 29 ; day++) {
var temp = new Date(i, month, day);
var expectedweek = temp.getWeek();
var temp2 = new Date(i, month, day, 23, 50);
var resultweek = temp.getWeek();
equal(expectedweek, Math.round(expectedweek), 'week number whole number expected ' + Math.round(expectedweek) + ' resulted week nr ' + expectedweek);
equal(resultweek, expectedweek, 'Week nr expected value: ' + expectedweek + ' Actual value: ' + resultweek + ' for year ' + i + ' month ' + month + ' day ' + day);
}
}
}
});
First of all the term fragmentation cues there's an entity divided into parts — fragments.
Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"
External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous
You can also do this by service name.
First, try to find the service name of the respective pod which corresponds to multiple pods of the same service. kubectl get svc
.
Next, run the following command to display logs from each container.
kubectl logs -f service/<service-name>
Tensorflow 2.0 Compatible Answer: The explanations of dga
and stackoverflowuser2010
are very detailed about Logits and the related Functions.
All those functions, when used in Tensorflow 1.x
will work fine, but if you migrate your code from 1.x (1.14, 1.15, etc)
to 2.x (2.0, 2.1, etc..)
, using those functions result in error.
Hence, specifying the 2.0 Compatible Calls for all the functions, we discussed above, if we migrate from 1.x to 2.x
, for the benefit of the community.
Functions in 1.x:
tf.nn.softmax
tf.nn.softmax_cross_entropy_with_logits
tf.nn.sparse_softmax_cross_entropy_with_logits
Respective Functions when Migrated from 1.x to 2.x:
tf.compat.v2.nn.softmax
tf.compat.v2.nn.softmax_cross_entropy_with_logits
tf.compat.v2.nn.sparse_softmax_cross_entropy_with_logits
For more information about migration from 1.x to 2.x, please refer this Migration Guide.
In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.
Here are some that do not resize their contents (I'm guessing that you are using one or more of these):
StackPanel
WrapPanel
Canvas
TabControl
Here are some that do resize their contents:
Grid
UniformGrid
DockPanel
Therefore, it is almost always preferable to use a Grid
instead of a StackPanel
unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid
to not size its inner controls... it all depends on your Grid.RowDefinition
and Grid.ColumnDefinition
settings:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
<RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
<RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
</Grid.RowDefinitions>
</Grid>
You can find out more about the Grid
control from the Grid
Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.
Further resizing can be achieved using the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties. The default value of these properties is Stretch
which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.
UPDATE >>>
In response to the questions in your comment:
Use the Grid.RowDefinition
and Grid.ColumnDefinition
settings to organise a basic structure first... it is common to add Grid
controls into the cells of outer Grid
controls if need be. You can also use the Grid.ColumnSpan
and Grid.RowSpan
properties to enable controls to span multiple columns and/or rows of a Grid
.
It is most common to have at least one row/column with a Height
/Width
of "*"
which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.
There is no Auto
setting that you can use on the controls in the cells, but this is just as well, because we want the Grid
to size the controls for us... therefore, we don't want to set the Height
or Width
of these controls at all.
The point that I made about the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties was just to let you know of their existence... as their default value is already Stretch
, you don't generally need to set them explicitly.
The Margin
property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin
property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin
property to suit your needs.
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
% ps -o args -C nginx
COMMAND
build/sbin/nginx -c ../test.conf
If nginx was run without the -c
option, then you can use the -V
option to find out the configure arguments that were set to non-standard values. Among them the most interesting for you are:
--prefix=PATH set installation prefix
--sbin-path=PATH set nginx binary pathname
--conf-path=PATH set nginx.conf pathname
Using the code from my answer to a very similar question:
Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
For Each cell In Selection
If IsInArray(cell.Value, MainFram) Then
Row(cell.Row).Style = "Accent1"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
Sorry to burst your bubble but Spotify desktop client is just a Webkit-based browser. Of course it exposes specific additional functionality, but it's only able to run JS and render HTML/CSS because it has a JS engine as well as a Chromium rendering engine. This does not help you with coding a client-side web-app and deploying to multiple platforms.
What you're looking for is similar to Sencha Touch - a framework that allows for HTML5 apps to be natively deployed to iOS, Android and Blackberry devices. It basically acts as an intermediary between certain API calls and device-specific functionality available.
I have no experience with appcelerator, bit it appears to be doing exactly that - and get very favourable reviews online. You should give it a go (unless you wanted to go back to 1999 and roll with MS HTA ;)
Nice question, a while ago I've experimented a bit with this, but haven't used it a lot because it's still not bulletproof. I divided the plot area into a 32x32 grid and calculated a 'potential field' for the best position of a label for each line according the following rules:
The code was something like this:
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
def my_legend(axis = None):
if axis == None:
axis = plt.gca()
N = 32
Nlines = len(axis.lines)
print Nlines
xmin, xmax = axis.get_xlim()
ymin, ymax = axis.get_ylim()
# the 'point of presence' matrix
pop = np.zeros((Nlines, N, N), dtype=np.float)
for l in range(Nlines):
# get xy data and scale it to the NxN squares
xy = axis.lines[l].get_xydata()
xy = (xy - [xmin,ymin]) / ([xmax-xmin, ymax-ymin]) * N
xy = xy.astype(np.int32)
# mask stuff outside plot
mask = (xy[:,0] >= 0) & (xy[:,0] < N) & (xy[:,1] >= 0) & (xy[:,1] < N)
xy = xy[mask]
# add to pop
for p in xy:
pop[l][tuple(p)] = 1.0
# find whitespace, nice place for labels
ws = 1.0 - (np.sum(pop, axis=0) > 0) * 1.0
# don't use the borders
ws[:,0] = 0
ws[:,N-1] = 0
ws[0,:] = 0
ws[N-1,:] = 0
# blur the pop's
for l in range(Nlines):
pop[l] = ndimage.gaussian_filter(pop[l], sigma=N/5)
for l in range(Nlines):
# positive weights for current line, negative weight for others....
w = -0.3 * np.ones(Nlines, dtype=np.float)
w[l] = 0.5
# calculate a field
p = ws + np.sum(w[:, np.newaxis, np.newaxis] * pop, axis=0)
plt.figure()
plt.imshow(p, interpolation='nearest')
plt.title(axis.lines[l].get_label())
pos = np.argmax(p) # note, argmax flattens the array first
best_x, best_y = (pos / N, pos % N)
x = xmin + (xmax-xmin) * best_x / N
y = ymin + (ymax-ymin) * best_y / N
axis.text(x, y, axis.lines[l].get_label(),
horizontalalignment='center',
verticalalignment='center')
plt.close('all')
x = np.linspace(0, 1, 101)
y1 = np.sin(x * np.pi / 2)
y2 = np.cos(x * np.pi / 2)
y3 = x * x
plt.plot(x, y1, 'b', label='blue')
plt.plot(x, y2, 'r', label='red')
plt.plot(x, y3, 'g', label='green')
my_legend()
plt.show()
And the resulting plot:
The only easy way to do this is to use snprintf
to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:
char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);
'self.webView.scrollView.bounces = NO;'
Just add this one line in the 'viewDidLoad' of the mainViewController.m file of your application. you can open it in the Xcode and add it .
This should make the page without any rubberband bounces still enabling the scroll in the app view.
Try this
git clone ssh://[email protected]:11111/home/git/repo.git
I think the canonical method is:
while IFS=, read field1 field2 field3 field4 field5 field6; do
do stuff
done < CSV.file
If you don't know or don't care about how many fields there are:
IFS=,
while read line; do
# split into an array
field=( $line )
for word in "${field[@]}"; do echo "$word"; done
# or use the positional parameters
set -- $line
for word in "$@"; do echo "$word"; done
done < CSV.file
Never tried with non Windows systems, but here's the one I have in my library, pretty easy to use. No special library reference required.
Function CreateFolder(ByVal sPath As String) As Boolean
'by Patrick Honorez - www.idevlop.com
'create full sPath at once, if required
'returns False if folder does not exist and could NOT be created, True otherwise
'sample usage: If CreateFolder("C:\toto\test\test") Then debug.print "OK"
'updated 20130422 to handle UNC paths correctly ("\\MyServer\MyShare\MyFolder")
Dim fs As Object
Dim FolderArray
Dim Folder As String, i As Integer, sShare As String
If Right(sPath, 1) = "\" Then sPath = Left(sPath, Len(sPath) - 1)
Set fs = CreateObject("Scripting.FileSystemObject")
'UNC path ? change 3 "\" into 3 "@"
If sPath Like "\\*\*" Then
sPath = Replace(sPath, "\", "@", 1, 3)
End If
'now split
FolderArray = Split(sPath, "\")
'then set back the @ into \ in item 0 of array
FolderArray(0) = Replace(FolderArray(0), "@", "\", 1, 3)
On Error GoTo hell
'start from root to end, creating what needs to be
For i = 0 To UBound(FolderArray) Step 1
Folder = Folder & FolderArray(i) & "\"
If Not fs.FolderExists(Folder) Then
fs.CreateFolder (Folder)
End If
Next
CreateFolder = True
hell:
End Function
SELECT s.name + '.' + ao.name
, s.name
FROM sys.all_objects ao
INNER JOIN sys.schemas s ON s.schema_id = ao.schema_id
WHERE ao.type='u';
One workaround could be to addClass to a container of the svg element:
$('.svg-container').addClass('svg-red');
_x000D_
.svg-red svg circle{_x000D_
fill: #ED3F32;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="svg-container">_x000D_
<svg height="40" width="40">_x000D_
<circle cx="20" cy="20" r="20"/>_x000D_
</svg>_x000D_
</div>
_x000D_
this.getClass().getClassLoader().getResource("").getPath()
To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0
, then you can be sure the original only contained whitespace. Try this:
var str = " ";_x000D_
if (!str.replace(/\s/g, '').length) {_x000D_
console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');_x000D_
}
_x000D_
there is configuration in the following way:
Preferences -> keys -> Navigation shortcuts
the 3rd option: shortcut to choose a split pane is "no shortcut" by default, we can choose one
cheers
If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103
I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.
Try this one
getActivity().finish();
This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input()
.
Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling
So instead of giving input to the program line by line try to map the space separated integers into a list using the map()
method.
The answer of Flip is computationally more consistent than the Muis one.
Using double number format, you could see the roundoff problem in the Muis approach:
When you divide and subtract, a roundoff appears in the previous stored value, changing it.
However, the Flip approach preserves the stored value and reduces the number of divisions, hence, reducing the roundoff, and minimizing the error propagated to the stored value. Adding only will bring up roundoffs if there is something to add (when N is big, there is nothing to add)
Those changes are remarkable when you make a mean of big values tend their mean to zero.
I show you the results using a spreadsheet program:
Firstly, the results obtained:
The A and B columns are the n and X_n values, respectively.
The C column is the Flip approach, and the D one is the Muis approach, the result stored in the mean. The E column corresponds with the medium value used in the computation.
A graph showing the mean of even values is the next one:
As you can see, there is big differences between both approachs.
The procedure is already well explained in the above answers. But if add the ANDROID_HOME
and PATH
to the .bashrc
or .zshrc
present in /home/username/
and try to run the ionic
command with sudo
, you may get this error again.
The reason is, it may look for the ANDROID_HOME
and PATH
in the .zshrc
file of root user instead of currently logged in user. So you shouldn't do that unless you add that in root user's .bashrc
or .zshrc
files.
I installed webapi with it via the helppages nuget package. That package replaced most of the asp.net mvc 4 binaries with beta versions which didn't work well together with the rest of the project. Fix was to restore the original mvc 4 dll's and all was good.
Your test requires a ServletContext: add @WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT
...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
UPDATE
In Spring Boot 1.4.x and above @WebIntegrationTest
is no longer preferred. @SpringBootTest
or @WebMvcTest
It has really different usage scenarios. When you use GROUP BY you merge some of the records for the columns that are same and you have an aggregation of the result set.
However when you use PARTITION BY your result set is same but you just have an aggregation over the window functions and you don't merge the records, you will still have the same count of records.
Here is a rally helpful article explaining the difference: http://alevryustemov.com/sql/sql-partition-by/
Function strlen
shows the number of character before \0
and using it for std::string
may report wrong length.
strlen(str.c_str()); // It may return wrong length.
In C++, a string can contain \0
within the characters but C-style-zero-terminated strings can not but at the end. If the std::string
has a \0
before the last character then strlen
reports a length less than the actual length.
Try to use .length()
or .size()
, I prefer second one since another standard containers have it.
str.size()
You have 9 fields listed, but only 8 values. Try adding the method.
The following works as expected:
SELECT Diff = CASE DATEDIFF(HOUR, StartTime, EndTime)
WHEN 0 THEN CAST(DATEDIFF(MINUTE, StartTime, EndTime) AS VARCHAR(10))
ELSE CAST(60 - DATEPART(MINUTE, StartTime) AS VARCHAR(10)) +
REPLICATE(',60', DATEDIFF(HOUR, StartTime, EndTime) - 1) +
+ ',' + CAST(DATEPART(MINUTE, EndTime) AS VARCHAR(10))
END
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) t (StartTime, EndTime);
To get 24 columns, you could use 24 case expressions, something like:
SELECT [0] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 0
THEN DATEDIFF(MINUTE, StartTime, EndTime)
ELSE 60 - DATEPART(MINUTE, StartTime)
END,
[1] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 1
THEN DATEPART(MINUTE, EndTime)
WHEN DATEDIFF(HOUR, StartTime, EndTime) > 1 THEN 60
END,
[2] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 2
THEN DATEPART(MINUTE, EndTime)
WHEN DATEDIFF(HOUR, StartTime, EndTime) > 2 THEN 60
END -- ETC
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) t (StartTime, EndTime);
The following also works, and may end up shorter than repeating the same case expression over and over:
WITH Numbers (Number) AS
( SELECT ROW_NUMBER() OVER(ORDER BY t1.N) - 1
FROM (VALUES (1), (1), (1), (1), (1), (1)) AS t1 (N)
CROSS JOIN (VALUES (1), (1), (1), (1)) AS t2 (N)
), YourData AS
( SELECT StartTime, EndTime
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('09:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) AS t (StartTime, EndTime)
), PivotData AS
( SELECT t.StartTime,
t.EndTime,
n.Number,
MinuteDiff = CASE WHEN n.Number = 0 AND DATEDIFF(HOUR, StartTime, EndTime) = 0 THEN DATEDIFF(MINUTE, StartTime, EndTime)
WHEN n.Number = 0 THEN 60 - DATEPART(MINUTE, StartTime)
WHEN DATEDIFF(HOUR, t.StartTime, t.EndTime) <= n.Number THEN DATEPART(MINUTE, EndTime)
ELSE 60
END
FROM YourData AS t
INNER JOIN Numbers AS n
ON n.Number <= DATEDIFF(HOUR, StartTime, EndTime)
)
SELECT *
FROM PivotData AS d
PIVOT
( MAX(MinuteDiff)
FOR Number IN
( [0], [1], [2], [3], [4], [5],
[6], [7], [8], [9], [10], [11],
[12], [13], [14], [15], [16], [17],
[18], [19], [20], [21], [22], [23]
)
) AS pvt;
It works by joining to a table of 24 numbers, so the case expression doesn't need to be repeated, then rolling these 24 numbers back up into columns using PIVOT
make sure you're using the newest jquery, and problem solved
I met this problem with this code:
<script src="/scripts/plugins/jquery/jquery-1.6.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>
After change it to this:
<script src="/scripts/plugins/jquery/jquery-1.7.2.min.js"> </script>
<script src="/scripts/plugins/bootstrap/js/bootstrap.js"></script>
It works fine
Use a wildcard (*
) to match multiple files.
For example, the command below will delete all files with names beginning with abc.log.2012-03-
.
rm -f abc.log.2012-03-*
I'd recommend running ls abc.log.2012-03-*
to list the files so that you can see what you are going to delete before running the rm
command.
For more details see the Bash man page on filename expansion.
How to add single item. This is not very effective but follows what you are asking for:
x = p.Series()
N = 4
for i in xrange(N):
x = x.set_value(i, i**2)
produces x:
0 0
1 1
2 4
3 9
Obviously there are better ways to generate this series in only one shot.
For your second question check answer and references of SO question add one row in a pandas.DataFrame.
You can't assign a process output directly into a var, you need to parse the output with a For /F loop:
@Echo OFF
FOR /F "Tokens=2,*" %%A IN (
'Reg Query "HKEY_CURRENT_USER\Software\Macromedia\FlashPlayer" /v "CurrentVersion"'
) DO (
REM Set "Version=%%B"
Echo Version: %%B
)
Pause&Exit
PS: Change the reg key used if needed.
I changed 3 things and then it works:
A hash_map
is an older, unstandardized version of what for standardization purposes is called an unordered_map
(originally in TR1, and included in the standard since C++11). As the name implies, it's different from std::map
primarily in being unordered -- if, for example, you iterate through a map from begin()
to end()
, you get items in order by key1, but if you iterate through an unordered_map
from begin()
to end()
, you get items in a more or less arbitrary order.
An unordered_map
is normally expected to have constant complexity. That is, an insertion, lookup, etc., typically takes essentially a fixed amount of time, regardless of how many items are in the table. An std::map
has complexity that's logarithmic on the number of items being stored -- which means the time to insert or retrieve an item grows, but quite slowly, as the map grows larger. For example, if it takes 1 microsecond to lookup one of 1 million items, then you can expect it to take around 2 microseconds to lookup one of 2 million items, 3 microseconds for one of 4 million items, 4 microseconds for one of 8 million items, etc.
From a practical viewpoint, that's not really the whole story though. By nature, a simple hash table has a fixed size. Adapting it to the variable-size requirements for a general purpose container is somewhat non-trivial. As a result, operations that (potentially) grow the table (e.g., insertion) are potentially relatively slow (that is, most are fairly fast, but periodically one will be much slower). Lookups, which cannot change the size of the table, are generally much faster. As a result, most hash-based tables tend to be at their best when you do a lot of lookups compared to the number of insertions. For situations where you insert a lot of data, then iterate through the table once to retrieve results (e.g., counting the number of unique words in a file) chances are that an std::map
will be just as fast, and quite possibly even faster (but, again, the computational complexity is different, so that can also depend on the number of unique words in the file).
1 Where the order is defined by the third template parameter when you create the map, std::less<T>
by default.
There's very little reason not to open multiple workbooks in Excel. Key lines of code are:
Application.EnableEvents = False
Application.ScreenUpdating = False
...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...
Application.DisplayAlerts = False
Application.Calculation = xlManual
...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming
If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format
Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data
An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With
FName = VBA.Dir(InputFolder)
Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop
Hopefully some of the above will be of use
If you are printing to stderr using the stdio library, a call to fflush(stderr)
should flush the buffer and get you real-time logging.
The bitmap constructor has resizing built in.
Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");
http://msdn.microsoft.com/en-us/library/0wh0045z.aspx
If you want control over interpolation modes see this post.
body{
height: 100%;
overflow: hidden !important;
width: 100%;
position: fixed;
works on iOS9
This command will give you postgres port number
\conninfo
If postgres is running on Linux server, you can also use the following command
sudo netstat -plunt |grep postgres
OR (if it comes as postmaster)
sudo netstat -plunt |grep postmaster
and you will see something similar as this
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 140/postgres
tcp6 0 0 ::1:5432 :::* LISTEN 140/postgres
in this case, port number is 5432 which is also default port number
credits link
yourTextView.setTextColor(color);
Or, in your case: yourTextView.setTextColor(0xffbdbdbd);
self.rx.viewDidAppearOnce
.flatMapLatest { _ in RxKeyboard.instance.isHidden }
.bind(onNext: { [unowned self] isHidden in
guard !isHidden else { return }
self.tableView.beginUpdates()
self.tableView.contentInsetAdjustmentBehavior = .automatic
self.tableView.endUpdates()
})
.disposed(by: self.disposeBag)
Try putting white-space:nowrap;
in your <ul>
style
edit: and use 'inline' rather than 'inline-block' as other have pointed out (and I forgot)
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
you can check if your session has a row in V$TRANSACTION
(obviously that requires read privilege on this view):
SQL> SELECT COUNT(*)
FROM v$transaction t, v$session s, v$mystat m
WHERE t.ses_addr = s.saddr
AND s.sid = m.sid
AND ROWNUM = 1;
COUNT(*)
----------
0
SQL> insert into a values (1);
1 row inserted
SQL> SELECT COUNT(*)
FROM v$transaction t, v$session s, v$mystat m
WHERE t.ses_addr = s.saddr
AND s.sid = m.sid
AND ROWNUM = 1;
COUNT(*)
----------
1
SQL> commit;
Commit complete
SQL> SELECT COUNT(*)
FROM v$transaction t, v$session s, v$mystat m
WHERE t.ses_addr = s.saddr
AND s.sid = m.sid
AND ROWNUM = 1;
COUNT(*)
----------
0
You can also use something like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add / Remove Table Rows Dynamically</title>
<style type="text/css">
form{
margin: 20px 0;
}
form input, button{
padding: 5px;
}
table{
width: 100%;
margin-bottom: 20px;
border-collapse: collapse;
}
table, th, td{
border: 1px solid #cdcdcd;
}
table th, table td{
padding: 10px;
text-align: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".add-row").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
$("table tbody").append(markup);
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text" id="name" placeholder="Name">
<input type="text" id="email" placeholder="Email Address">
<input type="button" class="add-row" value="Add Row">
</form>
<table>
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="record"></td>
<td>Peter Parker</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
</body>
</html>
You can use window.location.reload();
in your componentDidMount()
lifecycle method. If you are using react-router
, it has a refresh method to do that.
Edit: If you want to do that after a data update, you might be looking to a re-render
not a reload
and you can do that by using this.setState(). Here is a basic example of it to fire a re-render
after data is fetched.
import React from 'react'
const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;
class MyComponent extends React.Component {
state = {
users: null
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(users => this.setState({users: users}));
}
render() {
const {users} = this.state;
if (users) {
return (
<ul>
{users.map(user => <li>{user.name}</li>)}
</ul>
)
} else {
return (<h1>Loading ...</h1>)
}
}
}
export default MyComponent;
Instead of using string interpolation you could simply format the DateTime using the ToString("u")
method and concatenate that with the rest of the string:
$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u")
change it to chart.googleapis.com for the path, otherwise SSL won't work
When calling rsync within java (and perhaps other languages), I found that setting
-e ssh -p 22
resulting in rsync complaining it could not execute the binary:
ssh -p 22
because that path ssh -p 22
did not exist (the -p and 22 are no longer arguments for some reason and now make up part of the path to the binary rsync should call).
To workaround this problem I was able to use this environment variable:
export "RSYNC_RSH=ssh -p 2222"
(Programmatically set within java using env.put("RSYNC_RSH", "ssh -p " + port);
)
Here is what I believe answers the question (Python 3, with type hints):
from datetime import date
def int2date(argdate: int) -> date:
"""
If you have date as an integer, use this method to obtain a datetime.date object.
Parameters
----------
argdate : int
Date as a regular integer value (example: 20160618)
Returns
-------
dateandtime.date
A date object which corresponds to the given value `argdate`.
"""
year = int(argdate / 10000)
month = int((argdate % 10000) / 100)
day = int(argdate % 100)
return date(year, month, day)
print(int2date(20160618))
The code above produces the expected 2016-06-18
.
The following code is in plain c language and handles blank spaces. It only allocates memory once, so one free() is needed, for each processed line.
/* Tiny CSV Reader */
/* Copyright (C) 2015, Deligiannidis Konstantinos
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://w...content-available-to-author-only...u.org/licenses/>. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* For more that 100 columns or lines (when delimiter = \n), minor modifications are needed. */
int getcols( const char * const line, const char * const delim, char ***out_storage )
{
const char *start_ptr, *end_ptr, *iter;
char **out;
int i; //For "for" loops in the old c style.
int tokens_found = 1, delim_size, line_size; //Calculate "line_size" indirectly, without strlen() call.
int start_idx[100], end_idx[100]; //Store the indexes of tokens. Example "Power;": loc('P')=1, loc(';')=6
//Change 100 with MAX_TOKENS or use malloc() for more than 100 tokens. Example: "b1;b2;b3;...;b200"
if ( *out_storage != NULL ) return -4; //This SHOULD be NULL: Not Already Allocated
if ( !line || !delim ) return -1; //NULL pointers Rejected Here
if ( (delim_size = strlen( delim )) == 0 ) return -2; //Delimiter not provided
start_ptr = line; //Start visiting input. We will distinguish tokens in a single pass, for good performance.
//Then we are allocating one unified memory region & doing one memory copy.
while ( ( end_ptr = strstr( start_ptr, delim ) ) ) {
start_idx[ tokens_found -1 ] = start_ptr - line; //Store the Index of current token
end_idx[ tokens_found - 1 ] = end_ptr - line; //Store Index of first character that will be replaced with
//'\0'. Example: "arg1||arg2||end" -> "arg1\0|arg2\0|end"
tokens_found++; //Accumulate the count of tokens.
start_ptr = end_ptr + delim_size; //Set pointer to the next c-string within the line
}
for ( iter = start_ptr; (*iter!='\0') ; iter++ );
start_idx[ tokens_found -1 ] = start_ptr - line; //Store the Index of current token: of last token here.
end_idx[ tokens_found -1 ] = iter - line; //and the last element that will be replaced with \0
line_size = iter - line; //Saving CPU cycles: Indirectly Count the size of *line without using strlen();
int size_ptr_region = (1 + tokens_found)*sizeof( char* ); //The size to store pointers to c-strings + 1 (*NULL).
out = (char**) malloc( size_ptr_region + ( line_size + 1 ) + 5 ); //Fit everything there...it is all memory.
//It reserves a contiguous space for both (char**) pointers AND string region. 5 Bytes for "Out of Range" tests.
*out_storage = out; //Update the char** pointer of the caller function.
//"Out of Range" TEST. Verify that the extra reserved characters will not be changed. Assign Some Values.
//char *extra_chars = (char*) out + size_ptr_region + ( line_size + 1 );
//extra_chars[0] = 1; extra_chars[1] = 2; extra_chars[2] = 3; extra_chars[3] = 4; extra_chars[4] = 5;
for ( i = 0; i < tokens_found; i++ ) //Assign adresses first part of the allocated memory pointers that point to
out[ i ] = (char*) out + size_ptr_region + start_idx[ i ]; //the second part of the memory, reserved for Data.
out[ tokens_found ] = (char*) NULL; //[ ptr1, ptr2, ... , ptrN, (char*) NULL, ... ]: We just added the (char*) NULL.
//Now assign the Data: c-strings. (\0 terminated strings):
char *str_region = (char*) out + size_ptr_region; //Region inside allocated memory which contains the String Data.
memcpy( str_region, line, line_size ); //Copy input with delimiter characters: They will be replaced with \0.
//Now we should replace: "arg1||arg2||arg3" with "arg1\0|arg2\0|arg3". Don't worry for characters after '\0'
//They are not used in standard c lbraries.
for( i = 0; i < tokens_found; i++) str_region[ end_idx[ i ] ] = '\0';
//"Out of Range" TEST. Wait until Assigned Values are Printed back.
//for ( int i=0; i < 5; i++ ) printf("c=%x ", extra_chars[i] ); printf("\n");
// *out memory should now contain (example data):
//[ ptr1, ptr2,...,ptrN, (char*) NULL, "token1\0", "token2\0",...,"tokenN\0", 5 bytes for tests ]
// |__________________________________^ ^ ^ ^
// |_______________________________________| | |
// |_____________________________________________| These 5 Bytes should be intact.
return tokens_found;
}
int main()
{
char in_line[] = "Arg1;;Th;s is not Del;m;ter;;Arg3;;;;Final";
char delim[] = ";;";
char **columns;
int i;
printf("Example1:\n");
columns = NULL; //Should be NULL to indicate that it is not assigned to allocated memory. Otherwise return -4;
int cols_found = getcols( in_line, delim, &columns);
for ( i = 0; i < cols_found; i++ ) printf("Column[ %d ] = %s\n", i, columns[ i ] ); //<- (1st way).
// (2nd way) // for ( i = 0; columns[ i ]; i++) printf("start_idx[ %d ] = %s\n", i, columns[ i ] );
free( columns ); //Release the Single Contiguous Memory Space.
columns = NULL; //Pointer = NULL to indicate it does not reserve space and that is ready for the next malloc().
printf("\n\nExample2, Nested:\n\n");
char example_file[] = "ID;Day;Month;Year;Telephone;email;Date of registration\n"
"1;Sunday;january;2009;123-124-456;[email protected];2015-05-13\n"
"2;Monday;March;2011;(+30)333-22-55;[email protected];2009-05-23";
char **rows;
int j;
rows = NULL; //getcols() requires it to be NULL. (Avoid dangling pointers, leaks e.t.c).
getcols( example_file, "\n", &rows);
for ( i = 0; rows[ i ]; i++) {
{
printf("Line[ %d ] = %s\n", i, rows[ i ] );
char **columnX = NULL;
getcols( rows[ i ], ";", &columnX);
for ( j = 0; columnX[ j ]; j++) printf(" Col[ %d ] = %s\n", j, columnX[ j ] );
free( columnX );
}
}
free( rows );
rows = NULL;
return 0;
}
You can set :
overflow-y: scroll;height: XX px
mailx -a /path/to/file email@address
You might go into interactive mode (it will prompt you with "Subject: " and then a blank line), enter a subject, then enter a body and hit Ctrl+D (EOT) to finish.
Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.
It also has a JsonValue blob = JsonValue.Parse(json);
you can use. The blob will most likely be of type JsonObject
which is derived from JsonValue
, but could be JsonArray
. Check the blob.JsonType
if you need to know.
And to answer you question, YES, you may replace json
with the name of your actual variable that holds the JSON string. ;-D
There is a System.Json.dll you should add to your project References.
-Jesse
As rcs stated, cex
will do the job in base graphics package. I reckon that you're not willing to do your graph in ggplot2
but if you do, there's a size
aesthetic attribute, that you can easily control (ggplot2
has user-friendly function arguments: instead of typing cex
(character expansion), in ggplot2
you can type e.g. size = 2
and you'll get 2mm point).
Here's the example:
### base graphics ###
plot(mpg ~ hp, data = mtcars, pch = 16, cex = .9)
### ggplot2 ###
# with qplot()
qplot(mpg, hp, data = mtcars, size = I(2))
# or with ggplot() + geom_point()
ggplot(mtcars, aes(mpg, hp), size = 2) + geom_point()
# or another solution:
ggplot(mtcars, aes(mpg, hp)) + geom_point(size = 2)
When you try to update a text field value or adding a subview inside a background thread, you can get this problem. For that reason, you should put this kind of code in the main thread.
You need to wrap methods that call UI updates with dispatch_asynch to get the main queue. For example:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.friendLabel.text = "You are following \(friendCount) accounts"
})
Now, we can do that following the next code:
// Move to a background thread to do some long running work
DispatchQueue.global(qos: .userInitiated).async {
// Do long running task here
// Bounce back to the main thread to update the UI
DispatchQueue.main.async {
self.friendLabel.text = "You are following \(friendCount) accounts"
}
}
lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)
It will print as following:
[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]
Have a look at json_encode
(http://php.net/manual/en/function.json-encode.php). It is available as of PHP 5.2. Use the parameter dataType: 'json'
to have it parsed for you. You'll have the Object as the first argument in success then. For further information have a look at the jQuery-documentation: http://api.jquery.com/jQuery.ajax/
To align a text use the following:
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
e.Graphics.DrawString("My String", this.Font, Brushes.Black, ClientRectangle, sf);
Please note that the text here is aligned in the given bounds. In this sample this is the ClientRectangle.
Here's how you can POST XML on Windows using curl command line on Windows. Better use batch/.cmd file for that:
curl -i -X POST -H "Content-Type: text/xml" -d ^
"^<?xml version=\"1.0\" encoding=\"UTF-8\" ?^> ^
^<Transaction^> ^
^<SomeParam1^>Some-Param-01^</SomeParam1^> ^
^<Password^>SomePassW0rd^</Password^> ^
^<Transaction_Type^>00^</Transaction_Type^> ^
^<CardHoldersName^>John Smith^</CardHoldersName^> ^
^<DollarAmount^>9.97^</DollarAmount^> ^
^<Card_Number^>4111111111111111^</Card_Number^> ^
^<Expiry_Date^>1118^</Expiry_Date^> ^
^<VerificationStr2^>123^</VerificationStr2^> ^
^<CVD_Presence_Ind^>1^</CVD_Presence_Ind^> ^
^<Reference_No^>Some Reference Text^</Reference_No^> ^
^<Client_Email^>[email protected]^</Client_Email^> ^
^<Client_IP^>123.4.56.7^</Client_IP^> ^
^<Tax1Amount^>^</Tax1Amount^> ^
^<Tax2Amount^>^</Tax2Amount^> ^
^</Transaction^> ^
" "http://localhost:8080"
you can apply two commands
git diff --patch > mypatch.patch // to generate the patch
git apply mypatch.patch // to apply the patch
If you are using Android Studio 3.2 & above,then issue will be solved by adding google() & jcenter() to build.gradle of the project:
repositories {
google()
jcenter()
}
Please try below code :
public T? GetParsedOrDefaultValue<T>(string valueToParse) where T : struct, IComparable
{
if(string.EmptyOrNull(valueToParse))return null;
try
{
// return parsed value
return (T) Convert.ChangeType(valueToParse, typeof(T));
}
catch(Exception)
{
//default as null value
return null;
}
return null;
}
There's no need for hacks or overflow. There's a pseudo-element for the dropdown arrow on IE:
select::-ms-expand {
display: none;
}
A nice way to create buckets is the LOOKUP() function.
In this example contains cell A1 is a count of days. The vthe second parameter is a list of values. The third parameter is the list of bucket names.
=LOOKUP(A1,{0,7,14,31,90,180,360},{"0-6","7-13","14-30","31-89","90-179","180-359",">360"})
Try passing the password for the key and store as part of the command
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -keypass android -storepass android \
| openssl sha1 -binary \
| openssl base64
Just as another alternative you could use HASHBYTES, something like this:
SELECT *
FROM a_table
WHERE HASHBYTES('sha1', attribute) = HASHBYTES('sha1', 'k')
I tried using <div class="control-group">
and it did not change my layout. It did not add vertical space. The solution that worked for me was:
<ol style="visibility:hidden;"></ol>
If that doesn't give you enough vertical space, you can incrementally get more by adding nested <li> </li>
tags.
Below code worked for me
$today_start = Carbon::now()->format('Y-m-d 00:00:00');
$today_end = Carbon::now()->format('Y-m-d 23:59:59');
$start_activity = MarketingActivity::whereBetween('created_at', [$today_start, $today_end])
->orderBy('id', 'ASC')->limit(1)->get();
I wondered if it would be possible to avoid some of the disadvantages of using global variables (see e.g. http://wiki.c2.com/?GlobalVariablesAreBad) by using a class namespace rather than a global/module namespace to pass values of variables. The following code indicates that the two methods are essentially identical. There is a slight advantage in using class namespaces as explained below.
The following code fragments also show that attributes or variables may be dynamically created and deleted in both global/module namespaces and class namespaces.
wall.py
# Note no definition of global variables
class router:
""" Empty class """
I call this module 'wall' since it is used to bounce variables off of. It will act as a space to temporarily define global variables and class-wide attributes of the empty class 'router'.
source.py
import wall
def sourcefn():
msg = 'Hello world!'
wall.msg = msg
wall.router.msg = msg
This module imports wall and defines a single function sourcefn
which defines a message and emits it by two different mechanisms, one via globals and one via the router function. Note that the variables wall.msg
and wall.router.message
are defined here for the first time in their respective namespaces.
dest.py
import wall
def destfn():
if hasattr(wall, 'msg'):
print 'global: ' + wall.msg
del wall.msg
else:
print 'global: ' + 'no message'
if hasattr(wall.router, 'msg'):
print 'router: ' + wall.router.msg
del wall.router.msg
else:
print 'router: ' + 'no message'
This module defines a function destfn
which uses the two different mechanisms to receive the messages emitted by source. It allows for the possibility that the variable 'msg' may not exist. destfn
also deletes the variables once they have been displayed.
main.py
import source, dest
source.sourcefn()
dest.destfn() # variables deleted after this call
dest.destfn()
This module calls the previously defined functions in sequence. After the first call to dest.destfn
the variables wall.msg
and wall.router.msg
no longer exist.
The output from the program is:
global: Hello world!
router: Hello world!
global: no message
router: no message
The above code fragments show that the module/global and the class/class variable mechanisms are essentially identical.
If a lot of variables are to be shared, namespace pollution can be managed either by using several wall-type modules, e.g. wall1, wall2 etc. or by defining several router-type classes in a single file. The latter is slightly tidier, so perhaps represents a marginal advantage for use of the class-variable mechanism.
Late contribution but just came across something similar in Python datetime and pandas give different timestamps for the same date.
If you have timezone-aware datetime in pandas
, technically, tz_localize(None)
changes the POSIX timestamp (that is used internally) as if the local time from the timestamp was UTC. Local in this context means local in the specified timezone. Ex:
import pandas as pd
t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="US/Central")
# DatetimeIndex(['2013-05-18 12:00:00-05:00', '2013-05-18 13:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H')
t_loc = t.tz_localize(None)
# DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')
# offset in seconds according to timezone:
(t_loc.values-t.values)//1e9
# array([-18000, -18000], dtype='timedelta64[ns]')
Note that this will leave you with strange things during DST transitions, e.g.
t = pd.date_range(start="2020-03-08 01:00:00", periods=2, freq='H', tz="US/Central")
(t.values[1]-t.values[0])//1e9
# numpy.timedelta64(3600,'ns')
t_loc = t.tz_localize(None)
(t_loc.values[1]-t_loc.values[0])//1e9
# numpy.timedelta64(7200,'ns')
In contrast, tz_convert(None)
does not modify the internal timestamp, it just removes the tzinfo
.
t_utc = t.tz_convert(None)
(t_utc.values-t.values)//1e9
# array([0, 0], dtype='timedelta64[ns]')
My bottom line would be: stick with timezone-aware datetime if you can or only use t.tz_convert(None)
which doesn't modify the underlying POSIX timestamp. Just keep in mind that you're practically working with UTC then.
(Python 3.8.2 x64 on Windows 10, pandas
v1.0.5.)
On a 64-bit system you have to make sure that both the Tomcat application and the JDK are the same architecture: either both are x86 or x64.
In case you want to change the Tomcat instance to x64 you might have to download the tomcat8.exe
or tomcat9.exe
and the tcnative-1.dll
with the appropriate x64 versions. You can get those at http://svn.apache.org/viewvc/tomcat/.
Alternatively you can point Tomcat to the x86 JDK by changing the Java Virtual Machine path in the Tomcat config.
Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.
ES6 / Arrow functions version based on Francis' code (i.e. the top answer):
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
I've been using IE Tester (good) but didn't know I could simply switch versions in IE. It's nice to know the browser voted "Most likely to be the bain of your existence" has the tool built in to look at previous versions.
The down side to IE Tester is it does not support javascript well, and also doesn't always do a great job with iframes. (Yes, I still use them.)
I decided that since Google and Facebook no longer support IE7, I won't either. I have a lot less funding than they do.
I know this doesn't fix the need to use VM for MAC users, but there should be ways around that too. With an 8 core processor PC computer, you can VM MAC with 4 cores, same for PC, and run 4 displays, two for each OS. Expensive, but this is our business. In most business models, it is not uncommon to spend tens of thousands of dollars on equipment. We shouldn't think of ourselves any differently. Invest in your success.
For Rails 5, you should enable the follow config code:
config.public_file_server.enabled = true
By default, Rails 5 ships with this line of config:
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
Hence, you will need to set the environment variable RAILS_SERVE_STATIC_FILES
to true.
One can also do this with pylab and xticks
import matplotlib
import matplotlib.pyplot as plt
x = [0,1,2]
y = [90,40,65]
labels = ['high', 'low', 37337]
plt.plot(x,y, 'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()
http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html
As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class
to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession()
.
SessionFactory.openSession()
always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession()
returns a session bound to a context - you don't need to close this.
If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.
You should never use one session per web app
- session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"
ALTER TABLE <tablename> CHANGE COLUMN <colname> <colname> VARCHAR(65536);
You have to list the column name twice, even if you aren't changing its name.
Note that after you make this change, the data type of the column will be MEDIUMTEXT
.
Miky D is correct, the MODIFY
command can do this more concisely.
Re the MEDIUMTEXT
thing: a MySQL row can be only 65535 bytes (not counting BLOB/TEXT columns). If you try to change a column to be too large, making the total size of the row 65536 or greater, you may get an error. If you try to declare a column of VARCHAR(65536)
then it's too large even if it's the only column in that table, so MySQL automatically converts it to a MEDIUMTEXT
data type.
mysql> create table foo (str varchar(300));
mysql> alter table foo modify str varchar(65536);
mysql> show create table foo;
CREATE TABLE `foo` (
`str` mediumtext
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
I misread your original question, you want VARCHAR(65353)
, which MySQL can do, as long as that column size summed with the other columns in the table doesn't exceed 65535.
mysql> create table foo (str1 varchar(300), str2 varchar(300));
mysql> alter table foo modify str2 varchar(65353);
ERROR 1118 (42000): Row size too large.
The maximum row size for the used table type, not counting BLOBs, is 65535.
You have to change some columns to TEXT or BLOBs
When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.
Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.
If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.
Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.
If you have any function associated to list ,when you make the splice function, the association is deleted too. My solution:
$scope.remove = function() {
var oldList = $scope.items;
$scope.items = [];
angular.forEach(oldList, function(x) {
if (! x.done) $scope.items.push( { [ DATA OF EACH ITEM USING oldList(x) ] });
});
};
The list param is named items. The param x.done indicate if the item will be deleted. Hope help you. Greetings.
Make sure that the string is in the following JSON format which is something like this:
{"result":"success","testid":"1"} (with " ") .
If not, then you can add "responsetype => json"
in your request params.
Then use json_decode($response,true)
to convert it into an array.
I always use :
if (row["value"] != DBNull.Value)
someObject.Member = row["value"];
Found it short and comprehensive.
If you have apache running, put your file in server folder for html files and then call it from web-browser (Like http://localhost/myfile.php ).
Install psacct
or acct
package. Then use the sa
command to display CPU time used for various commands. sa man page
A nice howto from the nixCraft site.
The biggest disadvantage of Text
(together with NText
and Image
) is that it will be removed in a future version of SQL Server, as by the documentation. That will effectively make your schema harder to upgrade when that version of SQL Server will be released.
According to XMLHttpRequest, it's not valid. From the standard:
4.5.6 The
send()
methodclient . send([body = null])
Initiates the request. The optional argument provides the request body. The argument is ignored if request method is
GET
orHEAD
.Throws an
InvalidStateError
exception if either state is not opened or thesend()
flag is set.The
send(body)
method must run these steps:
- If state is not opened, throw an
InvalidStateError
exception.- If the
send()
flag is set, throw anInvalidStateError
exception.- If the request method is
GET
orHEAD
, set body to null.- If body is null, go to the next step.
Although, I don't think it should because GET request might need big body content.
So, if you rely on XMLHttpRequest of a browser, it's likely it won't work.
This approach can be used to automate this (the following exemplary solution is in python, although obviously it can be ported to any language):
you can strip the whitespace beforehand AND save the positions of non-whitespace characters so you can use them later to find out the matched string boundary positions in the original string like the following:
def regex_search_ignore_space(regex, string):
no_spaces = ''
char_positions = []
for pos, char in enumerate(string):
if re.match(r'\S', char): # upper \S matches non-whitespace chars
no_spaces += char
char_positions.append(pos)
match = re.search(regex, no_spaces)
if not match:
return match
# match.start() and match.end() are indices of start and end
# of the found string in the spaceless string
# (as we have searched in it).
start = char_positions[match.start()] # in the original string
end = char_positions[match.end()] # in the original string
matched_string = string[start:end] # see
# the match WITH spaces is returned.
return matched_string
with_spaces = 'a li on and a cat'
print(regex_search_ignore_space('lion', with_spaces))
# prints 'li on'
If you want to go further you can construct the match object and return it instead, so the use of this helper will be more handy.
And the performance of this function can of course also be optimized, this example is just to show the path to a solution.
Listen to the change event.
input.onchange = function(e) {
..
};
Query plans can be obtained from an Extended Events session via the query_post_execution_showplan
event. Here's a sample XEvent session:
/*
Generated via "Query Detail Tracking" template.
*/
CREATE EVENT SESSION [GetExecutionPlan] ON SERVER
ADD EVENT sqlserver.query_post_execution_showplan(
ACTION(package0.event_sequence,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)),
/* Remove any of the following events (or include additional events) as desired. */
ADD EVENT sqlserver.error_reported(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.module_end(SET collect_statement=(1)
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.rpc_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sp_statement_completed(SET collect_object_name=(1)
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sql_batch_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sql_statement_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0))))
ADD TARGET package0.ring_buffer
WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=ON,STARTUP_STATE=OFF)
GO
After you create the session, (in SSMS) go to the Object Explorer and delve down into Management | Extended Events | Sessions. Right-click the "GetExecutionPlan" session and start it. Right-click it again and select "Watch Live Data".
Next, open a new query window and run one or more queries. Here's one for AdventureWorks:
USE AdventureWorks;
GO
SELECT p.Name AS ProductName,
NonDiscountSales = (OrderQty * UnitPrice),
Discounts = ((OrderQty * UnitPrice) * UnitPriceDiscount)
FROM Production.Product AS p
INNER JOIN Sales.SalesOrderDetail AS sod
ON p.ProductID = sod.ProductID
ORDER BY ProductName DESC;
GO
After a moment or two, you should see some results in the "GetExecutionPlan: Live Data" tab. Click one of the query_post_execution_showplan events in the grid, and then click the "Query Plan" tab below the grid. It should look similar to this:
EDIT: The XEvent code and the screen shot were generated from SQL/SSMS 2012 w/ SP2. If you're using SQL 2008/R2, you might be able to tweak the script to make it run. But that version doesn't have a GUI, so you'd have to extract the showplan XML, save it as a *.sqlplan file and open it in SSMS. That's cumbersome. XEvents didn't exist in SQL 2005 or earlier. So, if you're not on SQL 2012 or later, I'd strongly suggest one of the other answers posted here.
Use set.update()
or |=
>>> a = set('abc')
>>> l = ['d', 'e']
>>> a.update(l)
>>> a
{'e', 'b', 'c', 'd', 'a'}
>>> l = ['f', 'g']
>>> a |= set(l)
>>> a
{'e', 'b', 'f', 'c', 'd', 'g', 'a'}
edit: If you want to add the list itself and not its members, then you must use a tuple, unfortunately. Set members must be hashable.
No need to find
. If you are just looking for a pattern within a specific directory, this should suffice:
grep -hn FOO /your/path/*.bar
Where -h
is the parameter to hide the filename, as from man grep
:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.
Note that you were using
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
The fastest way should be:
<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
if (entry.getKey().startsWith("question")) {
String[] values = entry.getValue();
// etc.
Note that you can't do:
for (Map.Entry<String, String[]> entry :
request.getParameterMap().entrySet()) { // WRONG!
for reasons explained here.
This is another modification of Tim Goldan's script that runs on unix types and adds a simple watcher for file modification by using a dict (file=>time).
usage: whateverName.py path_to_dir_to_watch
#!/usr/bin/env python
import os, sys, time
def files_to_timestamp(path):
files = [os.path.join(path, f) for f in os.listdir(path)]
return dict ([(f, os.path.getmtime(f)) for f in files])
if __name__ == "__main__":
path_to_watch = sys.argv[1]
print('Watching {}..'.format(path_to_watch))
before = files_to_timestamp(path_to_watch)
while 1:
time.sleep (2)
after = files_to_timestamp(path_to_watch)
added = [f for f in after.keys() if not f in before.keys()]
removed = [f for f in before.keys() if not f in after.keys()]
modified = []
for f in before.keys():
if not f in removed:
if os.path.getmtime(f) != before.get(f):
modified.append(f)
if added: print('Added: {}'.format(', '.join(added)))
if removed: print('Removed: {}'.format(', '.join(removed)))
if modified: print('Modified: {}'.format(', '.join(modified)))
before = after
The best solution:-
angular.module("myapp").controller("frstCtrl",function($scope){
$scope.name="Atul Singh";
})
.controller("secondCtrl",function($scope){
angular.extend(this, $controller('frstCtrl', {$scope:$scope}));
console.log($scope);
})
// Here you got the first controller call without executing it
AD registers Service Location (SRV) resource records in its DNS server which you can query to get the port and the hostname of the responsible LDAP server in your domain.
Just try this on the command-line:
C:\> nslookup
> set types=all
> _ldap._tcp.<<your.AD.domain>>
_ldap._tcp.<<your.AD.domain>> SRV service location:
priority = 0
weight = 100
port = 389
svr hostname = <<ldap.hostname>>.<<your.AD.domain>>
(provided that your nameserver is the AD nameserver which should be the case for the AD to function properly)
Please see Active Directory SRV Records and Windows 2000 DNS white paper for more information.
Assuming you stick to the rules and only produce enums with numeric values, you can use this code. This correctly handles the case where you have a name that is coincidentally a valid number
enum Color {
Red,
Green,
Blue,
"10" // wat
}
var names: string[] = [];
for(var n in Color) {
if(typeof Color[n] === 'number') names.push(n);
}
console.log(names); // ['Red', 'Green', 'Blue', '10']
site-packages is just the location where Python installs its modules.
No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).
Programmatically you can find it this way:
import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages
'/Users/foo/.envs/env1/lib/python2.7/site-packages'
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
Here is the source of these column flags
http://dev.mysql.com/doc/workbench/en/wb-table-editor-columns-tab.html
The reason is that your rule
%.o: %.cpp
...
expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.
You can use VPATH to resolve this:
VPATH = src/widgets
BUILDDIR = build/widgets
$(BUILDDIR)/%.o: %.cpp
...
When attempting to build "build/widgets/apple.o", make will search for apple.cpp in VPATH. Note that the build rule has to use special variables in order to access the actual filename make finds:
$(BUILDDIR)/%.o: %.cpp
$(CC) $< -o $@
Where "$<" expands to the path where make located the first dependency.
Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like
build/widgets/%.o: %.cpp
....
build/ui/%.o: %.cpp
....
build/tests/%.o: %.cpp
....
I would recommend that you use "canned command sequences" in order to avoid repeating the actual compiler build rule:
define cc-command
$(CC) $(CFLAGS) $< -o $@
endef
You can then have multiple rules like this:
build1/foo.o build1/bar.o: %.o: %.cpp
$(cc-command)
build2/frotz.o build2/fie.o: %.o: %.cpp
$(cc-command)
I have solved the same issue by giving the read permision from github account.
I think because of the below code you are not getting new credential
string fullName = Request.ServerVariables["LOGON_USER"];
You can try custom login page.
use jQuery's $.getJSON
$.getJSON('mydata.json', function(data) {
//do stuff with your data here
});
Here is a function that I use for looping over an array:
function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){
if (i < theArray.length && typeof delayAmount == 'number'){
console.log("i "+i);
theFunction(theArray[i], i);
setTimeout(function(){
loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
}else{
onComplete(i);
}
}
You use it like this:
loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
//Do something with item
}, function(i){
//Do something once loop has completed
}
You can detect text by finding close edge elements (inspired from a LPD):
#include "opencv2/opencv.hpp"
std::vector<cv::Rect> detectLetters(cv::Mat img)
{
std::vector<cv::Rect> boundRect;
cv::Mat img_gray, img_sobel, img_threshold, element;
cvtColor(img, img_gray, CV_BGR2GRAY);
cv::Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
cv::threshold(img_sobel, img_threshold, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY);
element = getStructuringElement(cv::MORPH_RECT, cv::Size(17, 3) );
cv::morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element); //Does the trick
std::vector< std::vector< cv::Point> > contours;
cv::findContours(img_threshold, contours, 0, 1);
std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
for( int i = 0; i < contours.size(); i++ )
if (contours[i].size()>100)
{
cv::approxPolyDP( cv::Mat(contours[i]), contours_poly[i], 3, true );
cv::Rect appRect( boundingRect( cv::Mat(contours_poly[i]) ));
if (appRect.width>appRect.height)
boundRect.push_back(appRect);
}
return boundRect;
}
Usage:
int main(int argc,char** argv)
{
//Read
cv::Mat img1=cv::imread("side_1.jpg");
cv::Mat img2=cv::imread("side_2.jpg");
//Detect
std::vector<cv::Rect> letterBBoxes1=detectLetters(img1);
std::vector<cv::Rect> letterBBoxes2=detectLetters(img2);
//Display
for(int i=0; i< letterBBoxes1.size(); i++)
cv::rectangle(img1,letterBBoxes1[i],cv::Scalar(0,255,0),3,8,0);
cv::imwrite( "imgOut1.jpg", img1);
for(int i=0; i< letterBBoxes2.size(); i++)
cv::rectangle(img2,letterBBoxes2[i],cv::Scalar(0,255,0),3,8,0);
cv::imwrite( "imgOut2.jpg", img2);
return 0;
}
Results:
a. element = getStructuringElement(cv::MORPH_RECT, cv::Size(17, 3) );
b. element = getStructuringElement(cv::MORPH_RECT, cv::Size(30, 30) );
Results are similar for the other image mentioned.
based on other answers here I'd like to share my one-liners that should work for dirs and files:
Len(Dir(path)) > 0 or Or Len(Dir(path, vbDirectory)) > 0 'version 1 - ... <> "" should be more inefficient generally
Len(Dir(path))
did not work for directories (Excel 2010 / Win7))CreateObject("Scripting.FileSystemObject").FileExists(path) 'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)
as PathExists(path)
function:
Public Function PathExists(path As String) As Boolean
PathExists = Len(Dir(path)) > 0 Or Len(Dir(path, vbDirectory)) > 0
End Function
Using either a float or a double value in a C expression will result in a value that is a double anyway, so printf can't tell the difference. Whereas a pointer to a double has to be explicitly signalled to scanf as distinct from a pointer to float, because what the pointer points to is what matters.
The answer by waqas716 is good. I created a workaround for a specific case demanding less code and maintenance.
I found a specific work around by having a static method fetch a view from the activity I suspect to be in the foreground. You can iterate through all activities and check if you wish or get the activity name from martin's answer
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
I then check if the view is not null and get the context via getContext().
View v = SuspectedActivity.get_view();
if(v != null)
{
// an example for using this context for something not
// permissible in global application context.
v.getContext().startActivity(new Intent("rubberduck.com.activities.SomeOtherActivity"));
}
This is so simple:
Create a drawable file with a gradient like this:
for shadow below a view below_shadow.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#20000000"
android:endColor="@android:color/transparent"
android:angle="270" >
</gradient>
</shape>
for shadow above a view above_shadow.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#20000000"
android:endColor="@android:color/transparent"
android:angle="90" >
</gradient>
</shape>
and so on for right and left shadow just change the angle of the gradient :)
For %F In ("C:\From\*.*") Do If Not Exist "C:\To\%~nxF" Copy "%F" "C:\To\%~nxF"
They need to be percent-encoded:
> encodeURIComponent('&')
"%26"
So in your case, the URL would look like:
http://www.mysite.com?candy_name=M%26M
How about something like
CREATE TABLE testRequest (
wardNo nchar(5),
BHTNo nchar(5),
testID nchar(5),
reqDateTime datetime,
PRIMARY KEY (wardNo, BHTNo, testID)
);
Have a look at this example
There is a potentially more powerful strategy based on the fact that grep() will return a numeric vector. If you have a long list of variables as I do in one of my dataset, some variables that end in ".A" and others that end in ".B" and you only want the ones that end in ".A" (along with all the variables that don't match either pattern, do this:
dfrm2 <- dfrm[ , -grep("\\.B$", names(dfrm)) ]
For the case at hand, using Joris Meys example, it might not be as compact, but it would be:
DF <- DF[, -grep( paste("^",drops,"$", sep="", collapse="|"), names(DF) )]
i just reinstalled the pip and it works, but I still wanna know why it happened...
i used the apt-get remove --purge python-pip
after I just apt-get install pyhton-pip
and it works, but don't ask me why...
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
ES6 based code:
let handleMousemove = (event) => {
console.log(`mouse position: ${event.x}:${event.y}`);
};
document.addEventListener('mousemove', handleMousemove);
If you need throttling for mousemoving, use this:
let handleMousemove = (event) => {
console.warn(`${event.x}:${event.y}\n`);
};
let throttle = (func, delay) => {
let prev = Date.now() - delay;
return (...args) => {
let current = Date.now();
if (current - prev >= delay) {
prev = current;
func.apply(null, args);
}
}
};
// let's handle mousemoving every 500ms only
document.addEventListener('mousemove', throttle(handleMousemove, 500));
here is example
strip
removes the whitespace from the beginning and end of the string. If you want the whitespace, don't call strip.
The use of line system("PAUSE")
will fix that problem and also include the pre processor directory #include<stdlib.h>
.
With deferred
(another promise/deferred implementation) you can do:
// Setup 'pdrop', promise version of 'drop' method
var deferred = require('deferred');
mongoose.Collection.prototype.pdrop =
deferred.promisify(mongoose.Collection.prototype.drop);
// Drop collections:
deferred.map(['aaa','bbb','ccc'], function(name){
return conn.collection(name).pdrop()(function () {
console.log("dropped");
});
}).end(function () {
console.log("all dropped");
}, null);
mysql_
functions have been removed from PHP 7. You can now use MySQLi or PDO.
MySQLi example:
mysqli_connect($mysql_hostname, $mysql_username, $mysql_password, $mysql_dbname);
The best method is given in the docs
$('#myModal').on('shown.bs.modal', function () {
// will only come inside after the modal is shown
});
for more info refer http://getbootstrap.com/javascript/#modals
In your specific case,
String cardString = "";
for (PlayingCard c : this.list) // <--
{
cardString = cardString + c + "\n";
}
this.list
is a collection (list, set, or array), and that code assigns c
to each element of the collection.
So, if this.list
were a collection {"2S", "3H", "4S"} then the cardString
on the end would be this string:
2S
3H
4S
I needed to add a ParsePosition
expression to the parse method of class SimpleDateFormat
:
simpledateformat.parse(mydatestring, new ParsePosition(0));
On Ubuntu 12.04 (Precise Pangolin), I got this working with the following command:
sudo apt-get install ruby1.9.1
sudo apt-get install ruby1.9.3
The solution to my problem today was slightly different that the other answers here.
In my case, the problem was caused by a missing close bracket (}
) at the end of one of the header files in the include chain.
Essentially, what was happening was that A
was including B
. Because B
was missing a }
somewhere in the file, the definitions in B
were not correctly found in A
.
At first I thought I have circular dependency and added the forward declaration B
. But then it started complaining about the fact that something in B
was an incomplete type. That's how I thought of double checking the files for syntax errors.