That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.
The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.
But, I'll take a stab. The original sentence is this:
All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.
X here is a category. Endofunctors are functors from a category to itself (which is usually all Functor
s as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.
And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:
* -> *
with a Functor
instance)join
in Haskell)return
in Haskell)With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.
You can simply append string like:
var worldArg = "world is good"
worldArg += " to live";
It is an error about react-scripts file missing in your node_modules/
directory at the time of installation.
Check your react-script dependency is avaliable or not in package.json
.
If not available then add it manually via:
npm install react-scripts --save
docker ps
docker kill ${containerId}
I find this simpler to understand:
split :: Char -> String -> [String]
split c xs = case break (==c) xs of
(ls, "") -> [ls]
(ls, x:rs) -> ls : split c rs
(out of date) Spreadsheet of device metrics.
SEE ALSO:
Device Metrics - Material Design.
Screen Sizes.
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Galaxy Y 320 x 240 ldpi 0.75 120 427 x 320 4:3 1.3333 427 x 320
? 400 x 240 ldpi 0.75 120 533 x 320 5:3 1.6667 533 x 320
? 432 x 240 ldpi 0.75 120 576 x 320 9:5 1.8000 576 x 320
Galaxy Ace 480 x 320 mdpi 1 160 480 x 320 3:2 1.5000 480 x 320
Nexus S 800 x 480 hdpi 1.5 240 533 x 320 5:3 1.6667 533 x 320
"Galaxy SIII Mini" 800 x 480 hdpi 1.5 240 533 x 320 5:3 1.6667 533 x 320
? 854 x 480 hdpi 1.5 240 569 x 320 427:240 1.7792 569 x 320
Galaxy SIII 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Galaxy Nexus 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
HTC One X 4.7" 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Nexus 5 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 YES 592 x 360
Galaxy S4 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
HTC One 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
Galaxy Note III 5.7" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
HTC One Max 5.9" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
Galaxy Note II 5.6" 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Nexus 4 4.4" 1200 x 768 xhdpi 2 320 600 x 384 25:16 1.5625 YES 552 x 384
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
? 800 x 480 mdpi 1 160 800 x 480 5:3 1.6667 800 x 480
? 854 x 480 mdpi 1 160 854 x 480 427:240 1.7792 854 x 480
Galaxy Mega 6.3" 1280 x 720 hdpi 1.5 240 853 x 480 16:9 1.7778 853 x 480
Kindle Fire HD 7" 1280 x 800 hdpi 1.5 240 853 x 533 8:5 1.6000 853 x 533
Galaxy Mega 5.8" 960 x 540 tvdpi 1.33333 213.333 720 x 405 16:9 1.7778 720 x 405
Sony Xperia Z Ultra 6.4" 1920 x 1080 xhdpi 2 320 960 x 540 16:9 1.7778 960 x 540
Blackberry Priv 5.43" 2560 x 1440 ? 540 ? 16:9 1.7778
Blackberry Passport 4.5" 1440 x 1440 ? 453 ? 1:1 1.0
Kindle Fire (1st & 2nd gen) 7" 1024 x 600 mdpi 1 160 1024 x 600 128:75 1.7067 1024 x 600
Tesco Hudl 7" 1400 x 900 hdpi 1.5 240 933 x 600 14:9 1.5556 933 x 600
Nexus 7 (1st gen/2012) 7" 1280 x 800 tvdpi 1.33333 213.333 960 x 600 8:5 1.6000 YES 912 x 600
Nexus 7 (2nd gen/2013) 7" 1824 x 1200 xhdpi 2 320 912 x 600 38:25 1.5200 YES 864 x 600
Kindle Fire HDX 7" 1920 x 1200 xhdpi 2 320 960 x 600 8:5 1.6000 960 x 600
? 800 x 480 ldpi 0.75 120 1067 x 640 5:3 1.6667 1067 x 640
? 854 x 480 ldpi 0.75 120 1139 x 640 427:240 1.7792 1139 x 640
Kindle Fire HD 8.9" 1920 x 1200 hdpi 1.5 240 1280 x 800 8:5 1.6000 1280 x 800
Kindle Fire HDX 8.9" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Tab 2 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Tab 3 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
ASUS Transformer 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
ASUS Transformer 2 10" 1920 x 1200 hdpi 1.5 240 1280 x 800 8:5 1.6000 1280 x 800
Nexus 10 10" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Note 10.1 10" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Coping with different aspect ratios
The different aspect ratios seen above are (from most square; h/w):
1:1 1.0 <- rare for phone; common for watch
4:3 1.3333 <- matches iPad (when portrait)
3:2 1.5000
38:25 1.5200
14:9 1.5556 <- rare
25:16 1.5625
8:5 1.6000 <- aka 16:10
5:3 1.6667
128:75 1.7067
16:9 1.7778 <- matches iPhone 5-7
427:240 1.7792 <- rare
37:18 2.0555 <- Galaxy S8
If you skip the extreme aspect ratios, that are rarely seen at phone size or larger, all the other devices fit a range from 1.3333 to 1.7778, which conveniently matches the current iPhone/iPad ratios (considering all devices in portrait mode). Note that there are quite a few variations within that range, so if you are creating a small number of fixed aspect-ratio layouts, you will need to decide how to handle the odd "in-between" screens.
Minimum "portrait mode" solution is to support 1.3333, which results in unused space at top and bottom, on all the resolutions with larger aspect ratio.
Most likely, you would instead design it to stretch over the 1.333 to 1.778 range. But sometimes part of your design looks too distorted then.
Advanced layout ideas:
For text, you can design for 1.3333, then increase line spacing for 1.666 - though that will look quite sparse. For graphics, design for an intermediate ratio, so that on some screens it is slightly squashed, on others it is slightly stretched. geometric mean of Sqrt(1333 x 1667) ~= 1491. So you design for 1491 x 1000, which will be stretched/squashed by +-12% when assigned to the extreme cases.
Next refinement is to design layout as a stack of different-height "bands" that each fill the width of the screen. Then determine where you can most pleasingly "stretch-or-squash" a band's height, to adjust for different ratios.
For example, consider imaginary phones with 1333 x 1000 pixels and 1666 x 1000 pixels. Suppose you have two "bands", and your main "band" is square, so it is 1000 x 1000. Second band is 333 x 1000 on one screen, 666 x 1000 on the other - quite a range to design for.
You might decide your main band looks okay altered 10% up-or-down, and squash it 900 x 1000 on the 1333 x 1000 screen, leaving 433 x 1000. Then stretch it to 1100 x 1000 on 1666 x 1000 screen, leaving 566 x 1000. So your second band now needs to adjust over only 433 to 566, which has geometric mean of Sqrt(433 x 566) ~= 495. So you design for 495 x 1000, which will be stretched/squashed by +-14% when assigned to the extreme cases.
Found this here ...
Problem: An XML parser returns the error “xmlParseEntityRef: noname”
Cause: There is a stray ‘&’ (ampersand character) somewhere in the XML text eg. some text & some more text
Solution:
- Solution 1: Remove the ampersand.
- Solution 2: Encode the ampersand (that is replace the
&
character with&
). Remember to Decode when reading the XML text.- Solution 3: Use CDATA sections (text inside a CDATA section will be ignored by the parser.) eg. <![CDATA[some text & some more text]]>
Note: ‘&’ ‘<' '>‘ will all give problems if not handled correctly.
The following example for complex numbers should be self explanatory including the error message at the end
>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y
Traceback (most recent call last):
File "<pyshell#149>", line 1, in <module>
print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>>
Try:
java -cp . Echo "hello"
Assuming that you compiled with:
javac Echo.java
Then there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions )
If that's the case and listing the contents of your dir displays:
Echo.java
Echo.class
Then any of this may work:
java -cp . Echo "hello"
or
SET CLASSPATH=%CLASSPATH;.
java Echo "hello"
And later as Fredrik points out you'll get another error message like.
Exception in thread "main" java.lang.NoSuchMethodError: main
When that happens, go and read his answer :)
Maybe you have run into this problem: net::ERR_INSECURE_RESPONSE
You need to check the encryption algorithms supported by your server. For example for apache you can configure the cipher suite this way: cipher suite.
Which version of chrome are you running and what is the server serving your APIs?
Disagree with the suggested answer. The short answer is: NO.
The purpose of the primary key is to uniquely identify a row on the table in order to form a relationship with another table. Traditionally, an auto-incremented integer value is used for this purpose, but there are variations to this.
There are cases though, for example logging time-series data, where the existence of a such key is simply not needed and just takes up memory. Making a row unique is simply ...not required!
A small example: Table A: LogData
Columns: DateAndTime, UserId, AttribA, AttribB, AttribC etc...
No Primary Key needed.
Table B: User
Columns: Id, FirstName, LastName etc.
Primary Key (Id) needed in order to be used as a "foreign key" to LogData table.
From Tomcat Documentation
maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.
maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.
If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the
libncurses5:i386
,libstdc++6:i386
, andzlib1g:i386
packages usingapt-get
:
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
Procedural generation is used heavily in the demoscene to create complex graphics in a small executable. Will Wright even said that he was inspired by the demoscene while making Spore. That may be your best place to start.
This code is working fine for me,
var a = serializer.Deserialize<List<Entity>>(json);
You need to set permissions within SSRS in two places to give yourself initial access. The set-up program only gives access to Builtin\Administrators, to gain access in order to do this you need to right click you browser link and choose Run as administrator.
Swift 4 label extension. Creating NSMutableAttributedString before passing into function in case there are extra attributes required for the attributed text.
extension UILabel {
func setLineHeightMultiple(to height: CGFloat, withAttributedText attributedText: NSMutableAttributedString) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 1.0
paragraphStyle.lineHeightMultiple = height
paragraphStyle.alignment = textAlignment
attributedText.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedText.length - 1))
self.attributedText = attributedText
}
}
Add following at start of cell and run it:
from IPython.display import clear_output
clear_output(wait=True)
var result = Math.round(original*100)/100;
The specifics, in case the code isn't self-explanatory.
edit: ...or just use toFixed
, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)
No, prior to Oracle version 12.2, identifiers are not allowed to exceed 30 characters in length. See the Oracle SQL Language Reference.
However, from version 12.2 they can be up to 128 bytes long. (Note: bytes, not characters).
This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/
Look at the following class, do you know which one gets executed first?
public class Foo {
//instance variable initializer
String s = "abc";
//constructor
public Foo() {
System.out.println("constructor called");
}
//static initializer
static {
System.out.println("static initializer called");
}
//instance initializer
{
System.out.println("instance initializer called");
}
public static void main(String[] args) {
new Foo();
new Foo();
}
}
Output:
static initializer called
instance initializer called
constructor called
instance initializer called
constructor called
The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0
. This can make it more obvious to understand.
Instead of
int b = 0
, you could write
int b;
b = 0;
Therefore, instance initializers and instance variable initializers are pretty much the same.
The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:
Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.
With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)
Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)
Thanks to Derhein.
Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.
$('.update-cart').click(function(e) {
updateCartWidget();
e.stopPropagation();
e.preventDefault();
});
$('.update-cart').click(function() {
updateCartWidget();
return false;
});
The following methods achieve the exact same thing.
u
means unsigned
, so ulong
is a large number without sign. You can store a bigger value in ulong
than long
, but no negative numbers allowed.
A long
value is stored in 64-bit,with its first digit to show if it's a positive/negative number. while ulong
is also 64-bit, with all 64 bit to store the number. so the maximum of ulong is 2(64)-1, while long is 2(63)-1.
You can try this:
requestPermissions(permissions, PERMISSIONS_CODE);
If you are calling this code from a fragment it has it's own requestPermissions method. I believe the problem is that you are calling static method.
Pro Tip if you want the onRequestPermissionsResult()
in a fragment:
FragmentCompat.requestPermissions(Fragment fragment, String[] permissions, int requestCode)
It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged()
you have full control of the Views generation and rendering.
Take a look at these tutorials
It's creating a size 0
bitfield if the condition is false, but a size -1
(-!!1
) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1
bitfield is created, of course).
I was having a similar problem. (No problems training with GradientDescent optimizer, but error raised when using to Adam Optimizer, or any other optimizer with its own variables)
Changing to an interactive session solved this problem for me.
sess = tf.Session()
into
sess = tf.InteractiveSession()
Try Fragment, if you don't want any of above.
In your case, we can write
import React, {useState, Fragment} from 'react'
const thisIsMyCopy = Fragment('<p>copy copy copy <strong>strong copy</strong></p>')
render: function() {
return (
<div className="content">{thisIsMyCopy}</div>
);
}
If you using hook want to set it in a state somewhere with any condition
const [thisIsMyCopy, setThisIsMyCopy] = useState(<Fragment><p>copy copy copy <strong>strong copy</strong></p></Fragment>);
Not sure if it still necessary. But the following solution should work with iterators and does not require count
.
<?php
foreach_first_last(array(), function ($key, $value, $step, $first, $last) {
echo intval($first), ' ', intval($last), ' ', $step, ' ', $value, PHP_EOL;
});
foreach_first_last(array('aa'), function ($key, $value, $step, $first, $last) {
echo intval($first), ' ', intval($last), ' ', $step, ' ', $value, PHP_EOL;
});
echo PHP_EOL;
foreach_first_last(array('aa', 'bb', 'cc'), function ($key, $value, $step, $first, $last) {
echo intval($first), ' ', intval($last), ' ', $step, ' ', $value, PHP_EOL;
});
echo PHP_EOL;
function foreach_first_last($array, $cb)
{
$next = false;
$current = false;
reset($array);
for ($step = 0; true; ++$step) {
$current = $next;
$next = each($array);
$last = ($next === false || $next === null);
if ($step > 0) {
$first = $step == 1;
list ($key, $value) = $current;
if (call_user_func($cb, $key, $value, $step, $first, $last) === false) {
break;
}
}
if ($last) {
break;
}
}
}
You don't give a reproducible example but your warning message tells you exactly what the problem is.
memb
only has a length of 10. I'm guessing the length of dih_y2$MemberID
isn't a multiple of 10. When using ==
, R spits out a warning if it isn't a multiple to let you know that it's probably not doing what you're expecting it to do. ==
does element-wise checking for equality. I suspect what you want to do is find which of the elements of dih_y2$MemberID
are also in the vector memb
. To do this you would want to use the %in%
operator.
dih_col <- which(dih_y2$MemeberID %in% memb)
Just pass it in, like this:
Game(list_a, list_b, Rule1)
and then your Game function could look something like this (still pseudocode):
def Game(listA, listB, rules=None):
if rules:
# do something useful
# ...
result = rules(variable) # this is how you can call your rule
else:
# do something useful without rules
Ran into this similar issue while using iframe to logout of sub sites with different domains. The solution I used was to load the iframe first, then update the source after the frame is loaded.
var frame = document.createElement('iframe');_x000D_
frame.style.display = 'none';_x000D_
frame.setAttribute('src', 'about:blank');_x000D_
document.body.appendChild(frame);_x000D_
frame.addEventListener('load', () => {_x000D_
frame.setAttribute('src', url);_x000D_
});
_x000D_
your form is missing the method...
<form name="registrationform" action="register.php" method="post"> //here
anywyas to check the posted data u can use isset()..
Determine if a variable is set and is not NULL
if(!isset($firstname) || trim($firstname) == '')
{
echo "You did not fill out the required fields.";
}
jQuery.now()
Returns: Number
Description: Return a number representing the current time.
This method does not accept any arguments.
The $.now()
method is a shorthand for the number returned by the expression (new Date).getTime()
.
http://api.jquery.com/jQuery.now/
It's simple to use Javascript:
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
console.log(time);
To answer your question, let's assume that you are interested in a specific angular version and NOT in a specific angular-cli version (angular-cli is just a tool after all).
A reasonnable move is to keep your angular-cli version alligned with your angular version, otherwise you risk to stumble into incompatibilities issues. So getting the correct angular-cli version will lead you to getting the desired angular version.
From that assumption, your question is not about angular-cli, but about npm.
Here is the way to go:
[STEP 0 - OPTIONAL] If you're not sure of the angular-cli version installed in your environment, uninstall it.
npm uninstall -g @angular/cli
Then, run (--force flag might be required)
npm cache clean
or, if you're using npm > 5.
npm cache verify
[STEP 1] Install an angular-cli specific version
npm install -g @angular/[email protected]
[STEP 2] Create a project
ng new you-app-name
The resulting white app will be created in the desired angular version.
NOTE: I have not found any page displaying the compatibility matrix of angular and angular-cli. So I guess the only way to know what angular-cli version should be installed is to try various versions, create a new project and checkout the package.json
to see which angular version is used.
angular versions changelog Here is the changelog from github reposition, where you can check available versions and the differences.
Hope it helps
Could this do for you? Check my JSFiddle
And the code:
HTML
<div class="container">
<div class="div1">Div 1</div>
<div class="div2">Div 2</div>
</div>
CSS
div.container {
background-color: #FF0000;
margin: auto;
width: 304px;
}
div.div1 {
border: 1px solid #000;
float: left;
width: 150px;
}
div.div2 {
border: 1px solid red;
float: left;
width: 150px;
}
Line numbers are printed with grep -n
:
grep -n pattern file.txt
To get only the line number (without the matching line), one may use cut
:
grep -n pattern file.txt | cut -d : -f 1
Lines not containing a pattern are printed with grep -v
:
grep -v pattern file.txt
$("#reset").on("click", function () {
$('#my_select').prop('selectedIndex',0);
});
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
In addition to the syntactic and operational properties, there's also a semantical difference.
Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.
Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.
Even if they were exactly the same thing (syntactically and in the IL code) there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way (which doesn't mean I like to have the same code twice).
Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.
JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP
is an array and contains elements with a value
property.
see this is pure css bases dropdown menu:-
HTML
<ul id="menu">
<li><a href="">Home</a></li>
<li><a href="">About Us</a>
<ul>
<li><a href="">The Team</a></li>
<li><a href="">History</a></li>
<li><a href="">Vision</a></li>
</ul>
</li>
<li><a href="">Products</a>
<ul>
<li><a href="">Cozy Couch</a></li>
<li><a href="">Great Table</a></li>
<li><a href="">Small Chair</a></li>
<li><a href="">Shiny Shelf</a></li>
<li><a href="">Invisible Nothing</a></li>
</ul>
</li>
<li><a href="">Contact</a>
<ul>
<li><a href="">Online</a></li>
<li><a href="">Right Here</a></li>
<li><a href="">Somewhere Else</a></li>
</ul>
</li>
</ul>
CSS
ul
{
font-family: Arial, Verdana;
font-size: 14px;
margin: 0;
padding: 0;
list-style: none;
}
ul li
{
display: block;
position: relative;
float: left;
}
li ul
{
display: none;
}
ul li a
{
display: block;
text-decoration: none;
color: #ffffff;
border-top: 1px solid #ffffff;
padding: 5px 15px 5px 15px;
background: #2C5463;
margin-left: 1px;
white-space: nowrap;
}
ul li a:hover
{
background: #617F8A;
}
li:hover ul
{
display: block;
position: absolute;
}
li:hover li
{
float: none;
font-size: 11px;
}
li:hover a
{
background: #617F8A;
}
li:hover li a:hover
{
background: #95A9B1;
}
see the demo:- http://jsfiddle.net/XPE3w/7/
I'm using ORMLite and below code worked for me
public class DatabaseProvider extends OrmLiteSqliteOpenHelper {
private static final String DatabaseName = "DatabaseName";
private static final int DatabaseVersion = 1;
private final Context ProvidedContext;
public DatabaseProvider(Context context) {
super(context, DatabaseName, null, DatabaseVersion);
this.ProvidedContext= context;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean databaseCopied = preferences.getBoolean("DatabaseCopied", false);
if (databaseCopied) {
//Do Nothing
} else {
CopyDatabase();
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("DatabaseCopied", true);
editor.commit();
}
}
private String DatabasePath() {
return "/data/data/" + ProvidedContext.getPackageName() + "/databases/";
}
private void CopyDatabase() {
try {
CopyDatabaseInternal();
} catch (IOException e) {
e.printStackTrace();
}
}
private File ExtractAssetsZip(String zipFileName) {
InputStream inputStream;
ZipInputStream zipInputStream;
File tempFolder;
do {
tempFolder = null;
tempFolder = new File(ProvidedContext.getCacheDir() + "/extracted-" + System.currentTimeMillis() + "/");
} while (tempFolder.exists());
tempFolder.mkdirs();
try {
String filename;
inputStream = ProvidedContext.getAssets().open(zipFileName);
zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
ZipEntry zipEntry;
byte[] buffer = new byte[1024];
int count;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
filename = zipEntry.getName();
if (zipEntry.isDirectory()) {
File fmd = new File(tempFolder.getAbsolutePath() + "/" + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fileOutputStream = new FileOutputStream(tempFolder.getAbsolutePath() + "/" + filename);
while ((count = zipInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.close();
zipInputStream.closeEntry();
}
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return tempFolder;
}
private void CopyDatabaseInternal() throws IOException {
File extractedPath = ExtractAssetsZip(DatabaseName + ".zip");
String databaseFile = "";
for (File innerFile : extractedPath.listFiles()) {
databaseFile = innerFile.getAbsolutePath();
break;
}
if (databaseFile == null || databaseFile.length() ==0 )
throw new RuntimeException("databaseFile is empty");
InputStream inputStream = new FileInputStream(databaseFile);
String outFileName = DatabasePath() + DatabaseName;
File destinationPath = new File(DatabasePath());
if (!destinationPath.exists())
destinationPath.mkdirs();
File destinationFile = new File(outFileName);
if (!destinationFile.exists())
destinationFile.createNewFile();
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
inputStream.close();
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int fromVersion, int toVersion) {
}
}
Please note, The code extracts database file from a zip file in assets
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
Use this....
string popupScript = "<script language=JavaScript>";
popupScript += "alert('Please enter valid Email Id');";
popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);
Try to use it via [ngClass]
property:
<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
(click)="toggle(!isOn)">
Click me!
</div>`,
BigInteger.valueOf(1695609641).toByteArray()
Here's a snippet I used - with plain SimpleDateFormat
. Hope somebody else may benefit from it:
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") {
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos) {
StringBuffer toFix = super.format(date, toAppendTo, pos);
return toFix.insert(toFix.length()-2, ':');
};
};
// Usage:
System.out.println(dateFormat.format(new Date()));
}
Output:
- Usual Output.........: 2013-06-14T10:54:07-0200
- This snippet's Output: 2013-06-14T10:54:07-02:00
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
// Usage:
System.out.println(dateFormat2.format(new Date()));
Output:
- This pattern's output: 2013-06-14T10:54:07-02:00
See the docs for that.
This worked for me:
$('.class1[class~="class2"]').append('something');
I prefer to use this extension method:
public static class Extensions
{
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)
=> self.Select((item, index) => (item, index));
}
Source:
https://stackoverflow.com/a/39997157/3850405
Razor:
@using Project.Shared.Helpers
@foreach (var (item, index) in collection.WithIndex())
{
<p>
Name: @item.Name Index: @index
</p>
}
I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.
Try this...
var str = 'f 34 545 323 12345 54321 123456',
matches = str.match(/\b\d{5}\b/g);
console.log(matches); // ["12345", "54321"]
The word boundary \b
is your friend here.
My regex will get a number like this 12345
, but not like a12345
. The other answers provide great regexes if you require the latter.
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "USER_ID")
Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> receiver;
}
public class Notification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "NOTIFICATION_ID")
Long notificationId;
@Column(name = "TEXT")
String text;
@Column(name = "ALERT_STATUS")
@Enumerated(EnumType.STRING)
AlertStatus alertStatus = AlertStatus.NEW;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SENDER_ID")
@JsonIgnore
User sender;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RECEIVER_ID")
@JsonIgnore
User receiver;
}
What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..
User model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
List<Notification> receiver;
Notification model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> **sender**;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> **receiver**;
I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.
This worked for me after struggling a bit
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
If you want to load the view from the same controller you are on:
if ($validator->fails()) {
return self::index($request)->withErrors($validator->errors());
}
And if you want to quickly display all errors but have a bit more control:
@if ($errors->any())
@foreach ($errors->all() as $error)
<div>{{$error}}</div>
@endforeach
@endif
Try to declare UseHttpGet over your method.
[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
return "Hello World";
}
Add these two like of code work like a charm for any view like Button, Linear Layout, or CardView Just put these two lines and see the magic...
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp
You would use it like this:
var date = Date.parse(dat1);
Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.
The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.
CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx
Another vote for using web.config or app.config. The config files are a good place for constants like connection strings, etc. I prefer not to have to look at the source to view or modify these types of things. A static class which reads these constants from a .config file might be a good compromise, as it will let your application access these resources as though they were defined in code, but still give you the flexibility of having them in an easily viewable/editable space.
System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();
Substitute the right encoding above: e.g.
System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();
In ES6, just one line.
const arr = arr.filter(item => item.key !== "some value");
:)
Or do the following:
...
Integer[] integerArray = new Integer[integerList.size()];
integerList.toArray(integerArray);
return integerArray;
}
Try this: If your collection was 'example'
db.example.update({}, {$unset: {words:1}}, false, true);
Refer this:
http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset
UPDATE:
The above link no longer covers '$unset'ing. Be sure to add {multi: true}
if you want to remove this field from all of the documents in the collection; otherwise, it will only remove it from the first document it finds that matches. See this for updated documentation:
https://docs.mongodb.com/manual/reference/operator/update/unset/
Example:
db.example.update({}, {$unset: {words:1}} , {multi: true});
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text("Login / Signup"),
),
body: new Container(
child: new Center(
child: ListView(
//mainAxisAlignment: MainAxisAlignment.center,
scrollDirection: Axis.vertical,
children: <Widget>[
new TextField(
decoration: new InputDecoration(
hintText: "E M A I L A D D R E S S"
),
),
new Padding(padding: new EdgeInsets.all(15.00)),
new TextField(obscureText: true,
decoration: new InputDecoration(
hintText: "P A S S W O R D"
),
),
new Padding(padding: new EdgeInsets.all(15.00)),
new TextField(decoration: new InputDecoration(
hintText: "U S E R N A M E"
),),
new RaisedButton(onPressed: null,
child: new Text("SIGNUP"),),
new Padding(padding: new EdgeInsets.all(15.00)),
new RaisedButton(onPressed: null,
child: new Text("LOGIN"),),
new Padding(padding: new EdgeInsets.all(15.00)),
new ListView(scrollDirection: Axis.horizontal,
children: <Widget>[
new RaisedButton(onPressed: null,
child: new Text("Facebook"),),
new Padding(padding: new EdgeInsets.all(5.00)),
new RaisedButton(onPressed: null,
child: new Text("Google"),)
],)
],
),
),
margin: new EdgeInsets.all(15.00),
),
),
);
The way I solved my problem is to keep the count of the number of objects iterated over, so far. I wanted to iterate over a set using calls to an instance method. Since I knew the length of the set, and the number of items counted so far, I effectively had an hasNext
method.
A simple version of my code:
class Iterator:
# s is a string, say
def __init__(self, s):
self.s = set(list(s))
self.done = False
self.iter = iter(s)
self.charCount = 0
def next(self):
if self.done:
return None
self.char = next(self.iter)
self.charCount += 1
self.done = (self.charCount < len(self.s))
return self.char
def hasMore(self):
return not self.done
Of course, the example is a toy one, but you get the idea. This won't work in cases where there is no way to get the length of the iterable, like a generator etc.
Ok this is my take on the question. I believe it's the most concise solution that modifies the string in place (free
will work) and avoids any UB. For small strings, it's probably faster than a solution involving memmove.
void stripWS_LT(char *str)
{
char *a = str, *b = str;
while (isspace((unsigned char)*a)) a++;
while (*b = *a++) b++;
while (b > str && isspace((unsigned char)*--b)) *b = 0;
}
The CSS solution for Angular Bootstrap is
::ng-deep .tooltip-inner {
white-space: pre-wrap;
}
No need to use a parent element or class selector if you don't need to restrict it's use. Copy/Pasta, and this rule will apply to all sub-components
Try wrapping the image with a linearlayout, and set it's background to the border color you want around the text. Then set the padding on the textview to be the thickness you want for your border.
From API version 19 it is possible to call ActivityManager.clearApplicationUserData().
((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();
Microsoft Visio 2013 Standard Edition does not provide UML shapes, you have to upgrade to Microsoft Visio 2013 Professional.
As Shimmy has pointed out, using Last() can be a performance problem, for instance if your collection is the live result of a LINQ expression. To prevent multiple iterations, you could use a "ForEach" extension method like this:
var elements = new[] { "A", "B", "C" };
elements.ForEach((element, info) => {
if (!info.IsLast) {
Console.WriteLine(element);
} else {
Console.WriteLine("Last one: " + element);
}
});
The extension method looks like this (as an added bonus, it will also tell you the index and if you're looking at the first element):
public static class EnumerableExtensions {
public delegate void ElementAction<in T>(T element, ElementInfo info);
public static void ForEach<T>(this IEnumerable<T> elements, ElementAction<T> action) {
using (IEnumerator<T> enumerator = elements.GetEnumerator())
{
bool isFirst = true;
bool hasNext = enumerator.MoveNext();
int index = 0;
while (hasNext)
{
T current = enumerator.Current;
hasNext = enumerator.MoveNext();
action(current, new ElementInfo(index, isFirst, !hasNext));
isFirst = false;
index++;
}
}
}
public struct ElementInfo {
public ElementInfo(int index, bool isFirst, bool isLast)
: this() {
Index = index;
IsFirst = isFirst;
IsLast = isLast;
}
public int Index { get; private set; }
public bool IsFirst { get; private set; }
public bool IsLast { get; private set; }
}
}
Once you have your Context and know the name of the database, use:
context.deleteDatabase(DATABASE_NAME);
When this line gets run, the database should be deleted.
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
You can do this by changing the php.ini file and add the following
display_errors = on
display_startup_errors = on
OR you can also use the following code as this always works for me
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
I have used the following method in a project and it's working successfully.
private string identifier(string wmiClass, string wmiProperty)
//Return a hardware identifier
{
string result = "";
System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
return result;
}
you can call the above method as mentioned below,
string modelNo = identifier("Win32_DiskDrive", "Model");
string manufatureID = identifier("Win32_DiskDrive", "Manufacturer");
string signature = identifier("Win32_DiskDrive", "Signature");
string totalHeads = identifier("Win32_DiskDrive", "TotalHeads");
If you need a unique identifier, use a combination of these IDs.
You need to add that folder to your Windows Path:
https://docs.python.org/2/using/windows.html Taken from this question.
Try command + t
.
It works for me.
> tmp = paste("GAD", "AB", sep = ",")
> tmp
[1] "GAD,AB"
I found this from Google by searching for R concatenate strings: http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html
You can also use the direct deploy method using curl. You don't need a pom for your file for it but it will not be generated as well so if you want one, you will have to upload it separately.
Here is the command:
version=1.2.3
artefact="myartefact"
repoId=yourrepository
groupId=org.myorg
REPO_URL=http://localhost:8081/nexus
curl -u nexususername:nexuspassword --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artefact/$version/$artefact-$version.tgz
On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:
view.settings().get('font_face')
You will find your default font.
Instead of passing functions or querying it on the controller, I think what you need is relationships on models since these are related tables on your database.
If based on your structure, input_details and products are related you should put relationship definition on your models like this:
public class InputDetail(){
protected $table = "input_details";
....//other code
public function product(){
return $this->hasOne('App\Product');
}
}
then in your view you'll just have to say:
<p>{{ $input_details->product->name }}</p>
More simpler that way. It is also the best practice that controllers should only do business logic for the current resource. For more info on how to do this just go to the docs: https://laravel.com/docs/5.0/eloquent#relationships
Kind of a trick realty... Even references are passed by value in Java, hence a change to the reference itself being scoped at the called function level. The compiler and/or JVM will often turn a value type into a reference.
Here is the Swift version of code to send SMS in iOS. Please noted that it only works in real devices. Code tested in iOS 7+. You can read more here.
1) Create a new Class which inherits MFMessageComposeViewControllerDelegate and NSObject:
import Foundation
import MessageUI
class MessageComposer: NSObject, MFMessageComposeViewControllerDelegate {
// A wrapper function to indicate whether or not a text message can be sent from the user's device
func canSendText() -> Bool {
return MFMessageComposeViewController.canSendText()
}
// Configures and returns a MFMessageComposeViewController instance
func configuredMessageComposeViewController(textMessageRecipients:[String] ,textBody body:String) -> MFMessageComposeViewController {
let messageComposeVC = MFMessageComposeViewController()
messageComposeVC.messageComposeDelegate = self // Make sure to set this property to self, so that the controller can be dismissed!
messageComposeVC.recipients = textMessageRecipients
messageComposeVC.body = body
return messageComposeVC
}
// MFMessageComposeViewControllerDelegate callback - dismisses the view controller when the user is finished with it
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
2) How to use this class:
func openMessageComposerHelper(sender:AnyObject ,withIndexPath indexPath: NSIndexPath) {
var recipients = [String]()
//modify your recipients here
if (messageComposer.canSendText()) {
println("can send text")
// Obtain a configured MFMessageComposeViewController
let body = Utility.createInvitationMessageText()
let messageComposeVC = messageComposer.configuredMessageComposeViewController(recipients, textBody: body)
// Present the configured MFMessageComposeViewController instance
// Note that the dismissal of the VC will be handled by the messageComposer instance,
// since it implements the appropriate delegate call-back
presentViewController(messageComposeVC, animated: true, completion: nil)
} else {
// Let the user know if his/her device isn't able to send text messages
self.displayAlerViewWithTitle("Cannot Send Text Message", andMessage: "Your device is not able to send text messages.")
}
}
torch.Tensor.view()
Simply put, torch.Tensor.view()
which is inspired by numpy.ndarray.reshape()
or numpy.reshape()
, creates a new view of the tensor, as long as the new shape is compatible with the shape of the original tensor.
Let's understand this in detail using a concrete example.
In [43]: t = torch.arange(18)
In [44]: t
Out[44]:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])
With this tensor t
of shape (18,)
, new views can only be created for the following shapes:
(1, 18)
or equivalently (1, -1)
or (-1, 18)
(2, 9)
or equivalently (2, -1)
or (-1, 9)
(3, 6)
or equivalently (3, -1)
or (-1, 6)
(6, 3)
or equivalently (6, -1)
or (-1, 3)
(9, 2)
or equivalently (9, -1)
or (-1, 2)
(18, 1)
or equivalently (18, -1)
or (-1, 1)
As we can already observe from the above shape tuples, the multiplication of the elements of the shape tuple (e.g. 2*9
, 3*6
etc.) must always be equal to the total number of elements in the original tensor (18
in our example).
Another thing to observe is that we used a -1
in one of the places in each of the shape tuples. By using a -1
, we are being lazy in doing the computation ourselves and rather delegate the task to PyTorch to do calculation of that value for the shape when it creates the new view. One important thing to note is that we can only use a single -1
in the shape tuple. The remaining values should be explicitly supplied by us. Else PyTorch will complain by throwing a RuntimeError
:
RuntimeError: only one dimension can be inferred
So, with all of the above mentioned shapes, PyTorch will always return a new view of the original tensor t
. This basically means that it just changes the stride information of the tensor for each of the new views that are requested.
Below are some examples illustrating how the strides of the tensors are changed with each new view.
# stride of our original tensor `t`
In [53]: t.stride()
Out[53]: (1,)
Now, we will see the strides for the new views:
# shape (1, 18)
In [54]: t1 = t.view(1, -1)
# stride tensor `t1` with shape (1, 18)
In [55]: t1.stride()
Out[55]: (18, 1)
# shape (2, 9)
In [56]: t2 = t.view(2, -1)
# stride of tensor `t2` with shape (2, 9)
In [57]: t2.stride()
Out[57]: (9, 1)
# shape (3, 6)
In [59]: t3 = t.view(3, -1)
# stride of tensor `t3` with shape (3, 6)
In [60]: t3.stride()
Out[60]: (6, 1)
# shape (6, 3)
In [62]: t4 = t.view(6,-1)
# stride of tensor `t4` with shape (6, 3)
In [63]: t4.stride()
Out[63]: (3, 1)
# shape (9, 2)
In [65]: t5 = t.view(9, -1)
# stride of tensor `t5` with shape (9, 2)
In [66]: t5.stride()
Out[66]: (2, 1)
# shape (18, 1)
In [68]: t6 = t.view(18, -1)
# stride of tensor `t6` with shape (18, 1)
In [69]: t6.stride()
Out[69]: (1, 1)
So that's the magic of the view()
function. It just changes the strides of the (original) tensor for each of the new views, as long as the shape of the new view is compatible with the original shape.
Another interesting thing one might observe from the strides tuples is that the value of the element in the 0th position is equal to the value of the element in the 1st position of the shape tuple.
In [74]: t3.shape
Out[74]: torch.Size([3, 6])
|
In [75]: t3.stride() |
Out[75]: (6, 1) |
|_____________|
This is because:
In [76]: t3
Out[76]:
tensor([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]])
the stride (6, 1)
says that to go from one element to the next element along the 0th dimension, we have to jump or take 6 steps. (i.e. to go from 0
to 6
, one has to take 6 steps.) But to go from one element to the next element in the 1st dimension, we just need only one step (for e.g. to go from 2
to 3
).
Thus, the strides information is at the heart of how the elements are accessed from memory for performing the computation.
This function would return a view and is exactly the same as using torch.Tensor.view()
as long as the new shape is compatible with the shape of the original tensor. Otherwise, it will return a copy.
However, the notes of torch.reshape()
warns that:
contiguous inputs and inputs with compatible strides can be reshaped without copying, but one should not depend on the copying vs. viewing behavior.
One thing to think about is: Do you have your WCF completely uncoupled from the WindowsService (WS)? A WS is painful because you don't have a lot of control or visibility to them. I try to mitigate this by having all of my non-WS stuff in their own classes so they can be tested independently of the host WS. Using this approach might help you eliminate anything that is happening with the WS runtime vs. your service in particular.
John is likely correct that it is a .config file problem. WCF will always look for the execution context .config. So if you are hosting your WCF in different execution contexts (that is, test with a console application, and deploy with a WS), you need to make sure you have WCF configuration data moved over to the proper .config file. But the underlying issue to me is that you don't know what the problem is because the WS goo gets in the way. If you haven't refactored to that yet so that you can run your service in any context (that is, unit test or console), then I'd sugget doing so. If you spun your service up in a unit test, it would likely fail the same way that you are seeing with the WS which is much easier to debug rather than attempting to do so with the yucky WS plumbing.
If you're happy you know what you're doing and can accept the portability problems, on GCC for example you can disable the warning on the command line:
-Wno-multichar
I use this for my own apps to work with AVI and MP4 file headers for similar reasons to you.
With the new @SpringBootTest
annotation, I took this answer and modified it to use profiles with a @SpringBootApplication
configuration class. The @Profile
annotation is necessary so that this class is only picked up during the specific integration tests that need this, as other test configurations do different component scanning.
Here is the configuration class:
@Profile("specific-profile")
@SpringBootApplication(scanBasePackages={"com.myco.package1", "com.myco.package2"})
public class SpecificTestConfig {
}
Then, the test class references this configuration class:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SpecificTestConfig.class })
@ActiveProfiles({"specific-profile"})
public class MyTest {
}
A function written in Kotlin:
/**
* Delete the notification
*/
fun delete(context: Context, notificationId: Int) =
with(NotificationManagerCompat.from(context)) {
cancel(notificationId)
}
Or shorter:
fun delete(context: Context, notificationId: Int) = NotificationManagerCompat.from(context).cancel(notificationId)
You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:
$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);
The pattern can also be expressed as /[^\d,.]+/
You can use the System.Diagnostics.Debug.Write
or System.Runtime.InteropServices
method to write messages to the Output Window.
I had this problem too. I was trying to run an old 32-bit dll in a 64 bit system. I got it working by copying the .dll to the C:\Windows\SysWoW64\ directory and running this:
%systemroot%\SysWoW64\regsvr32 "C:\Windows\SysWoW64\thenameofyourdll.dll"
And also enabling IIS to run 32 bit apps
For authoritative information about these files, check out the man pages, run the command on your terminal.
$ man stdout
But for a simple answer, each file is for:
stdout for a stream out
stdin for a stream input
stderr for printing errors or log messages.
Each unix program has each one of those streams.
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
Make sure your project defines a module and you have given a name to the module. Then rebuild, and Xcode will create the -Swift.h
header file and you will be able to import.
You can set module definition and module name in your project settings.
If you want first 2 letters and last 2 letters of a string then you can use the following code:
name = "India"
name[0:2]="In"
names[-2:]="ia"
As mentioned in Alain Beauvois's answer, and now (Q4 2013) better explained in
Copy the URL from GitHub and select in Eclipse from the menu the
File ? Import ? Git ? Projects from Git
If the Git repo isn't cloned yet:
In> order to checkout a remote project, you will have to clone its repository first.
Open the Eclipse Import wizard (e.g. File => Import
), select Git => Projects
from Git and click Next
.
Select “URI
” and click Next
.
Now you will have to enter the repository’s location and connection data. Entering the URI will automatically fill some fields. Complete any other required fields and hit Next
. If you use GitHub, you can copy the URI from the web page.
Select all branches you wish to clone and hit Next again.
Hit the Clone… button to open another wizard for cloning Git repositories.
Original answer (July 2011)
First, if your "Working Directory" is C:\Users
, that is odd, since it would mean you have cloned the GitHub repo directly within C:\Users (i.e. you have a .git
directory in C:\Users
)
Usually, you would clone a GitHub repo in "any directory of your choice\theGitHubRepoName
".
As described in the EGit user Manual page:
In any case (unless you create a "bare" Repository, but that's not discussed here), the new Repository is essentially a folder on the local hard disk which contains the "working directory" and the metadata folder.
The metadata folder is a dedicated child folder named ".git
" and often referred to as ".git-folder
". It contains the actual repository (i.e. the Commits, the References, the logs and such).The metadata folder is totally transparent to the Git client, while the working directory is used to expose the currently checked out Repository content as files for tools and editors.
Typically, if these files are to be used in Eclipse, they must be imported into the Eclipse workspace in one way or another. In order to do so, the easiest way would be to check in .project files from which the "Import Existing Projects" wizard can create the projects easily. Thus in most cases, the structure of a Repository containing Eclipse projects would look similar to something like this:
See also the Using EGit with Github section.
My working directory is now
c:\users\projectname\.git
You should have the content of that repo checked out in c:\users\projectname
(in other words, you should have more than just the .git
).
So then I try to import the project using the eclipse "import" option.
When I try to import selecting the option "Use the new projects wizard", the source code is not imported.
That is normal.
If I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project.
Again normal.
When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?
No, that would only create an empty project.
If that project is created in c:\users\projectname
, you can then declare the eisting source directory in that project.
Since it is defined in the same working directory than the Git repo, that project should then appear as "versioned".
You could also use the "Import existing project" option, if your GitHub repo had versioned the .project
and .classpath
file, but that may not be the case here.
To Remove Special character
String t2 = "!@#$%^&*()-';,./?><+abdd";
t2 = t2.replaceAll("\\W+","");
Output will be : abdd.
This works perfectly.
There are a few things you can try with this, seems to happen alot and the solution varies for everyone it seems.
If you are still using the IIS virtual directory make sure its pointed to the correct directory and also check the ASP.NET version it is set to, make sure it is set to ASP.NET 2.0.
Clear out your bin/debug/obj all of them. Do a Clean solution and then a Build Solution.
Check your project file in a text editor and make sure where its looking for the global file is correct, sometimes it doesnt change the directory.
Remove the global from the solution and add it back after saving and closing. make sure all the script tags in the ASPX file point to the correct one after.
You can try running the Convert to Web Application tool, that redoes all of the code and project files.
IIS Express is using the wrong root directory (see answer in VS 2012 launching app based on wrong path)
Make sure you close VS after you try them.
Those are some things I know to try. Hope one of them works for you.
When people talk about the ".net framework" they tend to be combining two main areas - the runtime library and the virtual machine that actually runs the .net code.
When you create a class library in Visual Studio in C#, the DLL follows a prescribed format - very roughly, there is section that contains meta data that describes what classes are included in it and what functions they have, etc.. and that describes where in the binary those objects exist. This common .net format is what allows libraries to be shared between .net languages (C#, VB.Net, F# and others) easily. Although much of the .net "runtime library" is written in C# now (I believe), you can imagine how many of them could have been written in unmanaged languages but arranged in this prescribed format so that they could be consumed by .net languages.
The real "meat" of the library that you build consists of CIL ("Common Intermediate Language") which is a bit like the assembly language of .net - again, this language is the common output of all .net languages, which is what makes .net libraries consumable by any .net language.
Using the tool "ildasm.exe", which is freely available in Microsoft SDKs (and might already be on your computer), you can see how C# code is converted into meta data and IL. I've included a sample at the bottom of this answer as an example.
When you run execute .net code, what is commonly happening is the .net virtual machine is reading that IL and processing it. This is the other side of .net and, again, you can likely imagine that this could easily be written in an unmanaged language - it "only" needs to read VM instructions and run them (and integrate with the garbage collector, which also need not be .net code).
What I've described is (again, roughly) what happens when you build an executable in Visual Studio (for more information, I highly recommend the book "CLR via C# by Jeffrey Richter" - it's very detailed and excellently written).
However, there are times that you might write C# that will not be executed within a .net environment - for example, Bridge.NET "compiles" C# code into JavaScript which is then run in the browser (the team that produce it have gone to the effort of writing versions of the .net runtime library that are written in JavaScript and so the power and flexibility of the .net library is available to the generated JavaScript). This is a perfect example of the separation between C# and .net - it's possible to write C# for different "targets"; you might target the .net runtime environment (when you build an executable) or you might target the browser environment (when you use Bridge.NET).
A (very) simple example class:
using System;
namespace Example
{
public class Class1
{
public void SayHello()
{
Console.WriteLine("Hello");
}
}
}
The resulting meta data and IL (retrieved via ildasm.exe):
// Metadata version: v4.0.30319
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly Example
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 )
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx
63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows.
// --- The following custom attribute is added automatically, do not uncomment -------
// .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 07 01 00 00 00 00 )
.custom instance void [mscorlib]System.Reflection.AssemblyTitleAttribute::.ctor(string) = ( 01 00 0A 54 65 73 74 49 4C 44 41 53 4D 00 00 ) // ...TestILDASM..
.custom instance void [mscorlib]System.Reflection.AssemblyDescriptionAttribute::.ctor(string) = ( 01 00 00 00 00 )
.custom instance void [mscorlib]System.Reflection.AssemblyConfigurationAttribute::.ctor(string) = ( 01 00 00 00 00 )
.custom instance void [mscorlib]System.Reflection.AssemblyCompanyAttribute::.ctor(string) = ( 01 00 00 00 00 )
.custom instance void [mscorlib]System.Reflection.AssemblyProductAttribute::.ctor(string) = ( 01 00 0A 54 65 73 74 49 4C 44 41 53 4D 00 00 ) // ...TestILDASM..
.custom instance void [mscorlib]System.Reflection.AssemblyCopyrightAttribute::.ctor(string) = ( 01 00 12 43 6F 70 79 72 69 67 68 74 20 C2 A9 20 // ...Copyright ..
20 32 30 31 36 00 00 ) // 2016..
.custom instance void [mscorlib]System.Reflection.AssemblyTrademarkAttribute::.ctor(string) = ( 01 00 00 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) = ( 01 00 00 00 00 )
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 39 33 32 61 32 30 65 2D 61 37 36 64 // ..$1932a20e-a76d
2D 34 36 33 35 2D 62 36 38 66 2D 36 63 35 66 36 // -4635-b68f-6c5f6
32 36 36 31 36 37 62 00 00 ) // 266167b..
.custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = ( 01 00 07 31 2E 30 2E 30 2E 30 00 00 ) // ...1.0.0.0..
.custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string) = ( 01 00 1C 2E 4E 45 54 46 72 61 6D 65 77 6F 72 6B // ....NETFramework
2C 56 65 72 73 69 6F 6E 3D 76 34 2E 35 2E 32 01 // ,Version=v4.5.2.
00 54 0E 14 46 72 61 6D 65 77 6F 72 6B 44 69 73 // .T..FrameworkDis
70 6C 61 79 4E 61 6D 65 14 2E 4E 45 54 20 46 72 // playName..NET Fr
61 6D 65 77 6F 72 6B 20 34 2E 35 2E 32 ) // amework 4.5.2
.hash algorithm 0x00008004
.ver 1:0:0:0
}
.module Example.dll
// MVID: {80A91E4C-0994-4773-9B73-2C4977BB1F17}
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
// Image base: 0x05DB0000
// =============== CLASS MEMBERS DECLARATION ===================
.class public auto ansi beforefieldinit Example.Class1
extends [mscorlib]System.Object
{
.method public hidebysig instance void
SayHello() cil managed
{
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Hello"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method Class1::SayHello
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method Class1::.ctor
} // end of class Example.Class1
// =============================================================
100% - discounted price / full price
An array is created with the -split
operator. Like so,
$myString="Four score and seven years ago"
$arr = $myString -split ' '
$arr # Print output
Four
score
and
seven
years
ago
When you need a certain item, use array index to reach it. Mind that index starts from zero. Like so,
$arr[2] # 3rd element
and
$arr[4] # 5th element
years
Right to left new page animation
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="0%" android:toXDelta="800%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600" />
Do this, it works:
defaultConfig {
applicationId "com.example.maps"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
multiDexEnabled true
}
You forgot to add the global operator. Use this:
var s = "04.07.2012";_x000D_
alert(s.replace(new RegExp("[0-9]","g"), "X"));
_x000D_
The common practice is to put scripts in a discrete folder, typically at the root of the site. So, if clock.js lived here:
/js/clock.js
then you could add this code to the top of any page in your site and it would just work:
<script src="/js/clock.js" type="text/javascript"></script>
I added
c:\users\[user]\appdata\roaming\python\python37\site-packages
to the path and it worked.
You were correct to use WaitForSeconds. But I suspect that you tried using it without coroutines. That's how it should work:
public void SomeMethod()
{
StartCoroutine(SomeCoroutine());
}
private IEnumerator SomeCoroutine()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds (3);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds (3);
TextUI.text = ("The lowest number you can pick is " + min);
}
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
No one seems to understand that a retail Nexus One even after being rooted still will not let you browse the file system using DDMS File Explorer. We are talking about real phones here and not the emulator. If you happen to have a Nexus One Developer Phone you can browse the file system using DDMS Filer Explorer, but a retail Nexus One that has been rooted you can't. Got it?
So I hope that answers the question of not being able to use the DDMS File Explorer to browse the file system of a rooted retail Nexus One. After rooting a retail Nexus One there is still something that remains to be done to use DDMS to use the File Explorer to browse the phones File System. I don't know what it is. Maybe someone else knowns.
Yes, in your formula
, you can cbind
the numeric variables to be aggregated:
aggregate(cbind(x1, x2) ~ year + month, data = df1, sum, na.rm = TRUE)
year month x1 x2
1 2000 1 7.862002 -7.469298
2 2001 1 276.758209 474.384252
3 2000 2 13.122369 -128.122613
...
23 2000 12 63.436507 449.794454
24 2001 12 999.472226 922.726589
See ?aggregate
, the formula
argument and the examples.
If you are testing single characters, then:
var isDigit = (function() {
var re = /^\d$/;
return function(c) {
return re.test(c);
}
}());
will return true or false depending on whether c is a digit or not.
If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection
.
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");
worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);
package.Save();
}
There should be no difference, but your tuple method is wrong, try:
a_list.append(tuple([3, 4]))
well looking for a simpler variation I found this:
it's truly smart, and I guess you might want to add other browsers variations too although it worked for me both on Chrome and Firefox.
demo and credit => http://codepen.io/Ahrengot/pen/bKdLC
@keyframes fadeIn { _x000D_
from { opacity: 0; } _x000D_
}_x000D_
_x000D_
.animate-flicker {_x000D_
animation: fadeIn 1s infinite alternate;_x000D_
}
_x000D_
<h2 class="animate-flicker">Jump in the hole!</h2>
_x000D_
Use cblas, included as part of OS X's Accelerate framework.
[02:31:59] [william@relativity ~]$ cat div3.c
#import <stdio.h>
#import <Accelerate/Accelerate.h>
int main() {
float multiplicand = 123456.0;
float multiplier = 0.333333;
printf("%f * %f == ", multiplicand, multiplier);
cblas_sscal(1, multiplier, &multiplicand, 1);
printf("%f\n", multiplicand);
}
[02:32:07] [william@relativity ~]$ clang div3.c -framework Accelerate -o div3 && ./div3
123456.000000 * 0.333333 == 41151.957031
create environment variable like in the screenshot and make sure to replace with your sdk path in my case it was C:\Users\zeesh\AppData\Local\Android\sdk replace zeesh with your username and make sure to restart android studio to take effect.
One option would be combining use of CASE..WHEN
statement is redundant within an aggregation for MySQL Database, and considering the needed query generation dynamically along with getting proper column title for the result set as in the following code block :
SET @sql = NULL;
SELECT GROUP_CONCAT(
CONCAT('SUM( `action` = ''', action, '''',pc0,' ) AS ',action,pc1)
)
INTO @sql
FROM
(
SELECT DISTINCT `action`,
IF(`pagecount` IS NULL,'',CONCAT('page',`pagecount`)) AS pc1,
IF(`pagecount` IS NULL,'',CONCAT(' AND `pagecount` = ', pagecount, '')) AS pc0
FROM `tab`
ORDER BY CONCAT(action,pc0)
) t;
SET @sql = CONCAT('SELECT company_name,',@sql,' FROM `tab` GROUP BY company_name');
SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Cleaner code that lets you pass any UIColor
to an instance of the GradientLayer
class:
class GradientLayer {
let gradientLayer: CAGradientLayer
let colorTop: CGColor
let colorBottom: CGColor
init(colorTop: UIColor, colorBottom: UIColor) {
self.colorTop = colorTop.CGColor
self.colorBottom = colorBottom.CGColor
gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorTop, colorBottom]
gradientLayer.locations = [0.0, 1.0]
}
}
Better use int.TryParse
to avoid exceptions;
var numbers = sNumbers
.Split(',')
.Where(x => int.TryParse(x, out _))
.Select(int.Parse)
.ToList();
<script type="text/javascript">
function myFunction(checked,total_boxes){
for ( i=0 ; i < total_boxes ; i++ ){
if (checked){
document.forms[0].checkBox[i].checked=true;
}else{
document.forms[0].checkBox[i].checked=false;
}
}
}
</script>
<body>
<FORM>
<input type="checkbox" name="checkBox" >one<br>
<input type="checkbox" name="checkBox" >two<br>
<input type="checkbox" name="checkBox" >three<br>
<input type="checkbox" name="checkBox" >four<br>
<input type="checkbox" name="checkBox" >five<br>
<input type="checkbox" name="checkBox" >six<br>
<input type="checkbox" name="checkBox" >seven<br>
<input type="checkbox" name="checkBox" >eight<br>
<input type="checkbox" name="checkBox" >nine<br>
<input type="checkbox" name="checkBox" >ten<br> s
<input type=button name="CheckAll" value="Select_All" onClick="myFunction(true,10)">
<input type=button name="UnCheckAll" value="UnCheck All Boxes" onClick="myFunction(false,10)">
</FORM>
</body>
I'd recommend making "apple" its own class. You should avoid the starts-with/ends-with if you can because being able to select using div.apple
would be a lot faster. That's the more elegant solution. Don't be afraid to split things out into separate classes if it makes the task simpler/faster.
Use grep or grepl to find observations with white spaces and sub to get rid of them.
names<-c("Ganga Din\t", "Shyam Lal", "Bulbul ")
grep("[[:space:]]+$", names)
[1] 1 3
grepl("[[:space:]]+$", names)
[1] TRUE FALSE TRUE
sub("[[:space:]]+$", "", names)
[1] "Ganga Din" "Shyam Lal" "Bulbul"
Use white-space: nowrap;
[1] [2] or give that link more space by setting li
's width to greater values.
[1] § 3. White Space and Wrapping: the white-space property - W3 CSS Text Module Level 3
[2] white-space - CSS: Cascading Style Sheets | MDN
Using cp-axios wrapper you able to abort your requests with three diffent types of the cancellation API:
1. Promise cancallation API (CPromise):
const cpAxios= require('cp-axios');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const chain = cpAxios(url)
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
chain.cancel();
}, 500);
2. Using AbortController signal API:
const cpAxios= require('cp-axios');
const CPromise= require('c-promise2');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const abortController = new CPromise.AbortController();
const {signal} = abortController;
const chain = cpAxios(url, {signal})
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
abortController.abort();
}, 500);
3. Using a plain axios cancelToken:
const cpAxios= require('cp-axios');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const source = cpAxios.CancelToken.source();
cpAxios(url, {cancelToken: source.token})
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
source.cancel();
}, 500);
Are you attempting to do this inside of an XCTest and on the verge of smashing your laptop? This is the thread for you: Why can't code inside unit tests find bundle resources?
adb shell "svc wifi enable"
This worked & it makes action in background without opening related option !!
I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.
Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.
Total Start End
829 29170 29998
815 38866 39680
710 41798 42507
681 43442 44122
661 46337 46997
643 35358 36000
609 36866 37474
596 38204 38799
592 33657 34248
571 30261 30831
563 41231 41793
542 21011 21552
528 28590 29117
521 14415 14935
510 26490 26999
Source (via the CSV download button):
http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
Use std::printf and c_str() example:
std::printf("Follow this command: %s", myString.c_str());
We are using Response.SetCookie()
for update the old one cookies and Response.Cookies.Add()
are use to add the new cookies. Here below code CompanyId
is update in old cookie[OldCookieName]
.
HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.
I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.
http://technet.microsoft.com/en-us/library/bb490986.aspx
Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.
You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800
from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()
If we take the problem as "how to make singleton with state", then it is not necessary to pass the state as constructor parameter. I agree with the posts that initialize the states or using set method after getting the singleton instance.
Another question is: is it good to have singleton with state?
Just came acreoss this, and since I had the same issue, I'd just post the results I came up with
when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.
moment(moment.utc('1.1.2014').format());
Well, came in handy for me to support across timezones
B
Here is my generic function to test private fields:
protected <F> F getPrivateField(String fieldName, Object obj)
throws NoSuchFieldException, IllegalAccessException {
Field field =
obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (F)field.get(obj);
}
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
Quick way to print something is:
select '** Place your mesage here' AS '** DEBUG:';
Attach an event handler to the submit event of the form. Make sure it cancels the default action.
Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.
Here is how you would do it in YUI 3:
<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
YUI().use('event', function (Y) {
Y.one('form').on('submit', function (e) {
// Whatever else you want to do goes here
e.preventDefault();
});
});
</script>
Make sure that the server will pick up the slack if the JavaScript fails for any reason.
You have to loop through all rows, and add the missing rows and columns. For the already existing rows, you loop from c to cols, for the new rows, first push an empty array to outer array, then loop from 0 to cols:
var r = 3; //start from rows 3
var c = 5; //start from col 5
var rows = 8;
var cols = 7;
for (var i = 0; i < rows; i++) {
var start;
if (i < r) {
start = c;
} else {
start = 0;
myArray.push([]);
}
for (var j = start; j < cols; j++) {
myArray[i].push(0);
}
}
Refer this link for full understand of multiple permission, also full source code download, click Here
private boolean checkAndRequestPermissions() {
int permissionReadPhoneState = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
int permissionProcessOutGogingCalls = ContextCompat.checkSelfPermission(this, Manifest.permission.PROCESS_OUTGOING_CALLS);
int permissionProcessReadContacts = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
int permissionProcessReadCallLog = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG);
int permissionWriteStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionReadStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionReadPhoneState != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
}
if (permissionProcessOutGogingCalls != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
}
if (permissionProcessReadContacts != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_CONTACTS);
}
if (permissionProcessReadCallLog != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_CALL_LOG);
}
if (permissionWriteStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionReadStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length == 0 || grantResults == null) {
/*If result is null*/
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/*If We accept permission*/
} else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
/*If We Decline permission*/
}
}
I've recently tried piping the output of one free obfuscator into the another free obfuscator - namely Dotfuscator CE and the new Babel obfuscator on CodePlex. More details on my blog.
As for serialization, I've moved that code into a different DLL and included that in the project. I reasoned that there weren't any secrets in there that aren't in the XML anyway, so it didn't need obfuscation. If there is any serious code in those classes, using partial classes in the main assembly should cover it.
From Using Triggers:
Detecting the DML Operation That Fired a Trigger
If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.
So
IF DELETING THEN ... END IF;
should work for your case.
Customer.java
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
int id;
String desc;
ArrayList<String> list;
public ArrayList<String> getList()
{
return list;
}
@XmlElement
public void setList(ArrayList<String> list)
{
this.list = list;
}
public String getDesc()
{
return desc;
}
@XmlElement
public void setDesc(String desc)
{
this.desc = desc;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
createXML.java
import java.io.StringWriter;
import java.util.ArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class createXML {
public static void main(String args[]) throws Exception
{
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
Customer c = new Customer();
c.setAge(45);
c.setDesc("some desc ");
c.setId(23);
c.setList(list);
c.setName("name");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(c, sw);
String xmlString = sw.toString();
System.out.println(xmlString);
}
}
The accepted answer is not always correct. If you configure binary logging on MySQL, you can rollback the database to any previous point you still have a snapshot and binlog for.
7.5 Point-in-Time (Incremental) Recovery Using the Binary Log is a good starting point for learning about this facility.
You can trigger a newline by inserting Chunk.NEWLINE
into your document. Here's an example.
public static void main(String args[]) {
try {
// create a new document
Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );
document.open();
document.add( new Paragraph( "Hello, World!" ) );
document.add( new Paragraph( "Hello, World!" ) );
// add a couple of blank lines
document.add( Chunk.NEWLINE );
document.add( Chunk.NEWLINE );
// add one more line with text
document.add( new Paragraph( "Hello, World!" ) );
document.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Below is a screen shot showing part of the PDF that the code above produces.
If you're willing to use an external library, check out Apache Commons IO (200KB JAR). It contains an org.apache.commons.io.FileUtils.readFileToString()
method that allows you to read an entire File
into a String
with one line of code.
Example:
import java.io.*;
import java.nio.charset.*;
import org.apache.commons.io.*;
public String readFile() throws IOException {
File file = new File("data.txt");
return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}
First you'll need to get it into a byte[]
, so do this:
byte[] ba = Encoding.Default.GetBytes("sample");
and then you can get the string:
var hexString = BitConverter.ToString(ba);
now, that's going to return a string with dashes (-
) in it so you can then simply use this:
hexString = hexString.Replace("-", "");
to get rid of those if you want.
NOTE: you could use a different Encoding
if you needed to.
Simply use an image extension like .jpeg
or .png
.
If you're using MS SQL, you can try:
SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC
Yes, it means "not equal", either less than or greater than. e.g
If x <> y Then
can be read as
if x is less than y or x is greater than y then
The logical outcome being "If x is anything except equal to y"
I found that the useful getResources().getColor(R.color.color_name) is deprecated.
It is not deprecated in API Level 21, according to the documentation.
It is deprecated in the M Developer Preview. However, the replacement method (a two-parameter getColor()
that takes the color resource ID and a Resources.Theme
object) is only available in the M Developer Preview.
Hence, right now, continue using the single-parameter getColor()
method. Later this year, consider using the two-parameter getColor()
method on Android M devices, falling back to the deprecated single-parameter getColor()
method on older devices.
Double period (..) means you go up one folder and then look for the folder behind the slash. For example:
If your index.html is in the folder html/files
and the fonts are in html/fonts
, the .. is fine (because you have to go back one folder to go to /fonts
). Is your index.html in html
and your fonts in html/fonts
, then you should use only one period.
Another problem could be that your browser might not support .eot font-files.
Without seeing more of your code (and maybe a link to a live version of your website), I can't really help you further.
Edit: Forget the .eot part, I missed the .ttf file in your css.
Try the following:
@font-face {
font-family: Gotham;
src: url(../fonts/gothammedium.eot);
src: url(../fonts/Gotham-Medium.ttf);
}
One detail hasn't been noted yet: modern desktop browsers consider different button presses to be "clicks" for AddEventListener('click'
and onclick
by default.
onclick
and AddEventListener
click fire on left and middle click.onclick
fires only on left click, but AddEventListener
click fires on left, middle and right clicks.Also, middle-click behavior is very inconsistent across browsers when scroll cursors are involved:
It is also worth noting that "click" events for any keyboard-selectable HTML element such as input
also fire on space or enter when the element is selected.
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener
-- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
2019 answer:
Using CSS grid:
.parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr;
}
<script>
function SetBack(dir) {
document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>
If you want to initialize an array in a constructor, you can't use those array initializer like.
data= {10,20,30,40,50,60,71,80,90,91};
Just change it to
data = new int[] {10,20,30,40,50,60,71,80,90,91};
You don't have to specify the size with data[10] = new int[] { 10,...,91}
Just declare the property / field with int[] data;
and initialize it like above.
The corrected version of your code would look like the following:
public class Array {
int[] data;
public Array() {
data = new int[] {10,20,30,40,50,60,71,80,90,91};
}
}
As you see the bracket are empty. There isn't any need to tell the size between the brackets, because the initialization and its size are specified by the count of the elements between the curly brackets.
You are getting the warning because ArrayList
is part of java generics. Essentially, it's a way to catch your type errors at compile time. For example, if you declare your array list with types Integer (ArrrayList<Integer>
) and then try to add Strings to it, you'll get an error at compile time - avoiding nasty crashes at runtime.
The first syntax is there for backward compatibility and should be avoided whenever possible (note that generics were not there in older versions of java).
Second and third examples are pretty much equivalent. As you need to pass an object and not a primitive type to add
method, your 3
is internally converted to Integer(3)
. By writing a string in double-quotes you effectively are creating a String
object. When calling String("ss")
you are creating a new String
object with value being the same as the parameter ("ss").
Unless you really do need to store different types in your List, I would suggest actually using a proper type declaration, e.g. ArrayList<Integer> = new ArrayList<Integer>()
- it'll save you a lot of headache in the long run.
If you do need multiple datatypes in the list, then the second example is better.
The reason why you don't have to load a certificate locally is that you've explicitly chosen not to verify the certificate, with this trust manager that trusts all certificates.
The traffic will still be encrypted, but you're opening the connection to Man-In-The-Middle attacks: you're communicating secretly with someone, you're just not sure whether it's the server you expect, or a possible attacker.
If your server certificate comes from a well-known CA, part of the default bundle of CA certificates bundled with the JRE (usually cacerts
file, see JSSE Reference guide), you can just use the default trust manager, you don't have to set anything here.
If you have a specific certificate (self-signed or from your own CA), you can use the default trust manager or perhaps one initialised with a specific truststore, but you'll have to import the certificate explicitly in your trust store (after independent verification), as described in this answer. You may also be interested in this answer.
I believe this is efficient enough... To get a String from an InputStream, I'd call the following method:
public static String getStringFromInputStream(InputStream stream) throws IOException
{
int n = 0;
char[] buffer = new char[1024 * 4];
InputStreamReader reader = new InputStreamReader(stream, "UTF8");
StringWriter writer = new StringWriter();
while (-1 != (n = reader.read(buffer))) writer.write(buffer, 0, n);
return writer.toString();
}
I always use UTF-8. You could, of course, set charset as an argument, besides InputStream.
For the sake of other developers who finds this question and need another solution that fits not only for unit-tests:
I've found this on a blog (not my solution! Credit to the blog's owner).
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
from terminal
> cd myProjectPath
myProjectPath > npm install
If you just need this for debugging to see how the XML looks like, then instead of print(xml.etree.ElementTree.tostring(e))
you can use dump
like this:
xml.etree.ElementTree.dump(e)
And this works both with Element
and ElementTree
objects as e
, so there should be no need for getroot
.
The documentation of dump
says:
xml.etree.ElementTree.dump(elem)
Writes an element tree or element structure to
sys.stdout
. This function should be used for debugging only.The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.
elem
is an element tree or an individual element.Changed in version 3.8: The
dump()
function now preserves the attribute order specified by the user.
"location of notepad file" > notepad Filename
C:\Users\Desktop\Anaconda> notepad myfile
works for me! :)
The link posted by Jose has been updated and pylab now has a tight_layout()
function that does this automatically (in matplotlib version 1.1.0).
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout
http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout
cross apply
sometimes enables you to do things that you cannot do with inner join
.
Example (a syntax error):
select F.* from sys.objects O
inner join dbo.myTableFun(O.name) F
on F.schema_id= O.schema_id
This is a syntax error, because, when used with inner join
, table functions can only take variables or constants as parameters. (I.e., the table function parameter cannot depend on another table's column.)
However:
select F.* from sys.objects O
cross apply ( select * from dbo.myTableFun(O.name) ) F
where F.schema_id= O.schema_id
This is legal.
Edit: Or alternatively, shorter syntax: (by ErikE)
select F.* from sys.objects O
cross apply dbo.myTableFun(O.name) F
where F.schema_id= O.schema_id
Edit:
Note: Informix 12.10 xC2+ has Lateral Derived Tables and Postgresql (9.3+) has Lateral Subqueries which can be used to a similar effect.
I used title and it worked!
The title attribute gives the title of the link. With one exception, it is purely advisory. The value is text. The exception is for style sheet links, where the title attribute defines alternative style sheet sets.
<a class="navbar-brand" href="http://www.alberghierocastelnuovocilento.gov.it/sito/index.php" title="sito dell'Istituto Ancel Keys">A.K.</a>
So, to summarize:
I don't want to make things more confusing but note that Java EE 6 provides modern, standardized and very nice equivalent of the above frameworks: JSF 2.0 and Facelets for the presentation, JPA 2.0 for the persistence, Dependency Injection, etc. For a new development, this is IMO a serious option, Java EE 6 is a great stack.
I've successfully used OpenPop.NET to access emails via POP3.
A plugin is probably your best option. Look in the wordpress plugins directory or google to see if you can find one. I found the one below and that seemed to work perfect.
https://wordpress.org/plugins/woocommerce-products-filter/
This one seems to do exactly what you are after
In order to make it work on selection in a list view use the following code:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#fff"/>
<item android:state_activated="true" android:color="#fff"/>
<item android:color="#000" />
</selector>
Apparently the key is state_activated="true"
state.
Read the input continuously within the loop so that the variable line
is assigned a value other than the initial value
while ((line = br.readLine()) !=null) {
...
}
Aside: This problem has already been solved using CSV libraries such as OpenCSV. Here are examples for reading and writing CSV files
Say you want Comic Sans for the title and Helvetica for the x label.
csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}
plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
The question is a bit old but I just solved a very similar problem. We have several intranet sites here including the one I'm responsible for, and the others require compatibility mode or they break. For that reason, site rules default IE to compatibility mode on intranet sites. I am upgrading my own stuff and no longer need it; in fact, some of the features I'm trying to use don't look right in compat mode. I'm using the meta IE-Edge tag like you are.
IE assumes websites without the fully-qualified address are intranet, and acts accordingly. With that in mind I just altered the bindings in IIS to only listen to the fully-qualified address, then set up a dummy website that listened for the unqualified address. The second one redirects all traffic to the fully-qualified address, making IE believe it's an external site. The site renders correctly with or without the Compatibility Mode on Intranet Sites box checked.
For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:
while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
n = (3*n + 1) / 2;
if (n % 2 == 0) {
do n /= 2; while (n % 2 == 0);
if (n == 1) break;
}
}
Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:
3n+1 -> ???? 0000 0100
/ 2 -> ???? ?000 0010
/ 2 -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2 -> ???? ???0 0010
/ 2 -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2 -> ???? ???? ?010
/ 2 -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2 -> ???? ???? ???0
/ 2 -> ???? ???? ????
So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:
k = n / 256;
m = n % 256;
switch (m) {
case 0: n = 1 * k + 0; break;
case 1: n = 81 * k + 1; break;
case 2: n = 81 * k + 1; break;
...
case 155: n = 729 * k + 425; break;
...
}
Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.
PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like
static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }
while (n > 128) {
size_t lastBits = n % 256;
n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}
In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.
PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).
We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).
If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.
You can't update with a number greater than 1 for datatype number(2,2)
is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1
. i.e. 0.12, 0.95 etc.
Please check NUMBER DATATYPE in NUMBER Datatype.
I prefer using the following code to generate a decimal number up to fist decimal point. you can copy paste the 3rd line to add more numbers after decimal point by appending that number in string "combined". You can set the minimum and maximum value by changing the 0 and 9 to your preferred value.
Random r = new Random();
string beforePoint = r.Next(0, 9).ToString();//number before decimal point
string afterPoint = r.Next(0,9).ToString();//1st decimal point
//string secondDP = r.Next(0, 9).ToString();//2nd decimal point
string combined = beforePoint+"."+afterPoint;
decimalNumber= float.Parse(combined);
Console.WriteLine(decimalNumber);
I hope that it helped you.
sc queryex type= service state= all | find /i "NATION"
/i
for case insensitive searchtype=
is deliberate and requiredMy solution:
complete
)/*global define */
define(['angular', './my-module'], function(angular, directives) {
'use strict';
directives.directive('polimerBinding', ['$compile', function($compile) {
return {
restrict: 'A',
scope: {
method:'&polimerBinding'
},
link : function(scope, element, attrs) {
var el = element[0];
var expressionHandler = scope.method();
var siemEvent = attrs['polimerEvent'];
if (!siemEvent) {
siemEvent = 'complete';
}
el.addEventListener(siemEvent, function (e, options) {
expressionHandler(e.detail);
})
}
};
}]);
});
<dom-module id="search">
<template>
<h3>Search</h3>
<div class="input-group">
<textarea placeholder="search by expression (eg. temperature>100)"
rows="10" cols="100" value="{{text::input}}"></textarea>
<p>
<button id="button" class="btn input-group__addon">Search</button>
</p>
</div>
</template>
<script>
Polymer({
is: 'search',
properties: {
text: {
type: String,
notify: true
},
},
regularSearch: function(e) {
console.log(this.range);
this.fire('complete', {'text': this.text});
},
listeners: {
'button.click': 'regularSearch',
}
});
</script>
</dom-module>
<search id="search" polimer-binding="searchData"
siem-event="complete" range="{{range}}"></siem-search>
searchData
is the control function
$scope.searchData = function(searchObject) {
alert('searchData '+ searchObject.text + ' ' + searchObject.range);
}
For WebAPI, check out this link: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
Basically, add this code to your Application_Start
:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Here is another way using WebRequest, I hope it will work for you
$user = 'whatever'
$pass = 'whatever'
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$headers = @{ Authorization = "Basic Zm9vOmJhcg==" }
Invoke-WebRequest -Credential $credential -Headers $headers -Uri "https://dc01.test.local/"
Swift 3
let secondviewController:UIViewController = self.storyboard?.instantiateViewController(withIdentifier: "StoryboardIdOfsecondviewController") as? SecondViewController
self.navigationController?.pushViewController(secondviewController, animated: true)
I had the same problem when my network config was incorrect and DNS was not resolving. In other words the issue could arise when there is no Network Access.
The downloaded sdk software does not contain sdk platform tools.
For this, using cmd
go to "C:\Program Files\Android\android-sdk\tools"
directory and then type the following command to download those missing tools:
android.bat update sdk --no-ui
Then type y
to accept all the licenses in cmd
. Downloading will start in cmd
itself.
There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.
Also, this structure is hardly a tree, finding a more representative name might be a good exercise.
On Ubuntu with OpenJDK, it installed in /usr/lib/jvm/default-java/jre/lib/ext/jfxrt.jar
(technically its a symlink to /usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
, but it is probably better to use the default-java
link)
You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399
part to the URL (you can see this in your dump of the request).
What you're returning is JSON, not JSONP. Your response looks like
{"red" : "#f00"}
and jQuery is expecting something like this:
jQuery16406345664265099913_1319854793396({"red" : "#f00"})
If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json
needs to be able to actually return a JSONP response.
If the same origin policy isn't an issue for your application, then you just need to fix the dataType
in your jQuery.ajax
call to be json
instead of jsonp
.
The problem was, in the URL i wrote http://my_domain instead of https://my_domain
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
✗
✗
✘
✘
✕
✕
✖
✖
From what I understand you do not want to redirect when the link is clicked. You can do :
<a href='javascript:;' onclick='show_more_menu();'>More ></a>
Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.
Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.
We can add the following to a particular tag in CSS:
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
In case of half rotation change 90
to 45
.
As an alternative to curl
, you can use HTTPie, it'a CLI, cURL-like tool for humans.
Installation instructions: https://github.com/jakubroztocil/httpie#installation
Then, run:
http -f POST http://localhost:4040/api/users username=johnsnow photo@images/avatar.jpg
HTTP/1.1 200 OK
Access-Control-Expose-Headers: X-Frontend
Cache-control: no-store
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 89
Content-Type: text/html; charset=windows-1251
Date: Tue, 26 Jun 2018 11:11:55 GMT
Pragma: no-cache
Server: Apache
Vary: Accept-Encoding
X-Frontend: front623311
...
following Donald's comment:
This variable applies when binary logging is enabled.
All I had to do was:
That step out that import problem.
(Then I'll review the programmer's code to suggest an improvement)
The location of the sitemap affects which URLs that it can include, but otherwise there is no standard. Here is a good link with more explaination: http://www.sitemaps.org/protocol.html#location