If you simply need to check whether the variable is of type X, or that it conforms to some protocol, then you can use is
, or as?
as in the following:
var unknownTypeVariable = …
if unknownTypeVariable is <ClassName> {
//the variable is of type <ClassName>
} else {
//variable is not of type <ClassName>
}
This is equivalent of isKindOfClass
in Obj-C.
And this is equivalent of conformsToProtocol
, or isMemberOfClass
var unknownTypeVariable = …
if let myClass = unknownTypeVariable as? <ClassName or ProtocolName> {
//unknownTypeVarible is of type <ClassName or ProtocolName>
} else {
//unknownTypeVariable is not of type <ClassName or ProtocolName>
}
Yes. You can use Process.Start
to launch an executable, including a console application.
If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.
What about just assigning a class to your widget and then binding that class to the JQuery datepicker?
Django forms.py:
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_date_field'].widget.attrs['class'] = 'datepicker'
And some JavaScript for the template:
$(".datepicker").datepicker();
Use this syntax:
CREATE TEMPORARY TABLE t1 (select * from t2);
imagecopyresampled()
will take a rectangular area from $src_image
of width $src_w
and height $src_h
at position ($src_x, $src_y)
and place it in a rectangular area of $dst_image
of width $dst_w
and height $dst_h
at position ($dst_x, $dst_y)
.
If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner.
This function can be used to copy regions within the same image. But if the regions overlap, the results will be unpredictable.
If $src_w
and $src_h
are smaller than $dst_w
and $dst_h
respectively, thumb image will be zoomed in. Otherwise it will be zoomed out.
<?php
$dst_x = 0; // X-coordinate of destination point
$dst_y = 0; // Y-coordinate of destination point
$src_x = 100; // Crop Start X position in original image
$src_y = 100; // Crop Srart Y position in original image
$dst_w = 160; // Thumb width
$dst_h = 120; // Thumb height
$src_w = 260; // Crop end X position in original image
$src_h = 220; // Crop end Y position in original image
// Creating an image with true colors having thumb dimensions (to merge with the original image)
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
// Get original image
$src_image = imagecreatefromjpeg('images/source.jpg');
// Cropping
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
// Saving
imagejpeg($dst_image, 'images/crop.jpg');
?>
When using buildout I have following in .gitignore
(along with *.pyo
and *.pyc
):
.installed.cfg
bin
develop-eggs
dist
downloads
eggs
parts
src/*.egg-info
lib
lib64
Thanks to Jacob Kaplan-Moss
Also I tend to put .svn
in since we use several SCM-s where I work.
If you know what class the field is on you can access it using reflection. This example (it's in Groovy but the method calls are identical) gets a Field object for the class Foo and gets its value for the object b
. It shows that you don't have to care about the exact concrete class of the object, what matters is that you know the class the field is on and that that class is either the concrete class or a superclass of the object.
groovy:000> class Foo { def stuff = "asdf"}
===> true
groovy:000> class Bar extends Foo {}
===> true
groovy:000> b = new Bar()
===> Bar@1f2be27
groovy:000> f = Foo.class.getDeclaredField('stuff')
===> private java.lang.Object Foo.stuff
groovy:000> f.getClass()
===> class java.lang.reflect.Field
groovy:000> f.setAccessible(true)
===> null
groovy:000> f.get(b)
===> asdf
Can I just ask about the long term need for this facility - is it for debuging purposes?
If so, then you may want to consider using a proper debugger, such as the one found in Visual Studio, as this allows you to step through the procedure in a more controlled way, and avoids having to constantly add/remove PRINT statement from the procedure.
Just my opinion, but I prefer the debugger approach - for code and databases.
You can't control the timeout due to UnknownHostException
. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.
But I find it hard to believe that you are really getting an UnknownHostException
when you specify an IP address rather than a hostname.
EDIT To control Java's DNS timeouts see this answer.
just delete this part Class.forName("com.mysql.jdbc.Driver")
from your code
because the machine is throwing a warning that
The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary."
meaning that no need to include it beacuse the driver is automatically registered for you by default.
Update with .NET 4.6.2. Check Release value in the same registry as in previous responses:
RegistryKey registry_key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full");
if (registry_key == null)
return false;
var val = registry_key.GetValue("Release", 0);
UInt32 Release = Convert.ToUInt32(val);
if (Release >= 394806) // 4.6.2 installed on all other Windows (different than Windows 10)
return true;
if (Release >= 394802) // 4.6.2 installed on Windows 10 or later
return true;
This code sums both the variables! Put it into your function
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = (y +z);
document.getElementById("demo").innerHTML = x;`
Use the continue
keyword. Read here.
The continue statement skips the current iteration of a for, while , or do-while loop.
The best solution is to refactor to your promise chain to use ES6 await's. Then you can just return from the function to skip the rest of the behavior.
I have been hitting my head against this pattern for over a year and using await's is heaven.
To hide warnings, you can also do
{r, warning=FALSE}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ChnagePassword.aspx/AutocompleteSuggestions",
data: "{'searchstring':'" + request.term + "','st':'Arb'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return { value: item }
}))
},
error: function (result) {
alert("Error");
}
});
To convert List<T> list
to observable collection you may use following code:
var oc = new ObservableCollection<T>();
list.ForEach(x => oc.Add(x));
You can select your desired columns and do it by assignment:
df[['a', 'b']] = df[['a','b']].fillna(value=0)
The resulting output is as expected:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0
You can use this code  
to add a space in the HTML content. For tab space, use it 5 times or more.
Check an example here: https://www.w3schools.com/charsets/tryit.asp?deci=8287&ent=ThickSpace
main you can do :
String mainTab = page.goToNewTab ();
//do what you want
page.backToMainPage(mainTab);
What you need to have in order to use the main
private static Set<String> windows;
//get all open windows
//return current window
public String initWindows() {
windows = new HashSet<String>();
driver.getWindowHandles().stream().forEach(n -> windows.add(n));
return driver.getWindowHandle();
}
public String getNewWindow() {
List<String> newWindow = driver.getWindowHandles().stream().filter(n -> windows.contains(n) == false)
.collect(Collectors.toList());
logger.info(newWindow.get(0));
return newWindow.get(0);
}
public String goToNewTab() {
String startWindow = driver.initWindows();
driver.findElement(By.cssSelector("XX")).click();
String newWindow = driver.getNewWindow();
driver.switchTo().window(newWindow);
return startWindow;
}
public void backToMainPage(String startWindow) {
driver.close();
driver.switchTo().window(startWindow);
}
U can use something like this....
function (field,value) {
var newItemOrder= value;
// Make sure user hasnt already added this item
angular.forEach(arr, function(item) {
if (newItemOrder == item.value) {
arr.splice(arr.pop(item));
} });
submitFields.push({"field":field,"value":value});
};
perl -pe 's/\..*$//;s{^.*/}{}'
For the specific case in the question, easiest way would be to add all files with .c extension and leave out everything else:
git add *.c
From git-scm (or/and man git add
):
git add <pathspec>…?
Files to add content from. Fileglobs (e.g. *.c) can be given to add all matching files. <...>
Note that this means that you could also do something like:
git add **/main/*
to add all files (that are not ignored) that are in the main
folder. You can even go wild with more elaborate patterns:
git add **/s?c/*Service*
The above will add all files that are in s(any char)c
folder and have Service
somewhere in their filename.
Obviously, you are not limited to one pattern per command. That is, you could ask git to add all files that have an extension of .c and .h:
git add *.c *.h
This link might give you some more glob pattern ideas.
I find it particularly useful when I'm making many changes, but still want my commits to stay atomic and reflect gradual process rather than a hodgepodge of changes I may be working at the time. Of course, at some point the cost of coming up with elaborate patterns outweighs the cost of adding files with simpler methods, or even one file at a time. However, most of the time I'm easily able to pinpoint just the files I need with a simple pattern, and exclude everything else.
By the way, you may need to quote your glob patterns for them to work, but this was never the case for me.
There is no way to delete or read the past history.
You could try going around it by emulating history in your own memory and calling history.pushState
everytime window popstate
event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:
So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.
A lot of the middleware was pulled out of the Express core in v4, and put into separate modules. The basic auth module is here: https://github.com/expressjs/basic-auth-connect
Your example would just need to change to this:
var basicAuth = require('basic-auth-connect');
app.use(basicAuth('username', 'password'));
/proc/net/tcp -a list of open tcp sockets
/proc/net/udp -a list of open udp sockets
/proc/net/raw -a list all the 'raw' sockets
These are the files, use cat
command to view them. For example:
cat /proc/net/tcp
You can also use the lsof
command.
lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.
#!/bin/bash
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"
# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"
# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer
or:
I would think that one reason could be that the color is applied to things other than font. For example:
div {
border: 1px solid;
color: red;
}
Yields both a red font color and a red border.
Alternatively, it could just be that the W3C's CSS standards are completely backwards and nonsensical as evidenced elsewhere.
You can just do this:
const char *text = "This is my string it is "
"very long";
I ended up with the following:
set input=AAA BBB CCC DDD EEE FFF
set nth=4
for /F "tokens=%nth% delims= " %%a in ("%input%") do set nthstring=%%a
echo %nthstring%
With this you can parameterize the input and index. Make sure to put this code in a bat file.
if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(hrefLink.Replace("/", "\\"));
}
THis assumes, of course, that you've parsed out the file name.
EDIT #2:
using System.IO;
private String GetFileName(String hrefLink)
{
return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\\"));
}
This should handle spaces and the like in the file name.
you can try checking out your fields as you are rendering email field which is not available in your ajax
$.ajax({_x000D_
url: "url",_x000D_
type: 'GET',_x000D_
success: function(data) {_x000D_
var new_data = {_x000D_
"data": data_x000D_
};_x000D_
console.log(new_data);_x000D_
}_x000D_
});
_x000D_
This might work for you:
printf "{new\nto\nlinux}" | paste -sd' '
{new to linux}
or:
printf "{new\nto\nlinux}" | tr '\n' ' '
{new to linux}
or:
printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}
Within Crystal, you can do it by creating a formula that uses the ToNumber
function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:
If NumericText ({field}) then ToNumber ({field}) else 0
Alternatively, you might find it easier to convert the field's datatype within the query used in the report.
The solution is very simple, but took me about 2 hours and half the hair on my head to find it.
Simply wrap your content with a (redundant) div
that has display: none
and Bob is your uncle.
<div style="display: none">
<div id="content-div">Some content here</div>
</div>
Voila
Just stumbled upon this and thought I would suggest my solution. I typically like to use the built in functionality of assigning a range to an multi-dim array (I guess it's also the JS Programmer in me).
I frequently write code like this:
Sub arrayBuilder()
myarray = Range("A1:D4")
'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned
For i = 1 To UBound(myarray)
For j = 1 To UBound(myarray, 2)
Debug.Print (myarray(i, j))
Next j
Next i
End Sub
Assigning ranges to variables is a very powerful way to manipulate data in VBA.
#progressbar {_x000D_
background-color: black;_x000D_
border-radius: 13px;_x000D_
/* (height of inner div) / 2 + padding */_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
#progressbar>div {_x000D_
background-color: orange;_x000D_
width: 40%;_x000D_
/* Adjust with JavaScript */_x000D_
height: 20px;_x000D_
border-radius: 10px;_x000D_
}
_x000D_
<div id="progressbar">_x000D_
<div></div>_x000D_
</div>
_x000D_
(EDIT: Changed Syntax highlight; changed descendant to child selector)
The simplest way of installing SBT on ubuntu is the deb
package provided by Typesafe.
Run the following shell commands:
wget http://apt.typesafe.com/repo-deb-build-0002.deb
sudo dpkg -i repo-deb-build-0002.deb
sudo apt-get update
sudo apt-get install sbt
And you're done !
This is what I have done. (Adapt from all of your answers)
<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />
It works. Thanks to all of you. :)
I know this is a pretty old topic, but I also had a same problem.
My solution:
how we fill the combobox:
foreach (KeyValuePair<int, string> item in listRegion)
{
combo.Items.Add(item.Value);
combo.ValueMember = item.Value.ToString();
combo.DisplayMember = item.Key.ToString();
combo.SelectedIndex = 0;
}
and that's how we get inside:
MessageBox.Show(combo_region.DisplayMember.ToString());
I hope it help someone
Sort of. As Bobby says:
svn co file:///.../trunk/foo file:///.../trunk/bar file:///.../trunk/hum
will get the folders, but you will get separate folders from a subversion perspective. You will have to go separate commits and updates on each subfolder.
I don't believe you can checkout a partial tree and then work with the partial tree as a single entity.
You may want to check out the YQL libraries from Yahoo: http://developer.yahoo.com/yql
The task at hand is as simple as
select * from html where url = 'http://stackoverflow.com/questions/ask'
You can try this out in the console at: http://developer.yahoo.com/yql/console (requires login)
Also see Chris Heilmanns screencast for some nice ideas what more you can do: http://developer.yahoo.net/blogs/theater/archives/2009/04/screencast_collating_distributed_information.html
This works in Oracle:
insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual
The thing to remember here is to use the from dual
statement.
The top answer was correct at the time but is now wrong; you can do it in pure javascript. But the one answer using javascript doesn't work any more, and the other answers are pretty limited or don't use pure javascript.
I made my own solution that works well and lets you control the volume, frequency, and wavetype.
//if you have another AudioContext class use that one, as some browsers have a limit
var audioCtx = new (window.AudioContext || window.webkitAudioContext || window.audioContext);
//All arguments are optional:
//duration of the tone in milliseconds. Default is 500
//frequency of the tone in hertz. default is 440
//volume of the tone. Default is 1, off is 0.
//type of tone. Possible values are sine, square, sawtooth, triangle, and custom. Default is sine.
//callback to use on end of tone
function beep(duration, frequency, volume, type, callback) {
var oscillator = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
if (volume){gainNode.gain.value = volume;}
if (frequency){oscillator.frequency.value = frequency;}
if (type){oscillator.type = type;}
if (callback){oscillator.onended = callback;}
oscillator.start(audioCtx.currentTime);
oscillator.stop(audioCtx.currentTime + ((duration || 500) / 1000));
};
Someone suggested I edit this to note it only works on some browsers. However Audiocontext seems to be supported on all modern browsers, as far as I can tell. It isn't supported on IE, but that has been discontinued by Microsoft. If you have any issues with this on a specific browser please report it.
JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.
Well, after long research, i found a workaround that does what i need: http://jsfiddle.net/CqB3d/25/
CSS:
body{
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
height: 100%;
max-height: 100%;
}
#caixa{
width: 800px;
margin-left: auto;
margin-right: auto;
}
#framecontentTop, #framecontentBottom{
position: absolute;
top: 0;
width: 800px;
height: 100px; /*Height of top frame div*/
overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
background-color: navy;
color: white;
}
#framecontentBottom{
top: auto;
bottom: 0;
height: 110px; /*Height of bottom frame div*/
overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
background-color: navy;
color: white;
}
#maincontent{
position: fixed;
top: 100px; /*Set top value to HeightOfTopFrameDiv*/
margin-left:auto;
margin-right: auto;
bottom: 110px; /*Set bottom value to HeightOfBottomFrameDiv*/
overflow: auto;
background: #fff;
width: 800px;
}
.innertube{
margin: 15px; /*Margins for inner DIV inside each DIV (to provide padding)*/
}
* html body{ /*IE6 hack*/
padding: 130px 0 110px 0; /*Set value to (HeightOfTopFrameDiv 0 HeightOfBottomFrameDiv 0)*/
}
* html #maincontent{ /*IE6 hack*/
height: 100%;
width: 800px;
}
HTML:
<div id="framecontentBottom">
<div class="innertube">
<h3>Sample text here</h3>
</div>
</div>
<div id="maincontent">
<div class="innertube">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque, ligula hendrerit euismod auctor, diam nunc sollicitudin nibh, id luctus eros nibh porta tellus. Phasellus sed suscipit dolor. Quisque at mi dolor, eu fermentum turpis. Nunc posuere venenatis est, in sagittis nulla consectetur eget... //much longer text...
</div>
</div>
might not work with the horizontal thingy yet, but, it's a work in progress!
I basically dropped the "inception" boxes-inside-boxes-inside-boxes model and used fixed positioning with dynamic height and overflow properties.
Hope this might help whoever finds the question later!
EDIT: This is the final answer.
You simply annotate a POJO with a special annotation and library does the rest.
Warning!
I'm not sure that Hrisey, Lombok, and other code generation libraries are compatible with Android's new build system. They may or may not play nicely with hot swapping code (i.e. jRebel, Instant Run).
Pros:
Cons:
Warning!
Hrisey has a known issue with Java 8 and therefore cannot be used for Android development nowadays. See #1 Cannot find symbol errors (JDK 8).
Hrisey is based on Lombok. Parcelable class using Hrisey:
@hrisey.Parcelable
public final class POJOClass implements android.os.Parcelable {
/* Fields, accessors, default constructor */
}
Now you don't need to implement any methods of Parcelable interface. Hrisey will generate all required code during preprocessing phase.
Hrisey in Gradle dependencies:
provided "pl.mg6.hrisey:hrisey:${hrisey.version}"
See here for supported types. The ArrayList
is among them.
Install a plugin - Hrisey xor Lombok* - for your IDE and start using its amazing features!
* Don't enable Hrisey and Lombok plugins together or you'll get an error during IDE launch.
Parcelable class using Parceler:
@java.org.parceler.Parcel
public class POJOClass {
/* Fields, accessors, default constructor */
}
To use the generated code, you may reference the generated class directly, or via the Parcels
utility class using
public static <T> Parcelable wrap(T input);
To dereference the @Parcel
, just call the following method of Parcels
class
public static <T> T unwrap(Parcelable input);
Parceler in Gradle dependencies:
compile "org.parceler:parceler-api:${parceler.version}"
provided "org.parceler:parceler:${parceler.version}"
Look in README for supported attribute types.
AutoParcel is an AutoValue extension that enables Parcelable values generation.
Just add implements Parcelable
to your @AutoValue
annotated models:
@AutoValue
abstract class POJOClass implements Parcelable {
/* Note that the class is abstract */
/* Abstract fields, abstract accessors */
static POJOClass create(/*abstract fields*/) {
return new AutoValue_POJOClass(/*abstract fields*/);
}
}
AutoParcel in Gradle build file:
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
repositories {
/*...*/
maven {url "https://clojars.org/repo/"}
}
dependencies {
apt "frankiesardo:auto-parcel:${autoparcel.version}"
}
PaperParcel is an annotation processor that automatically generates type-safe Parcelable boilerplate code for Kotlin and Java. PaperParcel supports Kotlin Data Classes, Google's AutoValue via an AutoValue Extension, or just regular Java bean objects.
Usage example from docs.
Annotate your data class with @PaperParcel
, implement PaperParcelable
, and add a JVM static instance of PaperParcelable.Creator
e.g.:
@PaperParcel
public final class Example extends PaperParcelable {
public static final PaperParcelable.Creator<Example> CREATOR = new PaperParcelable.Creator<>(Example.class);
private final int test;
public Example(int test) {
this.test = test;
}
public int getTest() {
return test;
}
}
For Kotlin users, see Kotlin Usage; For AutoValue users, see AutoValue Usage.
ParcelableGenerator (README is written in Chinese and I don't understand it. Contributions to this answer from english-chinese speaking developers are welcome)
Usage example from README.
import com.baoyz.pg.Parcelable;
@Parcelable
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The android-apt plugin assists in working with annotation processors in combination with Android Studio.
The verbose
configuration option might allow you to see what you want. There is an example in the documentation.
NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.
SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());
Example.
SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE());
Coming here from first Google hit:
You can turn off the behavior AND and warning by exporting GIT_DISCOVERY_ACROSS_FILESYSTEM=1
.
On heroku, if you heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1
the warning will go away.
It's probably because you are building a gem from source and the gemspec shells out to git
, like many do today. So, you'll still get the warning fatal: Not a git repository (or any of the parent directories): .git
but addressing that is for another day :)
My answer is a duplicate of: - comment GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion
Got the same question from a friend. My suggestion which does not require !Important
looks like this: I add a custom class "no-border
" which can be added to the bootstrap table.
.table.no-border tr td, .table.no-border tr th {
border-width: 0;
}
You can see my go at a solution here
TextPad will allow you to perform this operation.
example:
test this sentence
Find what: \([^ ]*\) \(.*\)
Replace with: \U\1\E \2
the \U
will cause all following chars to be upper
the \E
will turn off the \U
the result will be:
TEST this sentence
By default, np.genfromtxt
uses dtype=float
: that's why you string columns are converted to NaNs because, after all, they're Not A Number...
You can ask np.genfromtxt
to try to guess the actual type of your columns by using dtype=None
:
>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.genfromtxt(StringIO(test), delimiter=",", dtype=None)
>>> print a
array([('a',1,2),('b',3,4)], dtype=[('f0', '|S1'),('f1', '<i8'),('f2', '<i8')])
You can access the columns by using their name, like a['f0']
...
Using dtype=None
is a good trick if you don't know what your columns should be. If you already know what type they should have, you can give an explicit dtype
. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then use
>>> np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))
array([('a', 1, 2.0), ('b', 3, 4.0)],
dtype=[('f0', '|S10'), ('f1', '<i8'), ('f2', '<f8')])
Using an explicit dtype
is much more efficient than using dtype=None
and is the recommended way.
In both cases (dtype=None
or explicit, non-homogeneous dtype
), you end up with a structured array.
[Note: With dtype=None
, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]
First, I try without a space, rtrim($arraynama, ",");
and get an error result.
Then I add a space and get a good result:
$newarraynama = rtrim($arraynama, ", ");
"ASCII is a subset of UTF-8, so..." - so UTF-8 is a set? :)
In other words: any string build with code points
from x00 to x7F has indistinguishable representations (byte sequences) in ASCII and UTF-8. Converting such string is pointless.
For integers, there is no difference between pre- and post-increment.
If i
is an object of a non-trivial class, then ++i
is generally preferred, because the object is modified and then evaluated, whereas i++
modifies after evaluation, so requires a copy to be made.
Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement),
SecondList.OrderBy(sElement => sElement))
My problem was the location of the config file.
In eclipse settings (Windows->preferences->maven->User Settings) the default config file for maven points to C:\users\*yourUser*\.m2\settings.xml
. If you unzip maven and install it in a folder of your choice the file will be inside *yourMavenInstallDir*/conf/
, thus probably not where eclipse thinks (mine was not). If this is the case maven won't load correctly. You just need to set the "User Settings" path to point to the right file.
As stated on Installing MySQL-python on mac :
pip uninstall MySQL-python
brew install mysql
pip install MySQL-python
Then test it :
python -c "import MySQLdb"
This might help someone -
ArrayList<Integer> integerArrayList = new ArrayList<>(Arrays.asList(new Integer[10]));
Add:
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
To server{} in nginx.conf
Works for me.
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
var str = "hello world & hello universe"
In order to replace both Spaces and Symbols in one shot, we can use the below regex code.
str.replaceAll("\\W+","")
Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches
Try it!
I wrote with parameters that are predefined
They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:
Alter Procedure [Test]
@StartDate AS varchar(6) = NULL,
@EndDate AS varchar(6) = NULL
AS
...
NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.
Now you can call it without passing any arguments e.g.
exec dbo.TEST
It don't create normally; you need to add it by yourself.
After adding Global.asax
by
You need to add a class
Inherit the newly generated by System.Web.HttpApplication
and copy all the method created Global.asax
to Global.cs
and also add an inherit attribute to the Global.asax file.
Your Global.asax will look like this: -
<%@ Application Language="C#" Inherits="Global" %>
Your Global.cs in App_Code
will look like this: -
public class Global : System.Web.HttpApplication
{
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
/// Many other events like begin request...e.t.c, e.t.c
}
#overlay {
position: fixed;
width: 100%;
height: 100%;
background: black url(spinner.gif) center center no-repeat;
opacity: .5;
}
it's better to use rgba color instead of opacity to prevent applying alpha to spinner image.
background: rgba(0,0,0,.5) url(spinner.gif) center center no-repeat;
I deal with the same problem (Jenkins multibranch pipeline) - having only commit information and trying to find a branch name where this commit originally came from. It must work for remote branches, local copies are not available.
This is what I work with:
git rev-parse HEAD | xargs git name-rev
Optionally you can strip the output:
git rev-parse HEAD | xargs git name-rev | cut -d' ' -f2 | sed 's/remotes\/origin\///g'
Trying to JOIN in MongoDB would defeat the purpose of using MongoDB. You could, however, use a DBref and write your application-level code (or library) so that it automatically fetches these references for you.
Or you could alter your schema and use embedded documents.
Your final choice is to leave things exactly the way they are now and do two queries.
It normally means an un-aligned access.
An attempt to access memory that isn't physically present would also give a bus error, but you won't see this if you're using a processor with an MMU and an OS that's not buggy, because you won't have any non-existent memory mapped to your process's address space.
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
Just saw a variation on this issue: I went into the project.pbxproj file as per Brad Smith's notes above, except in this case all of the PROVISIONING_PROFILE lines seemed to be correct, with no occurrence of the "bad" profile string that Xcode couldn't find.
However, the fix was the same: deleting ALL of the PROVISIONING_PROFILE lines in project.pbxproj, even though they looked "good" in theory, and then reopening the project in Xcode.
Looking at their docs, they have a $.uniform.update
feature to refresh a "uniformed" element.
Example: http://jsfiddle.net/r87NH/4/
$("input:checkbox").uniform();
$("body").on("click", "#check1", function () {
var two = $("#check2").attr("checked", this.checked);
$.uniform.update(two);
});
Simply add an extension to the -i flag. This basically creates a backup file with the original file.
sed -i.bakup 's/linenumber/number/' ~/.vimrc
sed will execute without the error
Using a static const is like using any other const variables in your code. This means you can trace wherever the information comes from, as opposed to a #define that will simply be replaced in the code in the pre-compilation process.
You might want to take a look at the C++ FAQ Lite for this question: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.7
A good way to test if a string is a correct date is to use the command date:
if date -d "${DATE}" >/dev/null 2>&1
then
# do what you need to do with your date
else
echo "${DATE} incorrect date" >&2
exit 1
fi
from comment: one can use formatting
if [ "2017-01-14" == $(date -d "2017-01-14" '+%Y-%m-%d') ]
This solution also helps in cases of more than one extension like "Avishay.student.DB"
FileInfo FileInf = new FileInfo(filePath);
string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), "");
SELECT ... INTO :
select * into <destination table> from <source table>
You can use np.logaddexp
(which implements the idea in @gg349's answer):
In [33]: d = np.array([[1089, 1093]])
In [34]: e = np.array([[1000, 4443]])
In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
In [36]: log_res
Out[36]: -266.99999385580668
In [37]: res = exp(log_res)
In [38]: res
Out[38]: 1.1050349147204485e-116
Or you can use scipy.special.logsumexp
:
In [52]: from scipy.special import logsumexp
In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
In [54]: res
Out[54]: 1.1050349147204485e-116
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
sttr1.search(str2);
it will return the position of the match, or -1 if it isn't found.
TEXT and CHAR will convert to/from the character set they have associated with time. BLOB and BINARY simply store bytes.
BLOB is used for storing binary data while Text is used to store large string.
BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.
TEXT values are treated as nonbinary strings (character strings). They have a character set, and values are sorted and compared based on the collation of the character set.
look to the List AddRange
method here
-> it works like pointer u don't have to use *
for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'
go to services in administrative tools and select oracleserviceSID and restart it
Navigate to your play page:
https://play.google.com/store/apps/details?id=com.yourpackage
Using a standard HTTP GET. Now the following jQuery finds important info for you:
$("[itemprop='softwareVersion']").text()
$(".recent-change").each(function() { all += $(this).text() + "\n"; })
Now that you can extract these information manually, simply make a method in your app that executes this for you.
public static String[] getAppVersionInfo(String playUrl) {
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
props.setAllowHtmlInsideAttributes(true);
props.setAllowMultiWordAttributes(true);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
try {
URL url = new URL(playUrl);
URLConnection conn = url.openConnection();
TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
Object[] new_nodes = node.evaluateXPath("//*[@class='recent-change']");
Object[] version_nodes = node.evaluateXPath("//*[@itemprop='softwareVersion']");
String version = "", whatsNew = "";
for (Object new_node : new_nodes) {
TagNode info_node = (TagNode) new_node;
whatsNew += info_node.getAllChildren().get(0).toString().trim()
+ "\n";
}
if (version_nodes.length > 0) {
TagNode ver = (TagNode) version_nodes[0];
version = ver.getAllChildren().get(0).toString().trim();
}
return new String[]{version, whatsNew};
} catch (IOException | XPatherException e) {
e.printStackTrace();
return null;
}
}
Uses HtmlCleaner
You have to be careful with using a leading underscore. A leading underscore before a capital letter in a word is reserved. For example:
_Foo
_L
are all reserved words while
_foo
_l
are not. There are other situations where leading underscores before lowercase letters are not allowed. In my specific case, I found the _L happened to be reserved by Visual C++ 2005 and the clash created some unexpected results.
I am on the fence about how useful it is to mark up local variables.
Here is a link about which identifiers are reserved: What are the rules about using an underscore in a C++ identifier?
compactitem
does the job.
\usepackage{paralist}
...
\begin{compactitem}[$\bullet$]
\item Element 1
\item Element 2
\end{compactitem}
\vspace{\baselineskip} % new line after list
As (Bourne) shell variables cannot contain dots you can replace them by underscores. Read every line, translate . in the key to _ and evaluate.
#/bin/sh
file="./app.properties"
if [ -f "$file" ]
then
echo "$file found."
while IFS='=' read -r key value
do
key=$(echo $key | tr '.' '_')
eval ${key}=\${value}
done < "$file"
echo "User Id = " ${db_uat_user}
echo "user password = " ${db_uat_passwd}
else
echo "$file not found."
fi
Note that the above only translates . to _, if you have a more complex format you may want to use additional translations. I recently had to parse a full Ant properties file with lots of nasty characters, and there I had to use:
key=$(echo $key | tr .-/ _ | tr -cd 'A-Za-z0-9_')
In addition to the above great answers using Threads, in case you have to use your main thread or prefer an async approach - I wrapped a short class around aio_timers Timer class (to enable repeating)
import asyncio
from aio_timers import Timer
class RepeatingAsyncTimer():
def __init__(self, interval, cb, *args, **kwargs):
self.interval = interval
self.cb = cb
self.args = args
self.kwargs = kwargs
self.aio_timer = None
self.start_timer()
def start_timer(self):
self.aio_timer = Timer(delay=self.interval,
callback=self.cb_wrapper,
callback_args=self.args,
callback_kwargs=self.kwargs
)
def cb_wrapper(self, *args, **kwargs):
self.cb(*args, **kwargs)
self.start_timer()
from time import time
def cb(timer_name):
print(timer_name, time())
print(f'clock starts at: {time()}')
timer_1 = RepeatingAsyncTimer(interval=5, cb=cb, timer_name='timer_1')
timer_2 = RepeatingAsyncTimer(interval=10, cb=cb, timer_name='timer_2')
clock starts at: 1602438840.9690785
timer_1 1602438845.980087
timer_2 1602438850.9806316
timer_1 1602438850.9808934
timer_1 1602438855.9863033
timer_2 1602438860.9868324
timer_1 1602438860.9876585
I will suggest something totally different, we used it at work for many years ago on real computers and it worked perfect.
Boot both old and new machine on linux rescue Cd.
read the disk from one, and write it down to the other one, block by block, effectively copying the dist over the network.
You have to play around a little bit with the command line, but it worked so well that both machine complained about IP-conflict when they both booted :-) :-)
cat /dev/sda | ssh user@othermachine cat - > /dev/sda
Had the same problem. I changed the file build.gradle inside the app folder from this: compileSdkVersion 23 buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.vastsoftware.family.farmingarea"
minSdkVersion 11
targetSdkVersion 23
versionCode 1
versionName "1.0"
to this:
compileSdkVersion 23 buildToolsVersion "21.0.2"
defaultConfig {
applicationId "com.vastsoftware.family.farmingarea"
minSdkVersion 11
targetSdkVersion 21
versionCode 1
versionName "1.0"
and worked perfectly! hope it works for you too!
This can also be achieved with jsp:include. Chad Darby explains well here in this video https://www.youtube.com/watch?v=EWbYj0qoNHo
Just replace
& with &
And for other characters:
> with >
< with <
\" with "
' with '
Open target location of chrome and navigate through cmd type
chrome.exe --disable-web-security --user-data-dir=c:\my\dat
Use an Iterator
and call remove()
:
Iterator<String> iter = myArrayList.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (someCondition)
iter.remove();
}
I think jQuery cannot find the element.
First of all find the element
var rowTemplate= document.getElementsByName("rowTemplate");
or
var rowTemplate = document.getElementById("rowTemplate");
or
var rowTemplate = $('#rowTemplate');
Then try your code again
rowTemplate.html().replace(....)
In their simplest form, reset
resets the index without touching the working tree, while checkout
changes the working tree without touching the index.
Resets the index to match HEAD
, working tree left alone:
git reset
Conceptually, this checks out the index into the working tree. To get it to actually do anything you would have to use -f
to force it to overwrite any local changes. This is a safety feature to make sure that the "no argument" form isn't destructive:
git checkout
Once you start adding parameters it is true that there is some overlap.
checkout
is usually used with a branch, tag or commit. In this case it will reset HEAD
and the index to the given commit as well as performing the checkout of the index into the working tree.
Also, if you supply --hard
to reset
you can ask reset
to overwrite the working tree as well as resetting the index.
If you current have a branch checked out out there is a crucial different between reset
and checkout
when you supply an alternative branch or commit. reset
will change the current branch to point at the selected commit whereas checkout
will leave the current branch alone but will checkout the supplied branch or commit instead.
Other forms of reset
and commit
involve supplying paths.
If you supply paths to reset
you cannot supply --hard
and reset
will only change the index version of the supplied paths to the version in the supplied commit (or HEAD
if you don't specify a commit).
If you supply paths to checkout
, like reset
it will update the index version of the supplied paths to match the supplied commit (or HEAD
) but it will always checkout the index version of the supplied paths into the working tree.
I was able to resolve this very easily my simply enqueuing jQuery
wp_enqueue_script("jquery");
You only have to replace the WHERE with a LEFT JOIN:
SELECT CASE
WHEN S.Id IS NOT NULL AND S.Status = 1 AND ...) THEN 1
ELSE 0
END AS [Value]
FROM (SELECT @SiteId AS Id) R
LEFT JOIN Sites S ON S.Id = R.Id
This solution allows you to return default values for each column also, for example:
SELECT
CASE WHEN S.Id IS NULL THEN 0 ELSE S.Col1 END AS Col1,
S.Col2,
ISNULL(S.Col3, 0) AS Col3
FROM
(SELECT @Id AS Id) R
LEFT JOIN Sites S ON S.Id = R.Id AND S.Status = 1 AND ...
<object CLASSID="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320" height="256" CODEBASE="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="sample.mov">
<param name="qtsrc" value="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov">
<param name="autoplay" value="true">
<param name="loop" value="false">
<param name="controller" value="true">
<embed src="sample.mov" qtsrc="rtsp://realmedia.uic.edu/itl/ecampb5/demo_broad.mov" width="320" height="256" autoplay="true" loop="false" controller="true" pluginspage="http://www.apple.com/quicktime/"></embed>
</object>
source is the first search result of the Google
When you cast a DateTime to an int it "truncates" at noon, you might want to strip the day out like so
cast(DATEADD(DAY, DATEDIFF(DAY, 0, created_date), 0) as int) as DayBucket
From a performance point of view, I guess that a direct SQL query using the EXISTS command would be appropriate. See here for how to execute SQL directly in Entity Framework: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx
You can't alter the existing columns for identity.
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.
Alter Table Names
Add Id_new Int Identity(1, 1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
See the following Microsoft SQL Server Forum post for more details:
Assuming you're using winforms, default panel components does not offer you a way to disable the horizontal scrolling components. A workaround of this is to disable the auto scrolling and add a scrollbar yourself:
ScrollBar vScrollBar1 = new VScrollBar();
vScrollBar1.Dock = DockStyle.Right;
vScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };
panel1.Controls.Add(vScrollBar1);
Detailed discussion here.
Weak entities are also called dependent entities, since it's existence depends on other entities. Such entities are represented by a double outline rectangle in the E-R diagram.
Strong entities are also called independent entities.
By this code for formating price in product list
echo Mage::helper('core')->currency($_product->getPrice());
private string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
The method above will bring you something like this:
"C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace\bin\Debug"
From here you can navigate backwards using System.IO.Directory.GetParent:
_filePath = Directory.GetParent(_filePath).FullName;
1 time will get you to \bin, 2 times will get you to \myProjectNamespace, so it would be like this:
_filePath = Directory.GetParent(Directory.GetParent(_filePath).FullName).FullName;
Well, now you have something like "C:\Users\myuser\Documents\Visual Studio 2015\Projects\myProjectNamespace", so just attach the final path to your fileName, for example:
_filePath += @"\myfile.txt";
TextReader tr = new StreamReader(_filePath);
Hope it helps.
all
is one option:
> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")
> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE
But you may have to watch out for recycling:
> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE
The documentation for length
says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all
.
As of v6, Java SE ships with JAXB. javax.xml.bind.DatatypeConverter
has static methods that make this easy. See parseBase64Binary()
and printBase64Binary()
.
$ man tr
NAME
tr - translate or delete characters
SYNOPSIS
tr [OPTION]... SET1 [SET2]
DESCRIPTION
Translate, squeeze, and/or delete characters from standard
input, writing to standard output.
In order to wipe all whitespace including newlines you can try:
cat file.txt | tr -d " \t\n\r"
You can also use the character classes defined by tr (credits to htompkins comment):
cat file.txt | tr -d "[:space:]"
For example, in order to wipe just horizontal white space:
cat file.txt | tr -d "[:blank:]"
Below is the server side code that would call the handler and recieve the stream data and loads into xml doc
Stream stream = null;
**Create a web request with the specified URL**
WebRequest myWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
**Senda a web request and wait for response.**
WebResponse webResponse = myWebRequest.GetResponse();
**Get the stream object from response object**
stream = webResponse.GetResponseStream();
XmlDocument xmlDoc = new XmlDocument();
**Load stream data into xml**
xmlDoc.Load(stream);
I hope it will help someone else.
This error seems to occur also when you UNintentionally send an object to React child components.
Example of it is passing to child component new Date('....') as follows:
const data = {name: 'ABC', startDate: new Date('2011-11-11')}
...
<GenInfo params={data}/>
If you send it as value of a child component parameter you would be sending a complex Object and you may get the same error as stated above.
Check if you are passing something similar (that generates Object under the hood).
If you don't have access to a subfolder inside the directory tree, Directory.GetFiles stops and throws the exception resulting in a null value in the receiving string[].
Here, see this answer https://stackoverflow.com/a/38959208/6310707
It manages the exception inside the loop and keep on working untill the entire folder is traversed.
The thing is that decimal numbers defaults to double. And since double doesn't fit into float you have to tell explicitely you intentionally define a float. So go with:
float b = 3.6f;
You can put your file to /etc/cron.d/ in cron format. Add some unique prefix to the filenaname To list script-specific cron jobs simply work with a list of files with a unique prefix. Delete the file when you want to disable the job.
Not sure why you specify that it has to be within Angular. It's easily accomplished through JavaScript. Look at the navigator
object.
Just open up your console and inspect navigator
. It seems what you're specifically looking for is .userAgent
or .appVersion
.
I don't have IE9 installed, but you could try this following code
//Detect if IE 9
if(navigator.appVersion.indexOf("MSIE 9.")!=-1)
Most answer are assuming the RecyclerView
uses a LinearLayoutManager
, or GridLayoutManager
, or even StaggeredGridLayoutManager
, or assuming that the scrolling is vertical or horyzontal, but no one has posted a completly generic answer.
Using the ViewHolder
's adapter is clearly not a good solution. An adapter might have more than 1 RecyclerView
using it. It "adapts" their contents. It should be the RecyclerView (which is the one class which is responsible of what is currently displayed to the user, and not the adapter which is responsible only to provide content to the RecyclerView
) which must notify your system that more items are needed (to load).
Here is my solution, using nothing else than the abstracted classes of the RecyclerView (RecycerView.LayoutManager and RecycerView.Adapter):
/**
* Listener to callback when the last item of the adpater is visible to the user.
* It should then be the time to load more items.
**/
public abstract class LastItemListener extends RecyclerView.OnScrollListener {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// init
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
RecyclerView.Adapter adapter = recyclerView.getAdapter();
if (layoutManager.getChildCount() > 0) {
// Calculations..
int indexOfLastItemViewVisible = layoutManager.getChildCount() -1;
View lastItemViewVisible = layoutManager.getChildAt(indexOfLastItemViewVisible);
int adapterPosition = layoutManager.getPosition(lastItemViewVisible);
boolean isLastItemVisible = (adapterPosition == adapter.getItemCount() -1);
// check
if (isLastItemVisible)
onLastItemVisible(); // callback
}
}
/**
* Here you should load more items because user is seeing the last item of the list.
* Advice: you should add a bollean value to the class
* so that the method {@link #onLastItemVisible()} will be triggered only once
* and not every time the user touch the screen ;)
**/
public abstract void onLastItemVisible();
}
// --- Exemple of use ---
myRecyclerView.setOnScrollListener(new LastItemListener() {
public void onLastItemVisible() {
// start to load more items here.
}
}
The answer by @Pykler is great but the Node requirement is outdated. The comments in that answer suggest the simpler answer, which I've put here to save others time:
Install PhantomJS
As @Vivin-Paliath points out, it's a standalone project, not part of Node.
Mac:
brew install phantomjs
Ubuntu:
sudo apt-get install phantomjs
etc
Set up a virtualenv
(if you haven't already):
virtualenv mypy # doesn't have to be "mypy". Can be anything.
. mypy/bin/activate
If your machine has both Python 2 and 3 you may need run virtualenv-3.6 mypy
or similar.
Install selenium:
pip install selenium
Try a simple test, like this borrowed from the docs:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.PhantomJS()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
driver.close()
There are several ways to do plots in R; lattice
is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:
Reasonstats <- read.table(text="Category Reason Species
Decline Genuine 24
Improved Genuine 16
Improved Misclassified 85
Decline Misclassified 41
Decline Taxonomic 2
Improved Taxonomic 7
Decline Unclear 41
Improved Unclear 117", header=T)
ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3 <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason
windows()
barplot(t(Reasonstats3), beside=TRUE, ylab="number of species",
cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
box(bty="l")
Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline
and for Improved
. Then I made those categories the column names. I also made the Reason
s the row names. The barplot()
function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot()
function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot()
wants for your intended output.
In case you using lookup to set default read from environment you have also set the second parameter of default to true:
- set_facts:
ansible_ssh_user: "{{ lookup('env', 'SSH_USER') | default('foo', true) }}"
You can also concatenate multiple default definitions:
- set_facts:
ansible_ssh_user: "{{ some_var.split('-')[1] | default(lookup('env','USER'), true) | default('foo') }}"
Using bash regular expressions:
re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi
Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.
re="http://([^/]+)/"
This is the regular expression stored in a bash variable, re
- i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:
http://
is just a string - the input string must contain this substring for the regular expression to match[]
Normally square brackets are used say "match any character within the brackets". So c[ao]t
would match both "cat" and "cot". The ^
character within the []
modifies this to say "match any character except those within the square brackets. So in this case [^/]
will match any character apart from "/".+
to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+
matches 1 or more of the set of all characters, excluding "/".()
parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:
if [[ $name =~ $re ]]; then
echo ${BASH_REMATCH[1]}
fi
In bash, the [[ ]]
specify an extended conditional test, and may contain the =~
bash regular expression operator. In this case we test whether the input string $name
matches the regular expression $re
. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()
), and we can access it using the BASH_REMATCH array:
${BASH_REMATCH[0]}
will be the entire string matched by the regular expression, i.e. "http://www.google.com/".()
within a regular expression - The BASH_REMATCH
elements will correspond to these in order. So in this case ${BASH_REMATCH[1]}
will contain "www.google.com", which I think is the string you want.Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~
operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.
This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.
Note that instead of setting the $re
variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~
match operator.
You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).
http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx
But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends
http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx
Your code also seems a bit strange, like you are nesting lists?
Using a web service s-shot.ru (so it's not so fast), but quite easy to set up what need through the link configuration. And you can easily capture full page screenshots
import requests
import urllib.parse
BASE = 'https://mini.s-shot.ru/1024x0/JPEG/1024/Z100/?' # you can modify size, format, zoom
url = 'https://stackoverflow.com/'#or whatever link you need
url = urllib.parse.quote_plus(url) #service needs link to be joined in encoded format
print(url)
path = 'target1.jpg'
response = requests.get(BASE + url, stream=True)
if response.status_code == 200:
with open(path, 'wb') as file:
for chunk in response:
file.write(chunk)
You can use placeholder Attribute, which doesn't add a default value but might be what you are looking out for :
<textarea placeholder="this text will show in the textarea"></textarea>
Check it out here - http://jsfiddle.net/8DzCE/949/
Important Note ( As suggested by Jon Brave in the comments ) :
Placeholder Attribute does not set the value of a textarea. Rather "The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value" [and it disappears as soon as user clicks into the textarea]. It will never act as "the default value" for the control. If you want that, you must put the desired text inside the Here is the actual default value, as per other answers here
New, resurrected project site (Win7 compability and more!): http://sshwindows.sourceforge.net
1st January 2012
- OpenSSH for Windows 5.6p1-2 based release created!!
- Happy New Year all! Since COpSSH has started charging I've resurrected this project
- Updated all binaries to current releases
- Added several new supporting DLLs as required by all executables in package
- Renamed switch.exe to bash.exe to remove the need to modify and compile mkpasswd.exe each build
- Please note there is a very minor bug in this release, detailed in the docs. I'm working on fixing this, anyone who can code in C and can offer a bit of help it would be much appreciated
Soviut's advice for lxml objectify is good. With a specially subclassed simplejson, you can turn an lxml objectify result into json.
import simplejson as json
import lxml
class objectJSONEncoder(json.JSONEncoder):
"""A specialized JSON encoder that can handle simple lxml objectify types
>>> from lxml import objectify
>>> obj = objectify.fromstring("<Book><price>1.50</price><author>W. Shakespeare</author></Book>")
>>> objectJSONEncoder().encode(obj)
'{"price": 1.5, "author": "W. Shakespeare"}'
"""
def default(self,o):
if isinstance(o, lxml.objectify.IntElement):
return int(o)
if isinstance(o, lxml.objectify.NumberElement) or isinstance(o, lxml.objectify.FloatElement):
return float(o)
if isinstance(o, lxml.objectify.ObjectifiedDataElement):
return str(o)
if hasattr(o, '__dict__'):
#For objects with a __dict__, return the encoding of the __dict__
return o.__dict__
return json.JSONEncoder.default(self, o)
See the docstring for example of usage, essentially you pass the result of lxml objectify
to the encode method of an instance of objectJSONEncoder
Note that Koen's point is very valid here, the solution above only works for simply nested xml and doesn't include the name of root elements. This could be fixed.
I've included this class in a gist here: http://gist.github.com/345559
gettimeofday() will probably do what you want.
If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained, lowest overhead counter you can get for performance measurement.
Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.
When I run this on my box, I get
11867927879484732 11867927879692217 it took this long to call printf: 207485
Here's the Intel developer's guide that gives tons of detail.
#include <stdio.h>
#include <stdint.h>
inline uint64_t rdtsc() {
uint32_t lo, hi;
__asm__ __volatile__ (
"xorl %%eax, %%eax\n"
"cpuid\n"
"rdtsc\n"
: "=a" (lo), "=d" (hi)
:
: "%ebx", "%ecx");
return (uint64_t)hi << 32 | lo;
}
main()
{
unsigned long long x;
unsigned long long y;
x = rdtsc();
printf("%lld\n",x);
y = rdtsc();
printf("%lld\n",y);
printf("it took this long to call printf: %lld\n",y-x);
}
You need commas after end
finishing the case statement. And, the "as" goes after the case
statement, not inside it:
Insert into TblStuff(FullName, Address, City, Zip)
Select (Case When Middle is Null Then Fname + LName
Else Fname +' ' + Middle + ' '+ Lname
End) as FullName,
(Case When Address2 is Null Then Address1
else Address1 +', ' + Address2
End) as Address,
City as City,
Zip as Zip
from tblImport
You can use the mt
and mb
spacing utilities to add extra margins to the <hr>
, for example:
<hr class="mt-5 mb-5">
You need to set oracle to listen on all ip addresses (by default, it listens only to localhost connections.)
listener.ora
This file is located in:
%ORACLE_HOME%\network\admin\listener.ora
.Replace localhost
with 0.0.0.0
# ...
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
)
)
# ...
Windows: WinKey + r
services.msc
Linux (CentOs):
sudo systemctl restart oracle-xe
I think you could just use the String#length method...
http://ruby-doc.org/core-1.9.3/String.html#method-i-length
Example:
text = 'The quick brown fox jumps over the lazy dog.'
puts text.length > 25 ? 'Too many characters' : 'Accepted'
This works on Windows:
java -cp "lib/*" %MAINCLASS%
where %MAINCLASS%
of course is the class containing your main method.
Alternatively:
java -cp "lib/*" -jar %MAINJAR%
where %MAINJAR%
is the jar file to launch via its internal manifest.
Try this one
SELECT country_id, country_title
FROM (SELECT country_id, country_title,
CASE
WHEN country_title=LAG(country_title, 1, 0) OVER(ORDER BY country_title) THEN 1
ELSE 0
END AS "Duplicates"
FROM tbl_countries)
WHERE "Duplicates"=0;
Get the latest version of MVC3 via NuGet. Open your project in Dev Studio. Open the Package Manager Console tab at the bottom of Dev Studio. Then use this command:
PM> Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1
If you click the tab key after "-Version" you will get a list of all of the available versions.
If you have an old version of NuGet you may get an error indicating you have to upgrade it. If so, open Tools->Extension Manager to install the latest version of NuGet. Note, you will need to run Dev Studio as Administrator before you can install NuGet.
Installing MVC3 should update Web.config in your project.
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.1" newVersion="3.0.0.1" />
</dependentAssembly>
</assemblyBinding>
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
while($row = mysqli_fetch_array($result))
echo $row['note'];
Try ZebraTester which is much easier to use than jMeter. I have used jMeter for a long time but the total setup time for a load test was always an issue. Although ZebraTester isn't open source, the time that I have saved in the last six months makes up for it. They also have a SaaS portal which can be used for quickly running tests using their load generators.
something like:
DELIMITER //
CREATE PROCEDURE alluser()
BEGIN
SELECT *
FROM users;
END //
DELIMITER ;
than:
SHOW CREATE PROCEDURE alluser
gives result:
'alluser', 'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER', 'CREATE DEFINER=`root`@`localhost` PROCEDURE `alluser`()
BEGIN
SELECT *
FROM users;
END'
2017 Update I guess. textarea worked fine for me using Spring, Bootstrap and a bunch of other things. Got the SOAP payload stored in a DB, read by Spring and push via Spring-MVC. xmp didn't work at all.
If you are a programmer, many XML parsing programming libraries will let you parse XML, then output it - and generating pretty printed, indented output is an output option.
Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.
See,
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON
your syntax is completely wrong....you need to give findelement to the driver
i.e your code will be :
WebDriver driver = new FirefoxDriver();
WebeElement element ;
element = driver.findElement(By.xpath("//[@test-id='test-username']");
// your xpath is: "//[@test-id='test-username']"
i suggest try this :"//*[@test-id='test-username']"
Say you have a child_method()
in the child component:
export default {
methods: {
child_method () {
console.log('I got clicked')
}
}
}
Now you want to execute the child_method
from parent component:
<template>
<div>
<button @click="exec">Execute child component</button>
<child-cmp ref="child"></child_cmp> <!-- note the ref="child" here -->
</div>
</template>
export default {
methods: {
exec () { //accessing the child component instance through $refs
this.$refs.child.child_method() //execute the method belongs to the child component
}
}
}
If you want to execute a parent component method from child component:
this.$parent.name_of_method()
NOTE: It is not recommended to access the child and parent component like this.
Instead as best practice use Props & Events for parent-child communication.
If you want communication between components surely use vuex or event bus
Please read this very helpful article
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
You can try netstat
netstat -vanp tcp | grep 3000
For macOS El Capitan and newer (or if your netstat doesn't support -p
), use lsof
lsof -i tcp:3000
For Centos 7 use:
netstat -vanp --tcp | grep 3000
After checking the default locations on Win7 with mysql --help
and unable to find any config file, I manually searched for my.ini and found it at C:\ProgramData\MySQL\MySQL Server x.y
(yep, ProgramData
, not Program Files
).
Though I used an own my.ini at Program Files
, the other configuration overwrote my settings.
I know this is old, but none of the answers here is a real solution if you want to be able to double-click Python files and have the correct interpreter used without modifying your PYTHONPATH
or PATH
every time you want to use a different interpreter. Sure, from the command line, activate my-environment
works, but OP specifically asked about double-clicking.
In this case, the correct thing to do is use the Python launcher for Windows. Then, all you have to do is add #! path\to\interpreter\python.exe
to the top of your script. Unfortunately, although the launcher comes standard with Python 3.3+, it is not included with Anaconda (see Python & Windows: Where is the python launcher?), and the simplest thing to do is to install it separately from here.
Take a look at OPENROWSET
, and do something like:
SELECT * INTO #TEMPTABLE FROM OPENROWSET('SQLNCLI'
, 'Server=(local)\SQL2008;Trusted_Connection=yes;',
'SELECT * FROM ' + @tableName)
You can do typeOf(T)
, but I would double check your method and make sure your not violating single responsability here. This would be a code smell, and that's not to say it shouldn't be done but that you should be cautious.
The point of generics is being able to build type-agnostic algorthims were you don't care what the type is or as long as it fits within a certain set of criteria. Your implementation isn't very generic.
My situation was that I did not have a main function.
As other posters have pointed out, there are some limitations with the AWS Transfer for SFTP service. You need to closely align requirements. For example, there are no quotas, whitelists/blacklists, file type limits, and non key based access requires external services. There is also a certain overhead relating to user management and IAM, which can get to be a pain at scale.
We have been running an SFTP S3 Proxy Gateway for about 5 years now for our customers. The core solution is wrapped in a collection of Docker services and deployed in whatever context is needed, even on-premise or local development servers. The use case for us is a little different as our solution is focused data processing and pipelines vs a file share. In a Salesforce example, a customer will use SFTP as the transport method sending email, purchase...data to an SFTP/S3 enpoint. This is mapped an object key on S3. Upon arrival, the data is picked up, processed, routed and loaded to a warehouse. We also have fairly significant auditing requirements for each transfer, something the Cloudwatch logs for AWS do not directly provide.
As other have mentioned, rolling your own is an option too. Using AWS Lightsail you can setup a cluster, say 4, of $10 2GB instances using either Route 53 or an ELB.
In general, it is great to see AWS offer this service and I expect it to mature over time. However, depending on your use case, alternative solutions may be a better fit.
Although this doesn't give you the flexibility associated with multiple font sizes, adding a newline character to your pyplot.title() string can be a simple solution;
plt.title('Really Important Plot\nThis is why it is important')
You need to specify correct Content-type, Content-encoding and charset like
data:image/jpeg;charset=utf-8;base64,
according to the syntax of the data URI scheme:
data:[<media type>][;charset=<character set>][;base64],<data>
Yes. You know that you can put any Object
into the Object
parameter of most JOptionPane.showXXX methods
, and often that Object
happens to be a JPanel
.
In your situation, perhaps you could use a JPanel
that has several JTextFields
in it:
import javax.swing.*;
public class JOptionPaneMultiInput {
public static void main(String[] args) {
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("x:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("y:"));
myPanel.add(yField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("x value: " + xField.getText());
System.out.println("y value: " + yField.getText());
}
}
}
It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
$headers = apache_request_headers();
$is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');
You will get useful information from here.
SELECT ticker
INTO quotedb
FROM tickerdb;
there is a problem in best answer given by ScottKoon
here is it
} else if(el.attachEvent ) {
myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}
Should be
} else if(myInput.attachEvent ) {
myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}
Due to this it didn't work in IE. Hoping that ScottKoon will update code
Deleting is such a headache. I am posting the solution for Android Studio 1.0.2.
Step 1: Right click on the "Project Name" selected from the folder hierarchy like shown.
Note: It can also be deleted from the Commander View from right hand side of your window by right clicking the project name and selecting delete from the context menu.
Step 2: The project is deleted(seemingly) but gradle seems to keep the record of the project app folder(Check it by clcking on the Gradle View). Now go to File->Close Project.
Step 3: Now you are at the start window. Move the cursor on the in recent project list. Press Delete.
Step 4: Delete the folder from the explorer by moving or deleting it actually. This location is in your_user_name->Android Studio Projects->...
Step 5: Go back to the Android studio window and the project is gone for good. You can start a new project now.
Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.
public class Time
{
public static void Timestamps()
{
OutputTimestamp();
Thread.Sleep(1000);
OutputTimestamp();
}
private static void OutputTimestamp()
{
var timestamp = DateTime.UtcNow.Ticks;
var localTicks = DateTime.Now.Ticks;
var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
Console.Out.WriteLine("Timestamp = {0}. Local ticks = {1}. Local time = {2}.", timestamp, localTicks, localTime);
}
}
Output:
Timestamp = 636988286338754530. Local ticks = 636988034338754530. Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736. Local ticks = 636988034348878736. Local time = 2019-07-15 4:03:54 PM.
The problem is RecyclerView.Adatper
does not provide any methods that return the index of element
public abstract static class Adapter<VH extends ViewHolder> {
/**
* returns index of the given element in adapter, return -1 if not exist
*/
public int indexOf(Object elem);
}
My workaround is to create a map instance for (element, position)s
public class FriendAdapter extends RecyclerView.Adapter<MyViewHolder> {
private Map<Friend, Integer> posMap ;
private List<Friend> friends;
public FriendAdapter(List<Friend> friends ) {
this.friends = new ArrayList<>(friends);
this.posMap = new HashMap<>();
for(int i = 0; i < this.friends.size(); i++) {
posMap.put(this.friends.get(i), i);
}
}
public int indexOf(Friend friend) {
Integer position = this.posMap.get(elem);
return position == null ? -1 : position;
}
// skip other methods in class Adapter
}
Friend
) should implements hashCode()
and equals()
because it is key in hashmap.when an element changed,
void someMethod() {
Friend friend = ...;
friend.setPhoneNumber('xxxxx');
int position = friendAdapter.indexOf(friend);
friendAdapter.notifyItemChanged(position);
}
It is good to define an helper method
public class FriendAdapter extends extends RecyclerView.Adapter<MyViewHolder> {
public void friendUpdated(Friend friend) {
int position = this.indexOf(friend);
this.notifyItemChanged(position);
}
}
Map instance(Map<Friend, Integer> posMap
) is not necessarily required.
If map is not used, looping throughout list can find the position of an element.
The following function will create the requested table (with or without numpy) with Python 3 (maybe also Python 2). I have chosen to set the width of each column to match that of the longest team name. You could modify it if you wanted to use the length of the team name for each column, but will be more complicated.
Note: For a direct equivalent in Python 2 you could replace the zip
with izip
from itertools.
def print_results_table(data, teams_list):
str_l = max(len(t) for t in teams_list)
print(" ".join(['{:>{length}s}'.format(t, length = str_l) for t in [" "] + teams_list]))
for t, row in zip(teams_list, data):
print(" ".join(['{:>{length}s}'.format(str(x), length = str_l) for x in [t] + row]))
teams_list = ["Man Utd", "Man City", "T Hotspur"]
data = [[1, 2, 1],
[0, 1, 0],
[2, 4, 2]]
print_results_table(data, teams_list)
This will produce the following table:
Man Utd Man City T Hotspur
Man Utd 1 2 1
Man City 0 1 0
T Hotspur 2 4 2
If you want to have vertical line separators, you can replace " ".join
with " | ".join
.
References:
the main method should be declared in the your class like this :
public class derivativeQuiz_source{
// bunch of methods .....
public static void main(String args[])
{
// code
}
}
when I send only one object from the client to server all works well.
when I attempt to send several objects one after another on the same stream I get
StreamCorruptedException
.
Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.
Open Control Panel >> Network and Sharing Center. Now click on Change Adapter Settings. Right click on the adapter whose Name or the Device Name matches with VirtualBox Host-Only Ethernet Adapter # 3 and click on Properties. Click on the Configure button.
Now click on the Driver tab. Click on Update Driver. Select Browse my computer for drivers. Now choose Let me pick from a list of available drivers on my computer. Select the choice you get and click on Next. Click Close to finish the update. Now go back to your Terminal/Powershell/Command window and repeat the vagrant up command. It should work fine this time.
https://www.howtoforge.com/setup-a-local-wordpress-development-environment-with-vagrant/
The %d
conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.
There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:
if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
printf("got four numbers\n");
Note that this requires whitespace between the input numbers.
If the id is a single 11-digit number, it's best to treat as a string:
char id[12];
if(scanf("%11s", id) == 1)
{
/* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
Not yet mentioned, though it was the first in my search result: https://github.com/nlohmann/json
Perks listed:
Also, it's under the MIT License.
I'll be honest: I have yet to use it, but through some experience I have a knack for determining when I come across a really well-made c++ library.
Simple answer.
The map
operation can produce a Stream
of Stream
.EX Stream<Stream<Integer>>
flatMap
operation will only produce Stream
of something. EX Stream<Integer>
In my opinion, some of the node.js examples are quite contrived.
You might expect to see something more like this in the real world
// square.js
function Square(width) {
if (!(this instanceof Square)) {
return new Square(width);
}
this.width = width;
};
Square.prototype.area = function area() {
return Math.pow(this.width, 2);
};
module.exports = Square;
Usage
var Square = require("./square");
// you can use `new` keyword
var s = new Square(5);
s.area(); // 25
// or you can skip it!
var s2 = Square(10);
s2.area(); // 100
For the ES6 people
class Square {
constructor(width) {
this.width = width;
}
area() {
return Math.pow(this.width, 2);
}
}
export default Square;
Using it in ES6
import Square from "./square";
// ...
When using a class, you must use the new
keyword to instatiate it. Everything else stays the same.
I know its too late but this solution is working perfect for both .net framework and .net core:
@System.Web.HttpUtility.JavaScriptStringEncode()
Dispatching blocks to the main queue from the main thread can be useful. It gives the main queue a chance to handle other blocks that have been queued so that you're not simply blocking everything else from executing.
For example you could write an essentially single threaded server that nonetheless handles many concurrent connections. As long as no individual block in the queue takes too long the server stays responsive to new requests.
If your program does nothing but spend its whole life responding to events then this can be quite natural. You just set up your event handlers to run on the main queue and then call dispatch_main(), and you may not need to worry about thread safety at all.
Be careful with this. There are a number of different 'contexts' within an HTML document: Inside an element, quoted attribute value, unquoted attribute value, URL attribute, javascript, CSS, etc... You'll need to use a different encoding method for each of these to prevent Cross-Site Scripting (XSS). Check the OWASP XSS Prevention Cheat Sheet for details on each of these contexts. You can find escaping methods for each of these contexts in the OWASP ESAPI library -- https://github.com/ESAPI/esapi-java-legacy.
In Solaris OS I used this command:
$ who am i # Remember to use it with space.
On Linux- Someone already answered this in comments.
$ whoami # Without space
I actually disagree with SLaks. That solution did not work for me. Exception did not happen as expected. But this code worked for me:
if(System.IO.Directory.Exists(path))
{
...
}
I use a polyfill that seem to do a good job.
Box and Cox (1964) suggested a family of transformations designed to reduce nonnormality of the errors in a linear model. In turns out that in doing this, it often reduces non-linearity as well.
Here is a nice summary of the original work and all the work that's been done since: http://www.ime.usp.br/~abe/lista/pdfm9cJKUmFZp.pdf
You will notice, however, that the log-likelihood function governing the selection of the lambda power transform is dependent on the residual sum of squares of an underlying model (no LaTeX on SO -- see the reference), so no transformation can be applied without a model.
A typical application is as follows:
library(MASS)
# generate some data
set.seed(1)
n <- 100
x <- runif(n, 1, 5)
y <- x^3 + rnorm(n)
# run a linear model
m <- lm(y ~ x)
# run the box-cox transformation
bc <- boxcox(y ~ x)
(lambda <- bc$x[which.max(bc$y)])
[1] 0.4242424
powerTransform <- function(y, lambda1, lambda2 = NULL, method = "boxcox") {
boxcoxTrans <- function(x, lam1, lam2 = NULL) {
# if we set lambda2 to zero, it becomes the one parameter transformation
lam2 <- ifelse(is.null(lam2), 0, lam2)
if (lam1 == 0L) {
log(y + lam2)
} else {
(((y + lam2)^lam1) - 1) / lam1
}
}
switch(method
, boxcox = boxcoxTrans(y, lambda1, lambda2)
, tukey = y^lambda1
)
}
# re-run with transformation
mnew <- lm(powerTransform(y, lambda) ~ x)
# QQ-plot
op <- par(pty = "s", mfrow = c(1, 2))
qqnorm(m$residuals); qqline(m$residuals)
qqnorm(mnew$residuals); qqline(mnew$residuals)
par(op)
As you can see this is no magic bullet -- only some data can be effectively transformed (usually a lambda less than -2 or greater than 2 is a sign you should not be using the method). As with any statistical method, use with caution before implementing.
To use the two parameter Box-Cox transformation, use the geoR
package to find the lambdas:
library("geoR")
bc2 <- boxcoxfit(x, y, lambda2 = TRUE)
lambda1 <- bc2$lambda[1]
lambda2 <- bc2$lambda[2]
EDITS: Conflation of Tukey and Box-Cox implementation as pointed out by @Yui-Shiuan fixed.
There are two different ways to implement inserting data from one table to another table.
This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.
----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.
----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
My code to select top 1 from each group
select a.* from #DocumentStatusLogs a where datecreated in( select top 1 datecreated from #DocumentStatusLogs b where a.documentid = b.documentid order by datecreated desc )
If you want to concatenate your "text" in a list:
df.groupby(['name', 'month'], as_index = False).agg({'text': list})
This fiddle has both each
and direct json. http://jsfiddle.net/streethawk707/a9ssja22/.
Below are the two ways of iterating over array. One is with direct json passing and another is naming the json array while passing to content holder.
Eg1: The below example is directly calling json key (data) inside small_data variable.
In html use the below code:
<div id="small-content-placeholder"></div>
The below can be placed in header or body of html:
<script id="small-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>email</th>
</thead>
<tbody>
{{#data}}
<tr>
<td>{{username}}
</td>
<td>{{email}}</td>
</tr>
{{/data}}
</tbody>
</table>
</script>
The below one is on document ready:
var small_source = $("#small-template").html();
var small_template = Handlebars.compile(small_source);
The below is the json:
var small_data = {
data: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
]
};
Finally attach the json to content holder:
$("#small-content-placeholder").html(small_template(small_data));
Eg2: Iteration using each.
Consider the below json.
var big_data = [
{
name: "users1",
details: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]
},
{
name: "users2",
details: [
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]
}
];
While passing the json to content holder just name it in this way:
$("#big-content-placeholder").html(big_template({big_data:big_data}));
And the template looks like :
<script id="big-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>email</th>
</thead>
<tbody>
{{#each big_data}}
<tr>
<td>{{name}}
<ul>
{{#details}}
<li>{{username}}</li>
<li>{{email}}</li>
{{/details}}
</ul>
</td>
<td>{{email}}</td>
</tr>
{{/each}}
</tbody>
</table>
</script>
To: Killercam Thanks for your solutions. I tried the first solution for an hour, but didn't work for me.
I used scripts generate method to move data from SQL Server 2012 to SQL Server 2008 R2 as steps bellow:
In the 2012 SQL Management Studio
It works for me.
Try this:
var mydtn = DateTime.Today;
var myDt = mydtn.Date;return myDt.ToString("d", CultureInfo.GetCultureInfo("en-US"));
I just want to add to the answers that if you want to display a field that is nested in another object, you can use the following syntax
db.collection.find( {}, {{'object.key': true}})
Here key is present inside the object named object
{ "_id" : ObjectId("5d2ef0702385"), "object" : { "key" : "value" } }
Use this property for an Image view such as,
1) android:scaleType="fitXY"
- It means the Images will be stretched to fit all the sides of the parent that is based on your ImageView
!
2) By using above property, it will affect your Image resolution so if you want to maintain the resolution then add a property such as android:scaleType="centerInside"
.
Did you 'export' in your .bashrc?
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"/path/to/library"
In the box is working on being able to convert android projects to iOS
I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...
I think the differences can be put as the following:
In this blog post I write about it in more detail.
Most people advise against using global variables. If you want the same logger class in different modules you can do this
logger.js
module.exports = new logger(customConfig);
foobar.js
var logger = require('./logger');
logger('barfoo');
If you do want a global variable you can do:
global.logger = new logger(customConfig);
try with below on powershell:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
import-module [\path\]XMLHelpers.psm1
Instead of [] put the full path
Ok, so after running in the same issue, I have found a Solution.
This is what I did:
Step 1: Open ESET. Then click on Setup
Step 2: Click on Network protection
Step 3: Click on Troubleshooting wizard
Step 4: Find the Communication 10.0.75.2 (Default docker IP setting) Just check what the IP Range is defined inside your docker settings. Then look for for the IP which resides in that range.
Step 5: Click on the Unblock button, then you should receive this screen.
This solved the issue for myself.
You can then go to the Rules and check the rule that was added.
PS: This is my first post, sorry for any incorrect procedures.
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
On Mac: Eclipse -> Preferences -> Remote Systems -> Files -> click Show Hidden Files.
I think it is faster than regex .
public final boolean containsDigit(String s) {
boolean containsDigit = false;
if (s != null && !s.isEmpty()) {
for (char c : s.toCharArray()) {
if (containsDigit = Character.isDigit(c)) {
break;
}
}
}
return containsDigit;
}
As you know the display
property cannot be animated BUT just by having it in your CSS it overrides the visibility
and opacity
transitions.
The solution...just removed the display
properties.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
nav.main ul li:hover ul {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a>_x000D_
</li>_x000D_
<li><a href="">Dolor</a>_x000D_
</li>_x000D_
<li><a href="">Sit</a>_x000D_
</li>_x000D_
<li><a href="">Amet</a>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_