I guess ch
is a declared as char
. Since char
is a primitive data type and not and object, you can't call any methof from it. You should use Character.isLetter(ch)
.
I know this is really old, but I'm posting my solution anyways since google finds this thread.
background-image: url('./imagefolder/image.jpg');
That is what I do. Two dots means drill back one directory closer to root ".." while one "." should mean start where you are at as if it were root. I was having similar issues but adding that fixed it for me. You can even leave the "." in it when uploading to your host because it should work fine so long as your directory setup is exactly the same.
I had exact same error after adding a new configuration via ConfigurationManager in Visual Studio.
It turned out when the 'Production' configuration was added for the whole solution (and each project) the OutputPath element was not added to the .csproj files.
To fix, I went to the Build tab in project properties, changed OutputPath from \bin\Production\
to \bin\Production
(deleted trailing \
) and saved changes. This forced creation of the OutputPath element in the .csproj file and the project has built successfully.
Sounds like a glitch to me.
Here is how I do custom CSS for Internet Explorer:
In my JavaScript file:
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
jQuery(document).ready(function(){
if(var_isIE){
if(var_isIE == 10){
jQuery("html").addClass("ie10");
}
if(var_isIE == 8){
jQuery("html").addClass("ie8");
// you can also call here some function to disable things that
//are not supported in IE, or override browser default styles.
}
}
});
And then in my CSS file, y define each different style:
.ie10 .some-class span{
.......
}
.ie8 .some-class span{
.......
}
I like Clay Eclipse plugin. I've only used it with MySQL, but it claims Firebird support.
You could (but you shouldn't) use reflection for the job:
import java.lang.reflect.Field;
public class Outer {
public class Inner {
}
public static void main(String[] args) throws Exception {
// Create the inner instance
Inner inner = new Outer().new Inner();
// Get the implicit reference from the inner to the outer instance
// ... make it accessible, as it has default visibility
Field field = Inner.class.getDeclaredField("this$0");
field.setAccessible(true);
// Dereference and cast it
Outer outer = (Outer) field.get(inner);
System.out.println(outer);
}
}
Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries
int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries
If you want to have the result for all values of NUM
:
SELECT `NUM`, COUNT(*) AS `count`
FROM yourTable
GROUP BY `NUM`
Or just for one specific:
SELECT `NUM`, COUNT(*) AS `count`
FROM yourTable
WHERE `NUM`=1
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
my_list = sorted(dict.items(), key=lambda x: x[1])
How about something like this?
val newDF = df.filter($"B" === "").take(1) match {
case Array() => df
case _ => df.withColumn("D", $"B" === "")
}
Using take(1)
should have a minimal hit
If you're wanting to do this via powershell on windows this worked for me
$env:JPDA_SUSPEND="y"
$env:JPDA_TRANSPORT="dt_socket"
/path/to/tomcat/bin/catalina.bat jpda start
There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.
While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
I've found this the easy fix, simply add this to the css:
cursor: pointer;
You're missing the data-toggle="tab"
data-tag on your menu urls so your scripts can't tell where your tab switches are:
HTML
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a data-toggle="tab" href="#red">Red</a></li>
<li><a data-toggle="tab" href="#orange">Orange</a></li>
<li><a data-toggle="tab" href="#yellow">Yellow</a></li>
<li><a data-toggle="tab" href="#green">Green</a></li>
<li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
In my opinion, things like dependency injection are symptoms of a rigid and over-complex framework. When the main body of code becomes much too weighty to change easily, you find yourself having to pick small parts of it, define interfaces for them, and then allowing people to change behaviour via the objects that plug into those interfaces. That's all well and good, but it's better to avoid that sort of complexity in the first place.
It's also the symptom of a statically-typed language. When the only tool you have to express abstraction is inheritance, then that's pretty much what you use everywhere. Having said that, C++ is pretty similar but never picked up the fascination with Builders and Interfaces everywhere that Java developers did. It is easy to get over-exuberant with the dream of being flexible and extensible at the cost of writing far too much generic code with little real benefit. I think it's a cultural thing.
Typically I think Python people are used to picking the right tool for the job, which is a coherent and simple whole, rather than the One True Tool (With A Thousand Possible Plugins) that can do anything but offers a bewildering array of possible configuration permutations. There are still interchangeable parts where necessary, but with no need for the big formalism of defining fixed interfaces, due to the flexibility of duck-typing and the relative simplicity of the language.
Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:
public class Foo {
static {
System.out.println("Message");
System.exit(0);
}
}
The System.exit(0)
lets the program exit before the JVM is looking for the main
method, otherwise the following error will be thrown:
Exception in thread "main" java.lang.NoSuchMethodError: main
In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:
The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).
Here an alternative is to write your own launcher, this way you can define entry points as you want.
In the article JVM Launcher you will find the necessary information to get started:
This article explains how can we create a Java Virtual Machine Launcher (like java.exe or javaw.exe). It explores how the Java Virtual Machine launches a Java application. It gives you more ideas on the JDK or JRE you are using. This launcher is very useful in Cygwin (Linux emulator) with Java Native Interface. This article assumes a basic understanding of JNI.
If you use sufficiently big list not in b
clause will do a linear search for each of the item in a
. Why not use set? Set takes iterable as parameter to create a new set object.
>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}
consider the following solution
.disable-anchor-tag {
pointer-events: none;
}
If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:
public String loadResourceAsString(String fileName) throws IOException {
Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
String contents = scanner.useDelimiter("\\A").next();
scanner.close();
return contents;
}
"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).
@Cherniv Thanks for the answer
<Text style={{}}> {'Test'.toUpperCase()} </Text>
I would do it like this:
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)
In case you have some more complex formula it will be handy
Below is the relevant information from the link which Zaki provided.
Generate a 2048-bit RSA private key
$ openssl genrsa -out private_key.pem 2048
Convert private Key to PKCS#8 format (so Java can read it)
$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
Output public key portion in DER format (so Java can read it)
$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;
public class PrivateKeyReader {
public static PrivateKey get(String filename)
throws Exception {
byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
PKCS8EncodedKeySpec spec =
new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);
}
}
import java.io.*;
import java.nio.*;
import java.security.*;
import java.security.spec.*;
public class PublicKeyReader {
public static PublicKey get(String filename)
throws Exception {
byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
X509EncodedKeySpec spec =
new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
}
You need to use Iterator
and call remove()
on iterator
instead of using for
loop.
Just default the variable to the expected type:
(number=1) => ...
(number=1.0) => ...
(string='str') ...
Try this:
var text = $('#YourDropdownId').find('option:selected').text();
The probably shortest answer is
val==null || val==''
if you change rigth side to val===''
then empty array will give false. Proof
function isEmpty(val){_x000D_
return val==null || val==''_x000D_
}_x000D_
_x000D_
// ------------_x000D_
// TEST_x000D_
// ------------_x000D_
_x000D_
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
_x000D_
More details about ==
(source here)
BONUS: Reason why ===
is more clear than ==
To write clear and easy understandable code, use explicite list of accepted values
val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)
function isEmpty(val){_x000D_
return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)_x000D_
}_x000D_
_x000D_
// ------------_x000D_
// TEST_x000D_
// ------------_x000D_
_x000D_
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
_x000D_
Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)
import os
source = ['test_sound.flac','ts.mp3']
for files in source:
fileName,fileExtension = os.path.splitext(files)
print fileExtension # Print File Extensions
print fileName # It print file name
More type safe code for Swift 3.0
extension UIResponder {
func owningViewController() -> UIViewController? {
var nextResponser = self
while let next = nextResponser.next {
nextResponser = next
if let vc = nextResponser as? UIViewController {
return vc
}
}
return nil
}
}
Why don't you try android:hint="hint" to provide the hint to the user..!!
The "hint" will automatically disappear when the user clicks on the edittextbox. its the proper and best solution.
To download the SDK over command line, the link has changed slightly than previously mentioned:
wget --quiet --output-document=/tmp/sdk-tools-linux.zip https://dl.google.com/android/repository/commandlinetools-linux-${ANDROID_SDK_TOOLS}.zip
Latest version listed on the downloads page.
Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:
window.parent.$("#serverMsg")
Have you tried the "Publish" method? You just right click on the project file in the solution explorer and select "Publish" from the pop-up menu. This creates an installer in a few very simple steps.
You can do more configuration of the installer from the Publish tab in the project properties window.
NB: This method only works for WPF & Windows Forms apps.
I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.
According to the spec, a POST of json data should have the content-type:
application/json
Relevant portion of the HTML spec
6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows
Relevant portion of the JSON spec
- IANA Considerations
The MIME media type for JSON text is application/json.
Seems reflection only help here.. I've done small example of converting object to dictionary and vise versa:
[TestMethod]
public void DictionaryTest()
{
var item = new SomeCLass { Id = "1", Name = "name1" };
IDictionary<string, object> dict = ObjectToDictionary<SomeCLass>(item);
var obj = ObjectFromDictionary<SomeCLass>(dict);
}
private T ObjectFromDictionary<T>(IDictionary<string, object> dict)
where T : class
{
Type type = typeof(T);
T result = (T)Activator.CreateInstance(type);
foreach (var item in dict)
{
type.GetProperty(item.Key).SetValue(result, item.Value, null);
}
return result;
}
private IDictionary<string, object> ObjectToDictionary<T>(T item)
where T: class
{
Type myObjectType = item.GetType();
IDictionary<string, object> dict = new Dictionary<string, object>();
var indexer = new object[0];
PropertyInfo[] properties = myObjectType.GetProperties();
foreach (var info in properties)
{
var value = info.GetValue(item, indexer);
dict.Add(info.Name, value);
}
return dict;
}
The following examples are source ordered i.e. column 1 appears before column 2 in the HTML source. Whether a column appears on left or right is controlled by CSS:
Fixed Right
#wrapper {_x000D_
margin-right: 200px;_x000D_
}_x000D_
#content {_x000D_
float: left;_x000D_
width: 100%;_x000D_
background-color: #CCF;_x000D_
}_x000D_
#sidebar {_x000D_
float: right;_x000D_
width: 200px;_x000D_
margin-right: -200px;_x000D_
background-color: #FFA;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
Fixed Left
#wrapper {_x000D_
margin-left: 200px;_x000D_
}_x000D_
#content {_x000D_
float: right;_x000D_
width: 100%;_x000D_
background-color: #CCF;_x000D_
}_x000D_
#sidebar {_x000D_
float: left;_x000D_
width: 200px;_x000D_
margin-left: -200px;_x000D_
background-color: #FFA;_x000D_
}_x000D_
#cleared {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="content">Column 1 (fluid)</div>_x000D_
<div id="sidebar">Column 2 (fixed)</div>_x000D_
<div id="cleared"></div>_x000D_
</div>
_x000D_
Alternate solution is to use display: table-cell; which results in equal height columns.
grep -r -e string directory
-r
is for recursive; -e
is optional but its argument specifies the regex to search for. Interestingly, POSIX grep
is not required to support -r
(or -R
), but I'm practically certain that System V in practice they (almost) all do. Some versions of grep
did, sogrep
support -R
as well as (or conceivably instead of) -r
; AFAICT, it means the same thing.
I was looking for the same thing and found: https://github.com/medialize/URI.js which is quite nice :)
-- Update
I found a better package: https://www.npmjs.org/package/qs it also deals with arrays in get params.
Chrome doesn't render the fonts like Firefox or any other browser does. This is generally a problem in Chrome running on Windows only. If you want to make the fonts smooth, use the -webkit-font-smoothing
property on yer h4
tags like this.
h4 {
-webkit-font-smoothing: antialiased;
}
You can also use subpixel-antialiased
, this will give you different type of smoothing (making the text a little blurry/shadowed). However, you will need a nightly version to see the effects. You can learn more about font smoothing here.
You could write a convenience method:
public PrintStream print(String format, Object... arguments) {
return System.out.format(format, arguments);
}
But as you can see, you've simply just renamed format
(or printf
).
Here's how you could use it:
private void printScores(Player... players) {
for (int i = 0; i < players.length; ++i) {
Player player = players[i];
String name = player.getName();
int score = player.getScore();
// Print name and score followed by a newline
System.out.format("%s: %d%n", name, score);
}
}
// Print a single player, 3 players, and all players
printScores(player1);
System.out.println();
printScores(player2, player3, player4);
System.out.println();
printScores(playersArray);
// Output
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Abe: 11
Bob: 22
Cal: 33
Dan: 44
Note there's also the similar System.out.printf
method that behaves the same way, but if you peek at the implementation, printf
just calls format
, so you might as well use format
directly.
You probably could have them in a static class, with static read-only properties.
public static class Routes
{
public static string SignUp => "signup";
}
What about this :
li = [1,2,3,4,5] # create list
li = dict(zip(li,range(len(li)))) # convert List To Dict
print( li ) # {1: 0, 2: 1, 3: 2, 4:3 , 5: 4}
li.get(20) # None
li.get(1) # 0
You can write a PL/SQL function to return that cursor (or you could put that function in a package if you have more code related to this):
CREATE OR REPLACE FUNCTION get_allitems
RETURN SYS_REFCURSOR
AS
my_cursor SYS_REFCURSOR;
BEGIN
OPEN my_cursor FOR SELECT * FROM allitems;
RETURN my_cursor;
END get_allitems;
This will return the cursor.
Make sure not to put your SELECT
-String into quotes in PL/SQL when possible. Putting it in strings means that it can not be checked at compile time, and that it has to be parsed whenever you use it.
If you really need to use dynamic SQL you can put your query in single quotes:
OPEN my_cursor FOR 'SELECT * FROM allitems';
This string has to be parsed whenever the function is called, which will usually be slower and hides errors in your query until runtime.
Make sure to use bind-variables where possible to avoid hard parses:
OPEN my_cursor FOR 'SELECT * FROM allitems WHERE id = :id' USING my_id;
If you are using Jupyter in anaconda, after conda update scikit-learn
in terminal, close anaconda and restart, otherwise the error will occur again.
also you can open more than two page try this
`<a href="http://www.microsoft.com" target="_blank" onclick="window.open('http://www.google.com'); window.open('http://www.yahoo.com');">Click Here</a>`
I believe the way to do this is $location.url('/RouteTo/Login');
Edit for Clarity
Say my route for my login view was /Login
, I would say $location.url('/Login')
to navigate to that route.
For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:
window.location = "http://www.my-domain.com/login"
Try this:
if cookie and not cookie.isspace():
# the string is non-empty
else:
# the string is empty
The above takes in consideration the cases where the string is None
or a sequence of white spaces.
Note: Git 2.6 (Q3/Q4 2015) will finally provide a more meaningful error message.
See commit ce11360 (29 Aug 2015) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 699a0f3, 02 Sep 2015)
log
: diagnose emptyHEAD
more clearlyIf you init or clone an empty repository, the initial message from running "
git log
" is not very friendly:
$ git init
Initialized empty Git repository in /home/peff/foo/.git/
$ git log
fatal: bad default revision 'HEAD'
Let's detect this situation and write a more friendly message:
$ git log
fatal: your current branch 'master' does not have any commits yet
We also detect the case that 'HEAD' points to a broken ref; this should be even less common, but is easy to see.
Note that we do not diagnose all possible cases. We rely onresolve_ref
, which means we do not get information about complex cases. E.g., "--default master
" would usedwim_ref
to find "refs/heads/master
", but we notice only that "master
" does not exist.
Similarly, a complex sha1 expression like "--default HEAD^2
" will not resolve as a ref.But that's OK. We fall back to a generic error message in those cases, and they are unlikely to be used anyway.
Catching an empty or broken "HEAD" improves the common case, and the other cases are not regressed.
As others have pointed, having a response entity in an error code is perfectly allowable.
Do remember that 5xx errors are server-side, aka the client cannot change anything to its request to make the request pass. If the client's quota is exceeded, that's definitly not a server error, so 5xx should be avoided.
A modification of the accepted answer above, which also detects the MIME type in runtime:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
header('Content-Type: '.finfo_file($finfo, $path));
$finfo = finfo_open(FILEINFO_MIME_ENCODING);
header('Content-Transfer-Encoding: '.finfo_file($finfo, $path));
header('Content-disposition: attachment; filename="'.basename($path).'"');
readfile($path); // do the double-download-dance (dirty but worky)
I am covering most of the examples of Dependency Injection in ASP.NET Web API 2
public interface IShape
{
string Name { get; set; }
}
public class NoShape : IShape
{
public string Name { get; set; } = "I have No Shape";
}
public class Circle : IShape
{
public string Name { get; set; } = "Circle";
}
public class Rectangle : IShape
{
public Rectangle(string name)
{
this.Name = name;
}
public string Name { get; set; } = "Rectangle";
}
In DIAutoV2Controller.cs Auto Injection mechanism is used
[RoutePrefix("api/v2/DIAutoExample")]
public class DIAutoV2Controller : ApiController
{
private string ConstructorInjected;
private string MethodInjected1;
private string MethodInjected2;
private string MethodInjected3;
[Dependency]
public IShape NoShape { get; set; }
[Dependency("Circle")]
public IShape ShapeCircle { get; set; }
[Dependency("Rectangle")]
public IShape ShapeRectangle { get; set; }
[Dependency("PiValueExample1")]
public double PiValue { get; set; }
[InjectionConstructor]
public DIAutoV2Controller([Dependency("Circle")]IShape shape1, [Dependency("Rectangle")]IShape shape2, IShape shape3)
{
this.ConstructorInjected = shape1.Name + " & " + shape2.Name + " & " + shape3.Name;
}
[NonAction]
[InjectionMethod]
public void Initialize()
{
this.MethodInjected1 = "Default Initialize done";
}
[NonAction]
[InjectionMethod]
public void Initialize2([Dependency("Circle")]IShape shape1)
{
this.MethodInjected2 = shape1.Name;
}
[NonAction]
[InjectionMethod]
public void Initialize3(IShape shape1)
{
this.MethodInjected3 = shape1.Name;
}
[HttpGet]
[Route("constructorinjection")]
public string constructorinjection()
{
return "Constructor Injected: " + this.ConstructorInjected;
}
[HttpGet]
[Route("GetNoShape")]
public string GetNoShape()
{
return "Property Injected: " + this.NoShape.Name;
}
[HttpGet]
[Route("GetShapeCircle")]
public string GetShapeCircle()
{
return "Property Injected: " + this.ShapeCircle.Name;
}
[HttpGet]
[Route("GetShapeRectangle")]
public string GetShapeRectangle()
{
return "Property Injected: " + this.ShapeRectangle.Name;
}
[HttpGet]
[Route("GetPiValue")]
public string GetPiValue()
{
return "Property Injected: " + this.PiValue;
}
[HttpGet]
[Route("MethodInjected1")]
public string InjectionMethod1()
{
return "Method Injected: " + this.MethodInjected1;
}
[HttpGet]
[Route("MethodInjected2")]
public string InjectionMethod2()
{
return "Method Injected: " + this.MethodInjected2;
}
[HttpGet]
[Route("MethodInjected3")]
public string InjectionMethod3()
{
return "Method Injected: " + this.MethodInjected3;
}
}
In DIV2Controller.cs everything will be injected from the Dependency Configuration Resolver class
[RoutePrefix("api/v2/DIExample")]
public class DIV2Controller : ApiController
{
private string ConstructorInjected;
private string MethodInjected1;
private string MethodInjected2;
public string MyPropertyName { get; set; }
public double PiValue1 { get; set; }
public double PiValue2 { get; set; }
public IShape Shape { get; set; }
// MethodInjected
[NonAction]
public void Initialize()
{
this.MethodInjected1 = "Default Initialize done";
}
// MethodInjected
[NonAction]
public void Initialize2(string myproperty1, IShape shape1, string myproperty2, IShape shape2)
{
this.MethodInjected2 = myproperty1 + " & " + shape1.Name + " & " + myproperty2 + " & " + shape2.Name;
}
public DIV2Controller(string myproperty1, IShape shape1, string myproperty2, IShape shape2)
{
this.ConstructorInjected = myproperty1 + " & " + shape1.Name + " & " + myproperty2 + " & " + shape2.Name;
}
[HttpGet]
[Route("constructorinjection")]
public string constructorinjection()
{
return "Constructor Injected: " + this.ConstructorInjected;
}
[HttpGet]
[Route("PropertyInjected")]
public string InjectionProperty()
{
return "Property Injected: " + this.MyPropertyName;
}
[HttpGet]
[Route("GetPiValue1")]
public string GetPiValue1()
{
return "Property Injected: " + this.PiValue1;
}
[HttpGet]
[Route("GetPiValue2")]
public string GetPiValue2()
{
return "Property Injected: " + this.PiValue2;
}
[HttpGet]
[Route("GetShape")]
public string GetShape()
{
return "Property Injected: " + this.Shape.Name;
}
[HttpGet]
[Route("MethodInjected1")]
public string InjectionMethod1()
{
return "Method Injected: " + this.MethodInjected1;
}
[HttpGet]
[Route("MethodInjected2")]
public string InjectionMethod2()
{
return "Method Injected: " + this.MethodInjected2;
}
}
Configuring the Dependency Resolver
public static void Register(HttpConfiguration config)
{
var container = new UnityContainer();
RegisterInterfaces(container);
config.DependencyResolver = new UnityResolver(container);
// Other Web API configuration not shown.
}
private static void RegisterInterfaces(UnityContainer container)
{
var dbContext = new SchoolDbContext();
// Registration with constructor injection
container.RegisterType<IStudentRepository, StudentRepository>(new InjectionConstructor(dbContext));
container.RegisterType<ICourseRepository, CourseRepository>(new InjectionConstructor(dbContext));
// Set constant/default value of Pi = 3.141
container.RegisterInstance<double>("PiValueExample1", 3.141);
container.RegisterInstance<double>("PiValueExample2", 3.14);
// without a name
container.RegisterInstance<IShape>(new NoShape());
// with circle name
container.RegisterType<IShape, Circle>("Circle", new InjectionProperty("Name", "I am Circle"));
// with rectangle name
container.RegisterType<IShape, Rectangle>("Rectangle", new InjectionConstructor("I am Rectangle"));
// Complex type like Constructor, Property and method injection
container.RegisterType<DIV2Controller, DIV2Controller>(
new InjectionConstructor("Constructor Value1", container.Resolve<IShape>("Circle"), "Constructor Value2", container.Resolve<IShape>()),
new InjectionMethod("Initialize"),
new InjectionMethod("Initialize2", "Value1", container.Resolve<IShape>("Circle"), "Value2", container.Resolve<IShape>()),
new InjectionProperty("MyPropertyName", "Property Value"),
new InjectionProperty("PiValue1", container.Resolve<double>("PiValueExample1")),
new InjectionProperty("Shape", container.Resolve<IShape>("Rectangle")),
new InjectionProperty("PiValue2", container.Resolve<double>("PiValueExample2")));
}
This worked for me, as documented on this page:
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();
@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:
css:
.scrollme {
overflow-x: auto;
}
html:
<div class="scrollme">
<table class="table table-responsive"> ...
</table>
</div>
Edit: changing scroll-y to scroll-x
Martijn's method as a prototype function:
String.prototype.escape = function() {
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
return this.replace(/[&<>]/g, function(tag) {
return tagsToReplace[tag] || tag;
});
};
var a = "<abc>";
var b = a.escape(); // "<abc>"
They do behave differently when the value
is null
.
null.toString()
throws an error - Cannot call method 'toString' of nullString(null)
returns - "null"null + ""
also returns - "null"Very similar behaviour happens if value
is undefined
(see jbabey's answer).
Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.
Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.
My hack to automate this was to use an environment variable and access it via --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'"
.
Export an env var, but avoid bash/shell history (prepend with a space, or other methods). E.g.:
export ANSIBLE_BECOME_PASS='<your password>'
Lookup the env var while passing the extra ansible_become_pass
variable into the ansible-playbook
, E.g.:
ansible-playbook playbook.yml -i inventories/dev/hosts.yml -u user --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'"
Good alternate answers:
ansible_become_pass
. This is decent. However, for the paranoid teams that need to share ansible vault passwords, and execute ansible plays with induvidual accounts, they coudld use the shared vault password to reverse each others operating system password (identiy theft). Arguably, you need to trust your own team?@
prefix to read the ansible variable from the file desriptor. Avoids bash history at least. Not sure, but hopefully subshell echo doesn't get caught and exposed in audit logging (e.g. auditd).Here's your solution: JsFiddle
Basically, place your button into a div with centred text:
<div class="wrapper">
<button class="button">Button</button>
</div>
With the following styles:
.wrapper {
text-align: center;
}
.button {
position: absolute;
top: 50%;
}
There are many ways to skin a cat, and this is just one.
i think you use this method to compress the bitmap
BitmapFactory.Option imageOpts = new BitmapFactory.Options ();
imageOpts.inSampleSize = 2; // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(photoPath, imageOpts), 96, 96, false);
This one works for me...
new System.Uri(Page.Request.Url, ResolveClientUrl("~/mypage.aspx")).AbsoluteUri
If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:
Sub norepeat()
Range("C8:C16").RemoveDuplicates (1)
End Sub
Regards
Make sure the filter box is empty
I found some examples are not compatible with python 3 I test one from @Triptych
s = filter(str.isdigit, repr(numList))
num = int(s)
in python 3 it's gonna give error
TypeError: int() argument must be a string, a bytes-like object or a number, not 'filter'
i think the more simple and compatible way would be
def magic(num_list):
return int("".join(map(str, num_list)))
Create a custom return type that will propagate the checked exception. This is an alternative to creating a new interface that mirrors the existing functional interface with the slight modification of a "throws exception" on the functional interface's method.
public static interface CheckedValueSupplier<V> {
public V get () throws Exception;
}
public class CheckedValue<V> {
private final V v;
private final Optional<Exception> opt;
public Value (V v) {
this.v = v;
}
public Value (Exception e) {
this.opt = Optional.of(e);
}
public V get () throws Exception {
if (opt.isPresent()) {
throw opt.get();
}
return v;
}
public Optional<Exception> getException () {
return opt;
}
public static <T> CheckedValue<T> returns (T t) {
return new CheckedValue<T>(t);
}
public static <T> CheckedValue<T> rethrows (Exception e) {
return new CheckedValue<T>(e);
}
public static <V> CheckedValue<V> from (CheckedValueSupplier<V> sup) {
try {
return CheckedValue.returns(sup.get());
} catch (Exception e) {
return Result.rethrows(e);
}
}
public static <V> CheckedValue<V> escalates (CheckedValueSupplier<V> sup) {
try {
return CheckedValue.returns(sup.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
// Don't use this pattern with FileReader, it's meant to be an
// example. FileReader is a Closeable resource and as such should
// be managed in a try-with-resources block or in another safe
// manner that will make sure it is closed properly.
// This will not compile as the FileReader constructor throws
// an IOException.
Function<String, FileReader> sToFr =
(fn) -> new FileReader(Paths.get(fn).toFile());
// Alternative, this will compile.
Function<String, CheckedValue<FileReader>> sToFr = (fn) -> {
return CheckedValue.from (
() -> new FileReader(Paths.get("/home/" + f).toFile()));
};
// Single record usage
// The call to get() will propagate the checked exception if it exists.
FileReader readMe = pToFr.apply("/home/README").get();
// List of records usage
List<String> paths = ...; //a list of paths to files
Collection<CheckedValue<FileReader>> frs =
paths.stream().map(pToFr).collect(Collectors.toList());
// Find out if creation of a file reader failed.
boolean anyErrors = frs.stream()
.filter(f -> f.getException().isPresent())
.findAny().isPresent();
A single functional interface that throws a checked exception is created (CheckedValueSupplier
). This will be the only functional interface which allows checked exceptions. All other functional interfaces will leverage the CheckedValueSupplier
to wrap any code that throws a checked exception.
The CheckedValue
class will hold the result of executing any logic that throws a checked exception. This prevents propagation of a checked exception until the point at which code attempts to access the value that an instance of CheckedValue
contains.
CheckedValue#get()
is called.Some functional interfaces (Consumer
for example) must be handled in a different manner as they don't provide a return value.
One approach is to use a function instead of a consumer, which applies when handling streams.
List<String> lst = Lists.newArrayList();
// won't compile
lst.stream().forEach(e -> throwyMethod(e));
// compiles
lst.stream()
.map(e -> CheckedValueSupplier.from(
() -> {throwyMethod(e); return e;}))
.filter(v -> v.getException().isPresent()); //this example may not actually run due to lazy stream behavior
Alternatively, you can always escalate to a RuntimeException
. There are other answers that cover escalation of a checked exception from within a Consumer
.
Just avoid functional interfaces all together and use a good-ole-fashioned for loop.
I think you just need COUNT(DISTINCT post_id) FROM votes
.
See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.
EDIT: Corrected my careless mistake per Erwin's comment.
I suggest to try out some Reflection approach, if you have time to spend on the debugger (sorry but I didn't have).
Starting from the loadUrl()
method of the android.webkit.WebView
class:
You should arrive on the android.webkit.BrowserFrame
that call the nativeLoadUrl()
native method:
The implementation of the native method should be here:
Wish you good luck!
Well, PHP does have magic methods __get
, __set
, __isset
& __unset
, which is always a start. Alas proper (get it?) OO properties is more than magic methods. The main problem with PHP's implementation is that magic methods are called for all inaccessible properties. Which means you have to Repeat Yourself (eg. by calling property_exists()) in the magic methods when determining if name is actually a property of your object. And you can't really solve this general problem with a base class unless all your classes inherit from ie. ClassWithProperties, since PHP lacks multiple inheritance.
In contrast, Python new style classes gives you property()
, which lets you explicitly define all your properties. C# has special syntax.
Set them so that their flex-basis
is 0
(so all elements have the same starting point), and allow them to grow:
flex: 1 1 0px
Your IDE or linter might mention that the unit of measure 'px' is redundant
. If you leave it out (like: flex: 1 1 0
), IE will not render this correctly. So the px
is required to support Internet Explorer, as mentioned in the comments by @fabb;
Another option:
string s2 = String.Join("," + Environment.NewLine, s1.Split(','));
Cut and paste:
Copy and paste is performed with the same steps except for step 4 where you would press y instead of d:
d = delete
= cut
y = yank
= copy
You also can take an array of keys with type []Value
by method MapKeys
of struct Value
from package "reflect":
package main
import (
"fmt"
"reflect"
)
func main() {
abc := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
keys := reflect.ValueOf(abc).MapKeys()
fmt.Println(keys) // [a b c]
}
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
There's a simple way to get rid of this restriction by using the datePicker component provided by jQuery.
Include jQuery and jQuery UI libraries (I'm still using an old one)
Use the following snip
$(function() {
$( "#id_of_the_component" ).datepicker({ dateFormat: 'yy-mm-dd'});
});
See jQuery UI DatePicker - Change Date Format if needed.
As of July 2016:
Short Answer:
If your game is released for iOS 9.0 or newer, you can have maximum app size of 400 MB for the size of the Mach-O binary file (for example, app_name.app/app_name).
Your app’s total uncompressed size must be less than 4 Gb.
Long Answer:
Your app’s total uncompressed size must be less than 4 billion bytes. Each Mach-O executable file (for example, app_name.app/app_name) must not exceed these limits:
For apps whose MinimumOSVersion is less than 7.0: maximum of 80 MB for the total of all __TEXT sections in the binary.
For apps whose MinimumOSVersion is 7.x through 8.x: maximum of 60 MB per slice for the __TEXT section of each architecture slice in the binary.
For apps whose MinimumOSVersion is 9.0 or greater: maximum of 400 MB for the size of the Mach-O binary file.
However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads. Abnormally large build files are usually the result of storing data, such as images, inside the compiled binary itself instead of as a resource inside your app bundle. If you are compiling an image or large dataset into your binary, it would be best to split this data out into a resource that is loaded dynamically by your app.
Here is the link to Apple Developer Guide that contains the info I posted above:
You can go to the section "Submitting the App for App Review" on the link above to read more on the info I posted above.
You want:
if (document.getElementById('customx').value === ""){
//do something
}
The value
property will give you a string value and you need to compare that against an empty string.
response.GetResponseStream()
should be used to return the response stream. And don't forget to close
the Stream
and Response
objects.
:-) Sunday | 0 -> Sun
|
Monday | 1 -> Mon
Tuesday | 2 -> Tue
Wednesday | 3 -> Wed
Thursday | 4 -> Thu
Friday | 5 -> Fri
Saturday | 6 -> Sat
|
:-) Sunday | 7 -> Sun
As you can see above, and as said before, the numbers 0
and 7
are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.
Examples of Number or Abbreviation Use
15 09 * * 5,6,0 command
15 09 * * 5,6,7 command
15 09 * * 5-7 command
15 09 * * Fri,Sat,Sun command
The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.
In Detail
Having two numbers 0
and 7
for Sunday can be useful for writing weekday ranges starting with 0
or ending with 7
. So you can write ranges starting with Sunday or ending with it, like 0-2
or 5-7
for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.
This is what I ended up using. Temporarily sets target to _blank, then sets it back.
OnClientClick="var originalTarget = document.forms[0].target; document.forms[0].target = '_blank'; setTimeout(function () { document.forms[0].target = originalTarget; }, 3000);"
Arrays are default passed by pointers. You can try modifying an array inside a function call for better understanding.
Using MySQL Workbench it will be shown under "Server Status":
I went into wp-config/ and deleted the object-cache.php and advanced-cache.php and it worked fine for me.
There is no col-??-offset-0. All "rows" assume there is no offset unless it has been specified. I think you are wanting 3 rows on a small screen and 1 row on a medium screen.
To get the result I believe you are looking for try this:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
<div class="col-sm-4 col-md-12">
<p>On small screen there are 3 rows, and on a medium screen 1 row</p>
</div>
</div>
</div>
Keep in mind you will only see a difference on a small tablet with what you described. Medium, large, and extra small screens the columns are spanning 12.
Hope this helps.
In Kotlin you can create extension property:
inline var TextView.underline: Boolean
set(visible) {
paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
}
get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG
And use:
textView.underline = true
you can use pandas.set_option(), for column, you can specify any of these options
pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", 100)
pd.set_option("display.max_colwidth", 200)
For full print column, you can use like this
import pandas as pd
pd.set_option('display.max_colwidth', -1)
print(words.head())
Is it possible to get this above example:
jQuery.fn.highlight = function (str, className)
{
var regex = new RegExp(str, "g");
return this.each(function ()
{
this.innerHTML = this.innerHTML.replace(
regex,
"<span class=\"" + className + "\">" + str + "</span>"
);
});
};
not to replace text inside html-tags like , this otherwise breakes the page.
I like to use enums as arguments to my functions. It's an easy means to provide a fixed list of "options". The trouble with the top voted answer here is that using that, a client can specify an "invalid option". As a spin off, I recommend doing essentially the same thing, but use a constant int outside of the enum to define the count of them.
enum foobar { foo, bar, baz, quz };
const int FOOBAR_NR_ITEMS=4;
It's not pleasant, but it's a clean solution if you don't change the enum without updating the constant.
Just add this namespace,
using System.Linq;
according to what I understood from here:
when you use align-item or justify-item, you are adjusting "the content inside a grid item along the column axis or row axis respectively.
But: if you use align-content or justify-content, you are setting the position a grid along the column axis or the row axis. it occurs when you have a grid in a bigger container and width or height are inflexible (using px).
After placing the jar file in desired location, you need to add the jar file by right click on
Project --> properties --> Java Build Path --> Libraries --> Add Jar.
Just MyString[0]
. This uses the String.Chars indexer.
Use elevation to implement shadows on RN Android. Added elevation prop #27
<View elevation={5}>
</View>
Instead of setting async to false which is usually bad design, you may want to consider blocking the UI while the operation is pending.
This can be nicely achieved with jQuery promises as follows:
// same as $.ajax but settings can have a maskUI property
// if settings.maskUI==true, the UI will be blocked while ajax in progress
// if settings.maskUI is other than true, it's value will be used as the color value while bloking (i.e settings.maskUI='rgba(176,176,176,0.7)'
// in addition an hourglass is displayed while ajax in progress
function ajaxMaskUI(settings) {
function maskPageOn(color) { // color can be ie. 'rgba(176,176,176,0.7)' or 'transparent'
var div = $('#maskPageDiv');
if (div.length === 0) {
$(document.body).append('<div id="maskPageDiv" style="position:fixed;width:100%;height:100%;left:0;top:0;display:none"></div>'); // create it
div = $('#maskPageDiv');
}
if (div.length !== 0) {
div[0].style.zIndex = 2147483647;
div[0].style.backgroundColor=color;
div[0].style.display = 'inline';
}
}
function maskPageOff() {
var div = $('#maskPageDiv');
if (div.length !== 0) {
div[0].style.display = 'none';
div[0].style.zIndex = 'auto';
}
}
function hourglassOn() {
if ($('style:contains("html.hourGlass")').length < 1) $('<style>').text('html.hourGlass, html.hourGlass * { cursor: wait !important; }').appendTo('head');
$('html').addClass('hourGlass');
}
function hourglassOff() {
$('html').removeClass('hourGlass');
}
if (settings.maskUI===true) settings.maskUI='transparent';
if (!!settings.maskUI) {
maskPageOn(settings.maskUI);
hourglassOn();
}
var dfd = new $.Deferred();
$.ajax(settings)
.fail(function(jqXHR, textStatus, errorThrown) {
if (!!settings.maskUI) {
maskPageOff();
hourglassOff();
}
dfd.reject(jqXHR, textStatus, errorThrown);
}).done(function(data, textStatus, jqXHR) {
if (!!settings.maskUI) {
maskPageOff();
hourglassOff();
}
dfd.resolve(data, textStatus, jqXHR);
});
return dfd.promise();
}
with this you can now do:
ajaxMaskUI({
url: url,
maskUI: true // or try for example 'rgba(176,176,176,0.7)'
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log('error ' + textStatus);
}).done(function (data, textStatus, jqXHR) {
console.log('success ' + JSON.stringify(data));
});
And the UI will block until the ajax command returns
see jsfiddle
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
You can use this Autoit script to handle the login popup:
WinWaitActive("Authentication Required","","10")
If WinExists("Authentication Required") Then
Send("username{TAB}")
Send("Password{Enter}")
EndIf'
ZEROFILL
This essentially means that if the integer value 23 is inserted into an INT column with the width of 8 then the rest of the available position will be automatically padded with zeros.
Hence
23
becomes:
00000023
I would use ternary operators to categorize your switch conditions.
So...
switch( number > 9 ? "High" :
number > 5 ? "Mid" :
number > 1 ? "Low" : "Floor")
{
case "High":
do the thing;
break;
case "Mid":
do the other thing;
break;
case "Low":
do something else;
break;
case "Floor":
do whatever;
break;
}
For a single result:
if (reader.Read())
{
Response.Write(reader[0].ToString());
Response.Write(reader[1].ToString());
}
For multiple results:
while (reader.Read())
{
Response.Write(reader[0].ToString());
Response.Write(reader[1].ToString());
}
I recommend setting an alternative location for your npm modules.
npm config set prefix C:\Dev\npm-repository\npm --global
npm config set cache C:\Dev\npm-repository\npm-cache --global
Of course you can set the location to wherever best suits.
This has worked well for me and gets around any permissions issues that you may encounter.
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
This may be new:
https://artifactory.example.com/artifactory/repo/com/example/foo/1.0.[RELEASE]/foo-1.0.[RELEASE].tgz
For loading module foo from example.com . Keep the [RELEASE] parts verbatim. This is mentioned in the docs but it's not made abundantly clear that you can actually put [RELEASE] into the URL (as opposed to a substitution pattern for the developer).
Windows doesn't ignore anything. This is an issue with your setup; Windows just uses what you provide. It has no special knowledge of JAVA_HOME
.
CLASSPATH
has nothing to do with Windows, either. To Windows it's only an environmental variable that gets expanded to a folder location.
Check your %PATH%
environmental variable. It's what's making Windows find one before the other. The path (as the post you linked to said) should point to %JAVA_HOME%\bin;<remainder of path>
. Again, the post you linked to gave you a way to set this using a batch file.
(For others who might not know this: The easiest way to inspect the %PATH% is to open a command prompt and type echo %PATH%
. You can also get there by right-clicking on Computer
in the right pane of the Start Menu and choosing Properties
, then Advanced System Settings
, and the tne Environmental Variables
button.)
yes, I know, I'm too late (as always). Here is my piece of code (based on the reply of mk2). Maybe this helps someone:
std::vector<std::string> find_serial_ports()
{
std::vector<std::string> ports;
std::filesystem::path kdr_path{"/proc/tty/drivers"};
if (std::filesystem::exists(kdr_path))
{
std::ifstream ifile(kdr_path.generic_string());
std::string line;
std::vector<std::string> prefixes;
while (std::getline(ifile, line))
{
std::vector<std::string> items;
auto it = line.find_first_not_of(' ');
while (it != std::string::npos)
{
auto it2 = line.substr(it).find_first_of(' ');
if (it2 == std::string::npos)
{
items.push_back(line.substr(it));
break;
}
it2 += it;
items.push_back(line.substr(it, it2 - it));
it = it2 + line.substr(it2).find_first_not_of(' ');
}
if (items.size() >= 5)
{
if (items[4] == "serial" && items[0].find("serial") != std::string::npos)
{
prefixes.emplace_back(items[1]);
}
}
}
ifile.close();
for (auto& p: std::filesystem::directory_iterator("/dev"))
{
for (const auto& pf : prefixes)
{
auto dev_path = p.path().generic_string();
if (dev_path.size() >= pf.size() && std::equal(dev_path.begin(), dev_path.begin() + pf.size(), pf.begin()))
{
ports.emplace_back(dev_path);
}
}
}
}
return ports;
}
From the manual:
Possible values for the parameter timeout: … x set timeout to x seconds
and
readlines(sizehint=None, eol='\n') Read a list of lines, until timeout. sizehint is ignored and only present for API compatibility with built-in File objects.
Note that this function only returns on a timeout.
So your readlines
will return at most every 2 seconds. Use read()
as Tim suggested.
Instead of adding any tag which is never a good solution. You can always use margin
property with the required element.
You can add the margin on row class itself. So it will affect globally.
.row{
margin-top: 30px;
margin-bottom: 30px
}
Update: Better solution in all cases would be to introduce a new class and then use it along with .row
class.
.row-m-t{
margin-top : 20px
}
Then use it wherever you want
<div class="row row-m-t"></div>
SEARCH
does not return 0
if there is no match, it returns #VALUE!
. So you have to wrap calls to SEARCH
with IFERROR
.
For example...
=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")
or
=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))
Here, IFERROR
returns the value from SEARCH
when it works; the given value of 0
otherwise.
Make sure you select the function that needs to be executed. See screenshot:
The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.
So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net
If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.
Use the following if you have discrete columns to plot in a graph
do for [indx in "2 3 7 8"] {
column = indx + 0
plot ifile using 1:column ;
}
Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx
Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\
In the folder path F:\Temp\
, create an Excel 2007 spreadsheet file named States_1.xlsx
with two worksheets.
Sheet 1
of States_1.xlsx contained the following data
Sheet 2
of States_1.xlsx contained the following data
In the folder path F:\Temp\
, create another Excel 2007 spreadsheet file named States_2.xlsx
with two worksheets.
Sheet 1
of States_2.xlsx contained the following data
Sheet 2
of States_2.xlsx contained the following data
Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.
CREATE TABLE [dbo].[Destination](
[Id] [int] IDENTITY(1,1) NOT NULL,
[State] [nvarchar](255) NULL,
[Country] [nvarchar](255) NULL,
[FilePath] [nvarchar](255) NULL,
[SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO
The table is currently empty.
Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx
. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx
of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$
to avoid design time error.
In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.
Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider
under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx
Click on the All
section on the left side and set the property Extended Properties to Excel 12.0
to denote the version of Excel. Here in this case 12.0 denotes Excel 2007
. Click on the Test Connection to make sure that the connection succeeds.
Create an Excel connection manager named Excel as shown below.
Create an OLE DB Connection SQL Server named SQLServer
. So, we should have three connections on the package as shown below.
We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.
On the connection ExcelSchema, configure the expression ServerName
to use the variable FilePath
. Click on the ellipsis button to configure the expression.
Similarly on the connection Excel, configure the expression ServerName
to use the variable FilePath
. Click on the ellipsis button to configure the expression.
On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container
named Loop files will loop through the files. The second Foreach Loop container
will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL
Configure the first Foreach loop container named Loop files as shown below:
Configure the first Foreach loop container named Loop sheets as shown below:
Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:
Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.
Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.
Configure the OLE DB destination to insert the data into the SQL table.
Below screenshot shows successful execution of the package.
Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.
Hope that helps.
there any rule I can follow to be sure that my app executes my own code just in the main thread?
Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.
If you want to be really sure, you can do things like
[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];
to execute a method on the main thread. (There's a GCD equivalent too.)
In your code, you can find this function:
// Update a particular HTML element with a new value
function updateHTML(elmId, value) {
document.getElementById(elmId).innerHTML = value;
}
Later on, you call this function with several params:
updateHTML("videoCurrentTime", secondsToHms(ytplayer.getCurrentTime())+' /');
updateHTML("videoDuration", secondsToHms(ytplayer.getDuration()));
updateHTML("bytesTotal", ytplayer.getVideoBytesTotal());
updateHTML("startBytes", ytplayer.getVideoStartBytes());
updateHTML("bytesLoaded", ytplayer.getVideoBytesLoaded());
updateHTML("volume", ytplayer.getVolume());
The first param is used for the "getElementById", but the elements with ID "bytesTotal", "startBytes", "bytesLoaded" and "volume" don't exist. You'll need to create them, since they'll return null.
To overcome this problem you can write an ActionMethodSelectorAttribute
that examines the MethodInfo
for each action and compares it to the posted Form values and then rejects any method for which the form values don't match (excluding the button name, of course).
Here's an example:- http://blog.abodit.com/2010/02/asp-net-mvc-ambiguous-match/
BUT, this isn't a good idea.
or you can just read js file by server with file_get_contets and then put in echo in the header the js contents
With padding:
function dec2hex(i) {
return (i+0x10000).toString(16).substr(-4).toUpperCase();
}
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
A good way to have a synthetic view of what's going on "origin" is:
git remote show origin
In case this happens to anyone else who tried both alphazero and Paul's method and still didn't work.
For me, eclipse somehow 'cached' the compile errors even after doing a Project > Clean...
I had to uncheck Project > Build Automatically, then do a Project > Clean, and then build again.
Also, when in doubt, try restarting Eclipse. This can fix a lot of awkward, unexplainable errors.
777
is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images..
You said I am using windows 7.
if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone
and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder.
If you want permission to be set on sub-directories
too then usually their is option to set permission recursively use that.
And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes
and write the following command
chmod 0777 module_installation/
for recursive
chmod -R 0777 module_installation/
Hope this will help you
const mergeByProperty = (target, source, prop) => {
source.forEach(sourceElement => {
let targetElement = target.find(targetElement => {
return sourceElement[prop] === targetElement[prop];
})
targetElement ? Object.assign(targetElement, sourceElement) : target.push(sourceElement);
})
}
var target /* arr1 */ = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var source /* arr2 */ = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
mergeByProperty(target, source, 'name');
console.log(target)
_x000D_
This answer was getting old, libs like lodash and underscore are much less needed these days. In this new version, the target (arr1) array is the one we’re working with and want to keep up to date. The source (arr2) array is where the new data is coming from, and we want it merged into our target array.
We loop over the source array looking for new data, and for every object that is not yet found in our target array we simply add that object using target.push(sourceElement) If, based on our key property ('name'), an object is already in our target array - we update its properties and values using Object.assign(targetElement, sourceElement). Our “target” will always be the same array and with updated content.
I always arrive here from google and I'm always not satisfy from the answers. YOU answer is good but it'll be easier and neater using underscore.js
DEMO: http://jsfiddle.net/guya/eAWKR/
Here is a more general function that will merge 2 arrays using a property of their objects. In this case the property is 'name'
var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];
function mergeByProperty(arr1, arr2, prop) {
_.each(arr2, function(arr2obj) {
var arr1obj = _.find(arr1, function(arr1obj) {
return arr1obj[prop] === arr2obj[prop];
});
arr1obj ? _.extend(arr1obj, arr2obj) : arr1.push(arr2obj);
});
}
mergeByProperty(arr1, arr2, 'name');
console.log(arr1);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>
_x000D_
[{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]
Actions at=new Actions(wd);
at.moveToElement(we);
at.contextClick(we).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
This will output the number of lines that contain your search string.
grep -c "echo" FILE
This won't, however, count the number of occurrences in the file (ie, if you have echo multiple times on one line).
edit:
After playing around a bit, you could get the number of occurrences using this dirty little bit of code:
sed 's/echo/echo\n/g' FILE | grep -c "echo"
This basically adds a newline following every instance of echo so they're each on their own line, allowing grep to count those lines. You can refine the regex if you only want the word "echo", as opposed to "echoing", for example.
Get Username and password
Make it more clear to read but put it on a better position over the screen
#!/bin/bash
clear
echo
echo
echo
counter=0
unset username
prompt=" Enter Username:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
if [[ $char == $'\0' ]]; then
break
elif [ $char == $'\x08' ] && [ $counter -gt 0 ]; then
prompt=$'\b \b'
username="${username%?}"
counter=$((counter-1))
elif [ $char == $'\x08' ] && [ $counter -lt 1 ]; then
prompt=''
continue
else
counter=$((counter+1))
prompt="$char"
username+="$char"
fi
done
echo
unset password
prompt=" Enter Password:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
if [[ $char == $'\0' ]]; then
break
elif [ $char == $'\x08' ] && [ $counter -gt 0 ]; then
prompt=$'\b \b'
password="${password%?}"
counter=$((counter-1))
elif [ $char == $'\x08' ] && [ $counter -lt 1 ]; then
echo
prompt=" Enter Password:"
continue
else
counter=$((counter+1))
prompt='*'
password+="$char"
fi
done
This one works for me:
<tr style="height: 15px;"/>
It could depend on your framework. (for each of them could exist an easier solution).
But to answer your question: there are a lot of external libraries for this functionality. Look here how to use apache commons fileupload.
For me, it was because the backup file was still open by another process. Here's the event log:
BackupDiskFile::OpenMedia: Backup device 'X:\Backups\MyDatabase\MyDatabase_backup_2014_08_22_132234_8270986.bak' failed to open. Operating system error 32(The process cannot access the file because it is being used by another process.).
Simply closing and reopening Sql Server Management Studio resolved it (so obviously it was ssms.exe that had the handle..)
Please remove all jar files of Http from libs folder and add below dependencies in gradle file :
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4.3'
Thanks.
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
For PDO You may do this
$stmt1 = "INSERT INTO users (username, password) VALUES('test', 'test')";
$stmt2 = "INSERT INTO profiles (userid, bio, homepage) VALUES('LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com')";
$sth1 = $dbh->prepare($stmt1);
$sth2 = $dbh->prepare($stmt2);
BEGIN;
$sth1->execute (array ('test','test'));
$sth2->execute (array ('Hello world!','http://www.stackoverflow.com'));
COMMIT;
You seem to be specifying the form to use a HTTP 'GET' request using FormMethod.Get
. This will not work unless you tell it to do a post as that is what you seem to want the ActionResult to do. This will probably work by changing FormMethod.Get
to FormMethod.Post
.
As well as this you may also want to think about how Get and Post requests work and how these interact with the Model.
It happens when common column in both table are of different data type.
Example: In table1, you have date as string whereas in table2 you have date as datetime. so before merging,we need to change date to common data type.
$(document).on('change', '#id', aFunc);
function aFunc() {
// code here...
}
In some cases margin="0 auto" won't cut the mustard when center aligning a html email in Outlook 2007, 2010, 2013.
Try the following:
Wrap your content in another table with style="table-layout: fixed;" and align=“center”.
<!-- WRAPPING TABLE -->
<table cellpadding="0" cellspacing="0" border="0" style="table-layout: fixed;" align="center">
<tr>
<td>
<!-- YOUR TABLES AND EMAIL CONTENT GOES HERE -->
</td>
</tr>
</table>
Month.of( yourMonthNumber ) // Represent a month by its number, 1-12 for January-December.
.getDisplayName( // Generate text of the name of the month automatically localized.
TextStyle.SHORT_STANDALONE , // Specify how long or abbreviated the name of month should be.
new Locale( "es" , "MX" ) // Locale determines (a) the human language used in translation, and (b) the cultural norms used in deciding issues of abbreviation, capitalization, punctuation, and so on.
) // Returns a String.
java.time.Month
Much easier to do now in the java.time classes that supplant these troublesome old legacy date-time classes.
The Month
enum defines a dozen objects, one for each month.
The months are numbered 1-12 for January-December.
Month month = Month.of( 2 ); // 2 ? February.
Ask the object to generate a String of the name of the month, automatically localized.
Adjust the TextStyle
to specify how long or abbreviated you want the name. Note that in some languages (not English) the month name varies if used alone or as part of a complete date. So each text style has a …_STANDALONE
variant.
Specify a Locale
to determine:
Example:
Locale l = new Locale( "es" , "MX" );
String output = Month.FEBRUARY.getDisplayName( TextStyle.SHORT_STANDALONE , l ); // Or Locale.US, Locale.CANADA_FRENCH.
Month
objectFYI, going the other direction (parsing a name-of-month string to get a Month
enum object) is not built-in. You could write your own class to do so. Here is my quick attempt at such a class. Use at your own risk. I gave this code no serious thought nor any serious testing.
Usage.
Month m = MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ; // Month.JANUARY
Code.
package com.basilbourque.example;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
// For a given name of month in some language, determine the matching `java.time.Month` enum object.
// This class is the opposite of `Month.getDisplayName` which generates a localized string for a given `Month` object.
// Usage… MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ) ? Month.JANUARY
// Assumes `FormatStyle.FULL`, for names without abbreviation.
// About `java.time.Month` enum: https://docs.oracle.com/javase/9/docs/api/java/time/Month.html
// USE AT YOUR OWN RISK. Provided without guarantee or warranty. No serious testing or code review was performed.
public class MonthDelocalizer
{
@NotNull
private Locale locale;
@NotNull
private List < String > monthNames, monthNamesStandalone; // Some languages use an alternate spelling for a “standalone” month name used without the context of a date.
// Constructor. Private, for static factory method.
private MonthDelocalizer ( @NotNull Locale locale )
{
this.locale = locale;
// Populate the pair of arrays, each having the translated month names.
int countMonthsInYear = 12; // Twelve months in the year.
this.monthNames = new ArrayList <>( countMonthsInYear );
this.monthNamesStandalone = new ArrayList <>( countMonthsInYear );
for ( int i = 1 ; i <= countMonthsInYear ; i++ )
{
this.monthNames.add( Month.of( i ).getDisplayName( TextStyle.FULL , this.locale ) );
this.monthNamesStandalone.add( Month.of( i ).getDisplayName( TextStyle.FULL_STANDALONE , this.locale ) );
}
// System.out.println( this.monthNames );
// System.out.println( this.monthNamesStandalone );
}
// Constructor. Private, for static factory method.
// Personally, I think it unwise to default implicitly to a `Locale`. But I included this in case you disagree with me, and to follow the lead of the *java.time* classes. --Basil Bourque
private MonthDelocalizer ( )
{
this( Locale.getDefault() );
}
// static factory method, instead of constructors.
// See article by Dr. Joshua Bloch. http://www.informit.com/articles/article.aspx?p=1216151
// The `Locale` argument determines the human language and cultural norms used in de-localizing input strings.
synchronized static public MonthDelocalizer of ( @NotNull Locale localeArg )
{
MonthDelocalizer x = new MonthDelocalizer( localeArg ); // This class could be optimized by caching this object.
return x;
}
// Attempt to translate the name of a month to look-up a matching `Month` enum object.
// Returns NULL if the passed String value is not found to be a valid name of month for the human language and cultural norms of the `Locale` specified when constructing this parent object, `MonthDelocalizer`.
@Nullable
public Month parse ( @NotNull String input )
{
int index = this.monthNames.indexOf( input );
if ( - 1 == index )
{ // If no hit in the contextual names, try the standalone names.
index = this.monthNamesStandalone.indexOf( input );
}
int ordinal = ( index + 1 );
Month m = ( ordinal > 0 ) ? Month.of( ordinal ) : null; // If we have a hit, determine the `Month` enum object. Else return null.
if ( null == m )
{
throw new java.lang.IllegalArgumentException( "The passed month name: ‘" + input + "’ is not valid for locale: " + this.locale.toString() );
}
return m;
}
// `Object` class overrides.
@Override
public boolean equals ( Object o )
{
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;
MonthDelocalizer that = ( MonthDelocalizer ) o;
return locale.equals( that.locale );
}
@Override
public int hashCode ( )
{
return locale.hashCode();
}
public static void main ( String[] args )
{
// Usage example:
MonthDelocalizer monthDelocJapan = MonthDelocalizer.of( Locale.JAPAN );
try
{
Month m = monthDelocJapan.parse( "pink elephant" ); // Invalid input.
} catch ( IllegalArgumentException e )
{
// … handle error
System.out.println( "ERROR: " + e.getLocalizedMessage() );
}
// Ignore exception. (not recommended)
if ( MonthDelocalizer.of( Locale.CANADA_FRENCH ).parse( "janvier" ).equals( Month.JANUARY ) )
{
System.out.println( "GOOD - In locale "+Locale.CANADA_FRENCH+", the input ‘janvier’ parses to Month.JANUARY." );
}
}
}
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Yes,
You are trying to access an element of the list that does not exist.
MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.
Have you got an off-by-one error?
I guess cross selection is not active anymore. We should use instead model selection. You can write it to run, from sklearn.model_selection import train_test_split
Thats it.
I was recently faced with this problem, and with no simple solution since my fields can be prepopulated, I wanted to share an elegant hack I came up with by setting password type in the ready event.
Don't declare your input field as type password when creating it, but add a ready event listener to add it for you:
function createSecretTextInput(name,parent){
var createInput = document.createElement("input");
createInput.setAttribute('name', name);
createInput.setAttribute('class', 'secretText');
createInput.setAttribute('id', name+'SecretText');
createInput.setAttribute('value', 'test1234');
if(parent==null)
document.body.appendChild(createInput);
else
document.getElementById(parent).appendChild(createInput);
$(function(){
document.getElementById(name+'SecretText').setAttribute('type', 'password');
});
};
createSecretTextInput('name', null);
I'm a recent student but I BELIEVE the original example with int[] is iterating over the primitives array, but not by using an Iterator object. It merely has the same (similar) syntax with different contents,
for (primitive_type : array) { }
for (object_type : iterableObject) { }
Arrays.asList() APPARENTLY just applies List methods to an object array that it's given - but for any other kind of object, including a primitive array, iterator().next() APPARENTLY just hands you the reference to the original object, treating it as a list with one element. Can we see source code for this? Wouldn't you prefer an exception? Never mind. I guess (that's GUESS) that it's like (or it IS) a singleton Collection. So here asList() is irrelevant to the case with a primitives array, but confusing. I don't KNOW I'm right, but I wrote a program that says that I am.
Thus this example (where basically asList() doesn't do what you thought it would, and therefore is not something that you'd actually use this way) - I hope the code works better than my marking-as-code, and, hey, look at that last line:
// Java(TM) SE Runtime Environment (build 1.6.0_19-b04)
import java.util.*;
public class Page0434Ex00Ver07 {
public static void main(String[] args) {
int[] ii = new int[4];
ii[0] = 2;
ii[1] = 3;
ii[2] = 5;
ii[3] = 7;
Arrays.asList(ii);
Iterator ai = Arrays.asList(ii).iterator();
int[] i2 = (int[]) ai.next();
for (int i : i2) {
System.out.println(i);
}
System.out.println(Arrays.asList(12345678).iterator().next());
}
}
I have not compiled this as it is meant for a proof of concept. This is how I have implemented a Progress bar for database access in the past. This example shows access to a SQLite database using the System.Data.SQLite module
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
using(SQLiteConnection cnn = new SQLiteConnection("Data Source=MyDatabase.db"))
{
cnn.Open();
int TotalQuerySize = GetQueryCount("Query", cnn); // This needs to be implemented and is not shown in example
using (SQLiteCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = "Query is here";
using(SQLiteDataReader reader = cmd.ExecuteReader())
{
int i = 0;
while(reader.Read())
{
// Access the database data using the reader[]. Each .Read() provides the next Row
if(worker.WorkerReportsProgress) worker.ReportProgress(++i * 100/ TotalQuerySize);
}
}
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Notify someone that the database access is finished. Do stuff to clean up if needed
// This could be a good time to hide, clear or do somthign to the progress bar
}
public void AcessMySQLiteDatabase()
{
BackgroundWorker backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorker1_ProgressChanged);
}
Intel provides pre-compiled Python modules for free in their "Intel Distribution for Python". The modules are compiled against Intel's MKL (Math Kernel Library) and thus optimized for faster performance. The package includes NumPy, SciPy, scikit-learn, pandas, matplotlib, Numba, tbb, pyDAAL, Jupyter, and others. Find more information and the download link here
Change this line:
Aboutme.Text = String.Format("{0}", reader.GetString(0));
If you have a code like
int arr[10] = {0, 5, 3, 64};
, and you want to append or add a value to next index, you can simply add it by typing a[5] = 5
.
The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8
to index 9, I can do it by the above concept prior to filling up before indices.
But in python by using list.append()
you can do it by continued indices.
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.
You have to inherit nusoap.php
class and put it in your project directory, you can download it from the Internet.
Use this code:
require_once('nusoap.php');
I am deploying VB6 IIS Applications to my remote dedicated server with 75 folders. The reason I was getting this error is the Default Document was not set on one of the folders, an oversight, so the URL hitting that folder did not know which page to server up, and thus threw the error mentioned in this thread.
@Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
Try this
div{_x000D_
display: block;_x000D_
display: -webkit-box;_x000D_
height: 20px;_x000D_
margin: 3px auto;_x000D_
font-size: 14px;_x000D_
line-height: 1.4;_x000D_
-webkit-line-clamp: 1;_x000D_
-webkit-box-orient: vertical;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
the property text-overflow: ellipsis add ... and line-clamp show the number of lines.
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
Programmatically in Swift 5 with Xcode 10.2
Building on top of @La masse's solution, but using autolayout to support rotation
Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)
label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()
If setting frame.width dynamically using UIScreen:
extension UIScreen { // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
class func absoluteWidth() -> CGFloat {
var width: CGFloat
if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
width = self.main.bounds.height // Landscape
} else {
width = self.main.bounds.width // Portrait
}
return width
}
}
In PowerShell v5.1 this is slightly different compared to v5. According to MS documentation, it has to have a -Path
parameter to specify the archive file path.
Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference
Or else, this can be an actual path:
Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference
If you are planing to use the same image for retina and non-retina screen then here is the solution. Say that you have a image of 200x200
and have two icons in top row and two icon in bottom row. So, it's four quadrants.
.sprite-of-icons {
background: url("../images/icons-in-four-quad-of-200by200.png") no-repeat;
background-size: 100px 100px /* Scale it down to 50% rather using 200x200 */
}
.sp-logo-1 { background-position: 0 0; }
/* Reduce positioning of the icons down to 50% rather using -50px */
.sp-logo-2 { background-position: -25px 0 }
.sp-logo-3 { background-position: 0 -25px }
.sp-logo-3 { background-position: -25px -25px }
Scaling and positioning of the sprite icons to 50% than actual value, you can get the expected result.
Another handy SCSS mixin solution by Ryan Benhase.
/****************************
HIGH PPI DISPLAY BACKGROUNDS
*****************************/
@mixin background-2x($path, $ext: "png", $w: auto, $h: auto, $pos: left top, $repeat: no-repeat) {
$at1x_path: "#{$path}.#{$ext}";
$at2x_path: "#{$path}@2x.#{$ext}";
background-image: url("#{$at1x_path}");
background-size: $w $h;
background-position: $pos;
background-repeat: $repeat;
@media all and (-webkit-min-device-pixel-ratio : 1.5),
all and (-o-min-device-pixel-ratio: 3/2),
all and (min--moz-device-pixel-ratio: 1.5),
all and (min-device-pixel-ratio: 1.5) {
background-image: url("#{$at2x_path}");
}
}
div.background {
@include background-2x( 'path/to/image', 'jpg', 100px, 100px, center center, repeat-x );
}
For more info about above mixin READ HERE.
To change the font size of the <input />
tag in HTML, use this:
<input style="font-size:20px" type="text" value="" />
It will create a text input box and the text inside the text box will be 20 pixels.
HashMap doesn't have "the last position", as it is not sorted.
You may use other Map
which implements java.util.SortedMap
, most popular one is TreeMap
.
Why not use the built in functionality built especially for this task?
let myArray: [Any] = ["easy", "as", "that"]
let type = type(of: myArray)
Result: "Array<Any>"
DECLARE @TABLE TABLE
(RowNo INT,ScripName VARCHAR(10),ScripCode VARCHAR(10)
,Price VARCHAR(10))
INSERT INTO @TABLE VALUES
(1,'20 MICRONS ','533022','39')
SELECT ColumnName,ColumnValue from @Table
Unpivot(ColumnValue For ColumnName IN (ScripName,ScripCode,Price)) AS H
Following Step to to enable disable ARC
Select Xcode project Go to targets Select the Build phases section Inside the build phases section select the compile sources. Select the file which you do not want to disable ARC and add -fno-objc-arc
Returns true if comes 'y', '1', 'true', 'on'or whatever you add in similar way
boolean getValue(String value) {
return ("Y".equals(value.toUpperCase())
|| "1".equals(value.toUpperCase())
|| "TRUE".equals(value.toUpperCase())
|| "ON".equals(value.toUpperCase())
);
}
A short function I wrote a while back to pack a wchar_t array into a char array. Characters that aren't on the ANSI code page (0-127) are replaced by '?' characters, and it handles surrogate pairs correctly.
size_t to_narrow(const wchar_t * src, char * dest, size_t dest_len){
size_t i;
wchar_t code;
i = 0;
while (src[i] != '\0' && i < (dest_len - 1)){
code = src[i];
if (code < 128)
dest[i] = char(code);
else{
dest[i] = '?';
if (code >= 0xD800 && code <= 0xD8FF)
// lead surrogate, skip the next code unit, which is the trail
i++;
}
i++;
}
dest[i] = '\0';
return i - 1;
}
For file deletion, I wrote following simple batch file which deleted all .pdf's recursively:
del /s /q "\\ad1pfrtg001\AppDev\ResultLogs\*.pdf"
del /s /q "\\ad1pfrtg001\Project\AppData\*.pdf"
Even for the local directory we can use it as:
del /s /q "C:\Project\*.pdf"
The same can be applied for directory deletion where we just need to change del with rmdir.
All of the above failed for me. However, I was able to resolve the problem (after many hours of banging my head - Google, if you're listening, please consider fixing what I encountered below in the form of compiler errors, if possible)
You really have to be careful of what android attributes you add to your xml layout here (in this original question, it is called list_items.xml). For me, what was causing the problem was that I had switched from an EditText view to a TextView and had leftover attribute cruft from the change (in my case, inputType). The compiler didn't catch it and the clickability just failed when I went to run the app. Double check all of the attributes you have in your layout xml nodes.
The calculation of the zoom level for the longitudes of Giles Gardam works fine for me. If you want to calculate the zoom factor for latitude, this is an easy solution that works fine:
double minLat = ...;
double maxLat = ...;
double midAngle = (maxLat+minLat)/2;
//alpha is the non-negative angle distance of alpha and beta to midangle
double alpha = maxLat-midAngle;
//Projection screen is orthogonal to vector with angle midAngle
//portion of horizontal scale:
double yPortion = Math.sin(alpha*Math.pi/180) / 2;
double latZoom = Math.log(mapSize.height / GLOBE_WIDTH / yPortion) / Math.ln2;
//return min (max zoom) of both zoom levels
double zoom = Math.min(lngZoom, latZoom);
This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin.
Thank You
I have not tried, but if you know Perl you can use the Parse-Stata-DtaReader module to convert the file for you.
The module has a command-line tool dta2csv, which can "convert Stata 8 and Stata 10 .dta files to csv"
if you want just the parts of url after http://domain.com, try this:
<?php echo $_SERVER['REQUEST_URI']; ?>
if the current url was http://domain.com/some-slug/some-id, echo will return only '/some-slug/some-id'.
if you want the full url, try this:
<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>
There are two possibilities, both from Quest Software, TOAD & SQL Navigator:
Here is the TOAD Freeware download: http://www.toadworld.com/Downloads/FreewareandTrials/ToadforOracleFreeware/tabid/558/Default.aspx
And the SQL Navigator (trial version): http://www.quest.com/sql-navigator/software-downloads.aspx
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
talonmies' answer above is a fine way to abort an application in an assert
-style manner.
Occasionally we may wish to report and recover from an error condition in a C++ context as part of a larger application.
Here's a reasonably terse way to do that by throwing a C++ exception derived from std::runtime_error
using thrust::system_error
:
#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
#include <sstream>
void throw_on_cuda_error(cudaError_t code, const char *file, int line)
{
if(code != cudaSuccess)
{
std::stringstream ss;
ss << file << "(" << line << ")";
std::string file_and_line;
ss >> file_and_line;
throw thrust::system_error(code, thrust::cuda_category(), file_and_line);
}
}
This will incorporate the filename, line number, and an English language description of the cudaError_t
into the thrown exception's .what()
member:
#include <iostream>
int main()
{
try
{
// do something crazy
throw_on_cuda_error(cudaSetDevice(-1), __FILE__, __LINE__);
}
catch(thrust::system_error &e)
{
std::cerr << "CUDA error after cudaSetDevice: " << e.what() << std::endl;
// oops, recover
cudaSetDevice(0);
}
return 0;
}
The output:
$ nvcc exception.cu -run
CUDA error after cudaSetDevice: exception.cu(23): invalid device ordinal
A client of some_function
can distinguish CUDA errors from other kinds of errors if desired:
try
{
// call some_function which may throw something
some_function();
}
catch(thrust::system_error &e)
{
std::cerr << "CUDA error during some_function: " << e.what() << std::endl;
}
catch(std::bad_alloc &e)
{
std::cerr << "Bad memory allocation during some_function: " << e.what() << std::endl;
}
catch(std::runtime_error &e)
{
std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}
catch(...)
{
std::cerr << "Some other kind of error during some_function" << std::endl;
// no idea what to do, so just rethrow the exception
throw;
}
Because thrust::system_error
is a std::runtime_error
, we can alternatively handle it in the same manner of a broad class of errors if we don't require the precision of the previous example:
try
{
// call some_function which may throw something
some_function();
}
catch(std::runtime_error &e)
{
std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}
If you use <tbody>
or <tfoot>
in your table, you'll have to use the following syntax or you'll get a incorrect value:
var rowCount = $('#myTable >tbody >tr').length;
$.map
is probably the most efficient way to do this.
var options = $('#selectBox option');
var values = $.map(options ,function(option) {
return option.value;
});
You can add change options to $('#selectBox option:selected')
if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map
function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.
Issue on my side(while deploying on localhost): there was views folder missing.. so if you have don't have the framework folder the you 'll need to add folders. but if already framework folder exist then make sure all above folders i.e 1. cache 2. session 3. views
exists in your framework directory.
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
I used this command and it worked fine with me:
>git push -f origin master
But notice, that may delete some files you already have on the remote repo. That came in handy with me as the scenario was different; I was pushing my local project to the remote repo which was empty but the READ.ME
config
is another option:
widget1.config(bg='black')
widget2.config(bg='#000000')
or:
widget1.config(background='black')
widget2.config(background='#000000')
The combined answer for writing to a file can be;
MemoryStream ms = new MemoryStream();
FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
A char
represents a character in Java (*). It is 2 bytes large (at least that's what the valid value range suggests).
That doesn't necessarily mean that every representation of a character is 2 bytes long. In fact many encodings only reserve 1 byte for every character (or use 1 byte for the most common characters).
When you call the String(byte[])
constructor you ask Java to convert the byte[]
to a String
using the platform default encoding. Since the platform default encoding is usually a 1-byte encoding such as ISO-8859-1 or a variable-length encoding such as UTF-8, it can easily convert that 1 byte to a single character.
If you run that code on a platform that uses UTF-16 (or UTF-32 or UCS-2 or UCS-4 or ...) as the platform default encoding, then you will not get a valid result (you'll get a String
containing the Unicode Replacement Character instead).
That's one of the reasons why you should not depend on the platform default encoding: when converting between byte[]
and char[]
/String
or between InputStream
and Reader
or between OutputStream
and Writer
, you should always specify which encoding you want to use. If you don't, then your code will be platform-dependent.
(*) that's not entirely true: a char
represents a UTF-16 codepoint. Either one or two UTF-16 codepoints represent a Unicode codepoint. A Unicode codepoint usually represents a character, but sometimes multiple Unicode codepoints are used to make up a single character. But the approximation above is close enough to discuss the topic at hand.
Edit 2018-02-06: revision based on this comment
Edit: forgot to mention that this works on Python 2.7.x
There's multiprocesing.pool, and the following sample illustrates how to use one of them:
from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool
pool_size = 5 # your "parallelness"
# define worker function before a Pool is instantiated
def worker(item):
try:
api.my_operation(item)
except:
print('error with item')
pool = Pool(pool_size)
for item in items:
pool.apply_async(worker, (item,))
pool.close()
pool.join()
Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers
I was playing with the code given by @tinfini, and thought people might benefit from what I think is a slightly more elegant solution (note I don't think scripts worked quite the same way when he created the original answer)...
//Note that this function assumes a single column of values, it will
//not function properly if given a multi-dimensional array (if the
//cells that are captured are not in a single row).
function LastInRange(values)
{
for (index = values.length - 1; values[index] == "" && index > 0; index--) {}
return String(values[index]);
}
In usage it would look like this:
=LastInRange(D2:D)
import os
os.system("pip install beautifulsoup4")
or
import subprocess
exe = subprocess.Popen("pip install beautifulsoup4")
exe_out = exe.communicate()
print(exe_out)
You are probably behind a firewall. Try cloning via https – that has a higher chance of not being blocked:
git clone https://github.com/angular/angular-phonecat.git
It allows you to provide a default value if the key is missing:
dictionary.get("bogus", default_value)
returns default_value
(whatever you choose it to be), whereas
dictionary["bogus"]
would raise a KeyError
.
If omitted, default_value
is None
, such that
dictionary.get("bogus") # <-- No default specified -- defaults to None
returns None
just like
dictionary.get("bogus", None)
would.
ok I finally found a good solution:
$('iframe').load(function() {
this.style.height =
this.contentWindow.document.body.offsetHeight + 'px';
});
Because some browsers (older Safari and Opera) report onload completed before CSS renders you need to set a micro Timeout and blank out and reassign the iframe's src.
$('iframe').load(function() {
setTimeout(iResize, 50);
// Safari and Opera need a kick-start.
var iSource = document.getElementById('your-iframe-id').src;
document.getElementById('your-iframe-id').src = '';
document.getElementById('your-iframe-id').src = iSource;
});
function iResize() {
document.getElementById('your-iframe-id').style.height =
document.getElementById('your-iframe-id').contentWindow.document.body.offsetHeight + 'px';
}
Try writing all the errors to a file.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
Something like that.
This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.
It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.
Read more in Scott Hanselman's blog post about it and other VS improvements here.
As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:
The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.
To change column data type there are change method and modify method
ALTER TABLE student_info CHANGE roll_no roll_no VARCHAR(255);
ALTER TABLE student_info MODIFY roll_no VARCHAR(255);
To change the field name also use the change method
ALTER TABLE student_info CHANGE roll_no identity_no VARCHAR(255);
Based on the op voted solution, the following should be a bit more efficient:
public static byte [] hexStringToByteArray (final String s) {
if (s == null || (s.length () % 2) == 1)
throw new IllegalArgumentException ();
final char [] chars = s.toCharArray ();
final int len = chars.length;
final byte [] data = new byte [len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit (chars[i], 16) << 4) + Character.digit (chars[i + 1], 16));
}
return data;
}
Because: the initial conversion to a char array spares the length checks in charAt
I too was getting this error. (for which I googled and I was directed to this page)
Problem: I was calling a static method defined in the class of a project A from a class defined in another project B. I was getting the following error:
error: cannot find symbol
Solution: I resolved this by first building the project where the method is defined then the project where the method was being called from.
Can you give a code example where, if the compiler did not have this restriction, something bad would happen?
class Good {
int essential1;
int essential2;
Good(int n) {
if (n > 100)
throw new IllegalArgumentException("n is too large!");
essential1 = 1 / n;
essential2 = n + 2;
}
}
class Bad extends Good {
Bad(int n) {
try {
super(n);
} catch (Exception e) {
// Exception is ignored
}
}
public static void main(String[] args) {
Bad b = new Bad(0);
// b = new Bad(101);
System.out.println(b.essential1 + b.essential2);
}
}
An exception during construction almost always indicates that the object being constructed could not be properly initialized, now is in a bad state, unusable, and must be garbage collected. However, a constructor of a subclass has got the ability to ignore an exception occurred in one of its superclasses and to return a partially initialized object. In the above example, if the argument given to new Bad()
is either 0 or greater than 100, then neither essential1
nor essential2
are properly initialized.
You may say that ignoring exceptions is always a bad idea. OK, here's another example:
class Bad extends Good {
Bad(int n) {
for (int i = 0; i < n; i++)
super(i);
}
}
Funny, isn't it? How many objects are we creating in this example? One? Two? Or maybe nothing...
Allowing to call super()
or this()
in the middle of a constructor would open a Pandora's box of heinous constructors.
On the other hand, I understand a frequent need to include some static part before a call to super()
or this()
. This might be any code not relying on this
reference (which, in fact, already exists at the very beginning of a constructor, but cannot be used orderly until super()
or this()
returns) and needed to make such call. In addition, like in any method, there's a chance that some local variables created before the call to super()
or this()
will be needed after it.
In such cases, you have the following opportunities:
super()
and pre-this()
code. It may be done by imposing a restriction on where super()
or this()
may occur in a constructor. Actually, even today's compiler is able to distinguish good and bad (or potentially bad) cases with the degree enough to securely allow static code addition at the beginning of a constructor. Indeed, assume that super()
and this()
return this
reference and, in turn, your constructor hasreturn this;
at the end. As well as the compiler rejects the code
public int get() {
int x;
for (int i = 0; i < 10; i++)
x = i;
return x;
}
public int get(int y) {
int x;
if (y > 0)
x = y;
return x;
}
public int get(boolean b) {
int x;
try {
x = 1;
} catch (Exception e) {
}
return x;
}
with the error "variable x might not have been initialized", it could do so on this
variable, making its checks on it just like on any other local variable. The only difference is this
cannot be assigned by any means other than super()
or this()
call (and, as usual, if there is no such call at a constructor, super()
is implicitly inserted by compiler in the beginning) and might not be assigned twice. In case of any doubt (like in the first get()
, where x
is actually always assigned), the compiler could return an error. That would be better than simply return error on any constructor where there is something except a comment before super()
or this()
.
It's correct way to get data in specified type:
var dataset = entities.processlists
.Where(x => x.environmentID == environmentid && x.ProcessName == processname && x.RemoteIP == remoteip && x.CommandLine == commandlinepart)
.Select(x => new { x.ServerName, x.ProcessID, x.Username })
.ToList() /// To get data from database
.Select(x => new PInfo()
{
ServerName = x.ServerName,
ProcessID = x.ProcessID,
Username = x.Username
});
For more information see: The entity cannot be constructed in a LINQ to Entities query
Regular expression for number, optional decimal point, optional negative:
^-?(\d*\.)?\d+$;
works for negative integer, decimal, negative with decimal
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
use the above page to refer more Functions in MySQL
SELECT STR_TO_DATE(StringColumn, '%d-%b-%y')
FROM table
say for example use the below query to get output
SELECT STR_TO_DATE('23-feb-14', '%d-%b-%y') FROM table
For String format use the below link
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
For AngularJs you have to use "angular-datatables.min.js" file for datatable settings. You will get this from http://l-lin.github.io/angular-datatables/#/welcome.
After that you can write code like below,
<script>
var app = angular.module('AngularWayApp', ['datatables']);
</script>
<div ng-app="AngularWayApp" ng-controller="AngularWayCtrl">
<table id="example" datatable="ng" class="table">
<thead>
<tr>
<th><b>UserID</b></th>
<th><b>Firstname</b></th>
<th><b>Lastname</b></th>
<th><b>Email</b></th>
<th><b>Actions</b></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" ng-click="testingClick(user)">
<td>
{{user.UserId}}
</td>
<td>
{{user.FirstName}}
</td>
<td>
{{user.Lastname}}
</td>
<td>
{{user.Email}}
</td>
<td>
<span ng-click="editUser(user)" style="color:blue;cursor: pointer; font-weight:500; font-size:15px" class="btnAdd" data-toggle="modal" data-target="#myModal">Edit</span> |
<span ng-click="deleteUser(user)" style="color:red; cursor: pointer; font-weight:500; font-size:15px" class="btnRed">Delete</span>
</td>
</tr>
</tbody>
</table>
</div>
At least in "Docker for Windows" you can see if you are logged in to docker hub over the UI. Just right click the docker icon in the windows notification area:
In WPF there is a control named Popup.
Popup myPopup = new Popup();
//(...)
myPopup.IsOpen = true;
/C
Carries out the command specified by the string and then terminates.
You can get all the cmd command line switches by typing cmd /?
.
Goto File -> Invalidate caches / Restart Shutdown Android Studio Rename/remove .gradle folder in the user home directory Restart Android Studio (It will download gradle metadata and data) Gradle build succeed Rebuild project. Done
Here is super solid solution, you just need have excell.dll in your Debug/Release folder Mine is 77,824 bytes, I downloaded it as a file, this also explain why some people have Debug compiled but Release not or vice versa.
Trento
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
I just ran into a very similar issue. When compiling using Visual Studio 2010, the DLL file was included in the bin
folder. But when compiling using MSBuild the third-party DLL file was not included.
Very frustrating. The way I solved it was to include the NuGet reference to the package in my web project even though I'm not using it directly there.
Try working with this C# snippet I just crafted:
using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string directory = @"C:\downloads";
DirectoryInfo di = new DirectoryInfo(directory);
DirectorySecurity ds = di.GetAccessControl();
foreach (AccessRule rule in ds.GetAccessRules(true, true, typeof(NTAccount)))
{
Console.WriteLine("Identity = {0}; Access = {1}",
rule.IdentityReference.Value, rule.AccessControlType);
}
}
}
}
And here's a reference you could also look at. My code might give you an idea as to how you could check for permissions before attempting to write to a directory.