I agree with squelart. Incrementing two variables is bug prone, especially if you only test for one of them.
This is the readable way to do this:
int j = 0;
for(int i = 0; i < 5; ++i) {
do_something(i, j);
++j;
}
For
loops are meant for cases where your loop runs on one increasing/decreasing variable. For any other variable, change it in the loop.
If you need j
to be tied to i
, why not leave the original variable as is and add i
?
for(int i = 0; i < 5; ++i) {
do_something(i,a+i);
}
If your logic is more complex (for example, you need to actually monitor more than one variable), I'd use a while
loop.
I've always used this syntax, which yields more predictable results than using !=.
<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')" />
I solved it by using git push -u origin master
document.evaluate()
(DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.
every objects in Objective C conform to NSObject protocol, which holds onto the performSelector: method. I was also previously looking for a way to create some "helper or private" methods that I did not need exposed on a public level. If you want to create a private method with no overhead and not having to define it in your header file then give this a shot...
define the your method with a similar signature as the code below...
-(void)myHelperMethod: (id) sender{
// code here...
}
then when you need to reference the method simply call it as a selector...
[self performSelector:@selector(myHelperMethod:)];
this line of code will invoke the method you created and not have an annoying warning about not having it defined in the header file.
You can simply use memcpy
as follows:
unsigned int value = 255;
char bytes[4] = {0, 0, 0, 0};
memcpy(bytes, &value, 4);
As an alternative approach, you can save the SBT Extras script to a file called sbt.sh and set the permission to executable. Then add this file to your path, or just put it under your ~/bin directory.
The bonus here, is that it will download and use the correct version of SBT depending on your project properties. This is a nice convenience if you tend to compile open source projects that you pull from GitHub and other.
Open Notepad and write this
@echo off
:A
Cls
echo MESSENGER
set /p n=User:
set /p m=Message:
net send %n% %m%
Pause
Goto A
and then save as "Messenger.bat
" and close the Notepad
Step 1:
when you open that saved notepad file it will open as a file Messenger command prompt with this details.
Messenger
User:
after "User
" write the ip of the computer you want to contact and then press enter.
It should also be noted that one key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the top level package. It shares a format with npm-shrinkwrap.json(5), which is essentially the same file, but allows publication. This is not recommended unless deploying a CLI tool or otherwise using the publication process for producing production packages.
If both package-lock.json and npm-shrinkwrap.json are present in the root of a package, package-lock.json will be completely ignored.
You can use another overload of the DropDownList
method. Pick the one you need and pass in
a object with your html attributes.
@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
Do you want to return a full row? Does the default row need to have default values or can it be an empty row? Do you want the default row to have the same column structure as the table in question?
Depending on your requirements, you might do something like this:
1) run the query and put results in a temp table (or table variable) 2) check to see if the temp table has results 3) if not, return an empty row by performing a select statement similar to this (in SQL Server):
select '' as columnA, '' as columnB, '' as columnC from #tempTable
Where columnA, columnB and columnC are your actual column names.
I had the same problem when I transferred the ownership of my repository to another user, at first I tried to use git branch --set-upstream-to origin/master master
but the terminal complained so after a little bit of looking around I used the following commands
git fetch
git branch --set-upstream-to origin/master master
git pull
and everything worked again
I'd recommend using the Buffer
class:
var someEncodedString = Buffer.from('someString', 'utf-8');
This avoids any unnecessary dependencies that other answers require, since Buffer
is included with node.js
, and is already defined in the global scope.
Press Ctrl+shift+L
and type your string
Make sure your first line is:
#!/bin/bash
Enter your path to bash if it is not /bin/bash
Try running:
dos2unix script.sh
That wil convert line endings, etc from Windows to unix format. i.e. it strips \r (CR) from line endings to change them from \r\n (CR+LF)
to \n (LF)
.
More details about the dos2unix
command (man page)
Another way to tell if your file is in dos/Win format:
cat scriptname.sh | sed 's/\r/<CR>/'
The output will look something like this:
#!/bin/sh<CR>
<CR>
echo Hello World<CR>
<CR>
This will output the entire file text with <CR>
displayed for each \r
character in the file.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL,Keys.SHIFT,Keys.TAB);
This method helps in switching between multiple windows. The restricting problem with this method is that it can only be used so many times until the required window is reached. Hope it helps.
I had this issue today, and for me the problem was that I had allocated too much memory:
-Xmx1024M -XX:MaxPermSize=1024m
Once I reduced the PermGen space, everything worked fine:
-Xmx1024M -XX:MaxPermSize=512m
I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.
I think this is probably the simplest out of the lot.
SELECT Name FROM Employees group BY Salary DESCENDING limit 2;
When you first instantiate the $objPHPExcel, it already has a single sheet (sheet 0); you're then adding a new sheet (which will become sheet 1), but setting active sheet to sheet $i (when $i is 0)... so you're renaming and populating the original worksheet created when you instantiated $objPHPExcel rather than the one you've just added... this is your title "0".
You're also using the createSheet() method, which both creates a new worksheet and adds it to the workbook... but you're also adding it again yourself which is effectively adding the sheet in two position.
So first iteration, you already have sheet0, add a new sheet at both indexes 1 and 2, and edit/title sheet 0. Second iteration, you add a new sheet at both indexes 3 and 4, and edit/title sheet 1, but because you have the same sheet at indexes 1 and 2 this effectively writes to the sheet at index 2. Third iteration, you add a new sheet at indexes 5 and 6, and edit/title sheet 2, overwriting your earlier editing/titleing of sheet 1 which acted against sheet 2 instead.... and so on
Math.round(number*100.0)/100.0;
MyButton.setGravity(Gravity.RIGHT);
For layout_gravity use the answer stated by "karthi". This method sets gravity to place the children inside the view.
content
doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is "
inside a "
block. You should mix '
and "
(class='headingDetail'
).
If content
did support HTML you could end up in an infinite loop where content
is added inside content
.
map.setZoom(zoom:number)
https://developers.google.com/maps/documentation/javascript/reference#Map
I like visual answers.
When you click #btn
, two event handlers get called and they output what you see in the picture.
Demo here: https://jsfiddle.net/ujhe1key/
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class ImageButton extends Button {
public void updateImages(final Image selected, final Image unselected) {
final ImageView iv = new ImageView(selected);
this.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(unselected);
}
});
iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(selected);
}
});
super.setGraphic(iv);
}
}
Another simple solution is to define your onClickListener, in the getView(..) method, of your ListAdapter.
public View getView(final int position, View convertView, ViewGroup parent){
//initialise your view
...
View row = context.getLayoutInflater().inflate(R.layout.list_item, null);
...
//define your listener on inner items
//define your global listener
row.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
doSomethingWithViewAndPosition(v,position);
}
});
return row;
That way your row are clickable, and your inner view too :)
Using select2 jquery library:
$('#selector').val(arrayOfValues).trigger('change')
You organized class interface such that public members begin with "my". Therefore you must use only those members. Instead of
myScoreonHole.hole = Console.ReadLine();
you should write
myScoreonHole.myhole = Console.ReadLine();
If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:
sys.path.insert(1, path_to_dev_pyworkbooks)
This could be important since 3rd party code may rely on sys.path documentation conformance:
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.
I know its a little bit late but someone may find this useful in future.
STEP 1:
Login to facebook Developer -> Your App
In Settings -> Basic -> Contact Email. (Give any email)
STEP 2:
And in 'App Review' Tab : change
Do you want to make this app and all its live features available to the general public? Yes
And you app will be live now ..
If you have Matlab, you can open large CSV (or TXT) files via its import facility. The tool gives you various import format options including tables, column vectors, numeric matrix, etc. However, with Matlab being an interpreter package, it does take its own time to import such a large file and I was able to import one with more than 2 million rows in about 10 minutes.
The tool is accessible via Matlab's Home tab by clicking on the "Import Data" button. An example image of a large file upload is shown below: Once imported, the data appears on the right-hand-side Workspace, which can then be double-clicked in an Excel-like format and even be plotted in different formats.
I was facing the same problem and non of the above solutions helped me. In my Web Api 2
project, I had actually updated my database and had placed a unique constraint
on an SQL table column.
That was actually causing the problem. Simply Checking the the duplicate column values before inserting helped me fix the problem!
I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.
You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.
What I identified in your first case is the following:
Let's see how we do that, we can do it with the following:
List<Player> playersOfTeam = players.stream()
.filter(player -> player.getTeam().equals(teamName))
.collect(Collectors.toList());
What you do here is:
Collection<Player>
, now you have a Stream<Player>
.Predicate<Player>
, mapping every player to the boolean true if it is wished to be kept.Collector
, here we can use one of the standard library collectors, which is Collectors.toList()
.This also incorporates two other points:
List<E>
over ArrayList<E>
.new ArrayList<>()
, you are using Java 8 after all.Now onto your second point:
You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)...
over what he suggested.
Download the latest gradle-3.0-all.zip from
http://gradle.org/gradle-download/
download from Complete Distribution link
open in android studio file ->settings ->gradle
open the path and paste the downloaded zip folder gradle-3.0 in that folder
change your gradle 2.8 to gradle 3.0 in file ->settings ->gradle
Or you can change your gradle wrapper in the project
edit YourProject\gradle\wrapper\gradle-wrapper.properties file and edit the field distributionUrl in to
distributionUrl= https://services.gradle.org/distributions/gradle-3.0-all.zip
Just like any other collection. With the addition of the List<T>.ForEach
method.
foreach (var item in myMoney)
Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type);
for (int i = 0; i < myMoney.Count; i++)
Console.WriteLine("amount is {0}, and type is {1}", myMoney[i].amount, myMoney[i].type);
myMoney.ForEach(item => Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type));
To write an equivalent method using iteration, we must explicitly use a stack. The fact that the iterative version requires a stack for its solution indicates that the problem is difficult enough that it can benefit from recursion. As a general rule, recursion is most suitable for problems that cannot be solved with a fixed amount of memory and consequently require a stack when solved iteratively. Having said that, recursion and iteration can show the same outcome while they follow different pattern.To decide which method works better is case by case and best practice is to choose based on the pattern that problem follows.
For example, to find the nth triangular number of Triangular sequence: 1 3 6 10 15 … A program that uses an iterative algorithm to find the n th triangular number:
Using an iterative algorithm:
//Triangular.java
import java.util.*;
class Triangular {
public static int iterativeTriangular(int n) {
int sum = 0;
for (int i = 1; i <= n; i ++)
sum += i;
return sum;
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = stdin.nextInt();
System.out.println("The " + n + "-th triangular number is: " +
iterativeTriangular(n));
}
}//enter code here
Using a recursive algorithm:
//Triangular.java
import java.util.*;
class Triangular {
public static int recursiveTriangular(int n) {
if (n == 1)
return 1;
return recursiveTriangular(n-1) + n;
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = stdin.nextInt();
System.out.println("The " + n + "-th triangular number is: " +
recursiveTriangular(n));
}
}
A constructor should no have a return type . remove void before each constructor .
Some very basic characteristic of a constructor :
a. Same name as class b. no return type. c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow, Flow flow1=new Flow(); Flow flow2=new Flow(); then Flow constructor will be called for 2 times.
d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor ..
some guys who still might have the problem like me (FOR IRANIAN and all the coutries who have sanctions) , this is error can be fixed with proxy
i used this free proxy for android studio 3.2
https://github.com/freedomofdevelopers/fod
just to to Settings (Ctrl + Alt + S)
and search HTTP proxy
then check Manual proxy configuration
then add fodev.org
for host name
and 8118
for Port number
My answer directly inspired from @valex very usefull, if you need several cols in the ORDER BY clause.
SELECT u.*
FROM users AS u
INNER JOIN (
SELECT p.*,
@num := if(@id = user_id, @num + 1, 1) as row_number,
@id := user_id as tmp
FROM (SELECT * FROM payments ORDER BY p.user_id ASC, date DESC) AS p,
(SELECT @num := 0) x,
(SELECT @id := 0) y
)
ON (p.user_id = u.id) and (p.row_number=1)
WHERE u.package = 1
I've never had a good memory for exact wording, but in my database class I think the professor always said something like:
The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF].
Example for SignalR 2.2.1 (May 2017)
Server
Install-Package Microsoft.AspNet.SignalR.SelfHost -Version 2.2.1
[assembly: OwinStartup(typeof(Program.Startup))]
namespace ConsoleApplication116_SignalRServer
{
class Program
{
static IDisposable SignalR;
static void Main(string[] args)
{
string url = "http://127.0.0.1:8088";
SignalR = WebApp.Start(url);
Console.ReadKey();
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
/* CAMEL CASE & JSON DATE FORMATTING
use SignalRContractResolver from
https://stackoverflow.com/questions/30005575/signalr-use-camel-case
var settings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
settings.ContractResolver = new SignalRContractResolver();
var serializer = JsonSerializer.Create(settings);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
*/
app.MapSignalR();
}
}
[HubName("MyHub")]
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
}
Client
(almost the same as Mehrdad Bahrainy reply)
Install-Package Microsoft.AspNet.SignalR.Client -Version 2.2.1
namespace ConsoleApplication116_SignalRClient
{
class Program
{
private static void Main(string[] args)
{
var connection = new HubConnection("http://127.0.0.1:8088/");
var myHub = connection.CreateHubProxy("MyHub");
Console.WriteLine("Enter your name");
string name = Console.ReadLine();
connection.Start().ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
myHub.On<string, string>("addMessage", (s1, s2) => {
Console.WriteLine(s1 + ": " + s2);
});
while (true)
{
Console.WriteLine("Please Enter Message");
string message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
{
break;
}
myHub.Invoke<string>("Send", name, message).ContinueWith(task1 => {
if (task1.IsFaulted)
{
Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
}
else
{
Console.WriteLine(task1.Result);
}
});
}
}
}).Wait();
Console.Read();
connection.Stop();
}
}
}
Format the redirect URL in the following way:
stuff.mysite.org.uk$S$Q
The $S
will say that any path must be applied to the new URL.
$Q
says that any parameter variables must be passed to the new URL.
In IIS 7.0, you must enable the option Redirect to exact destination
.
I believe there must be an option like this in IIS 6.0 too.
$_GET
is not a function or language construct—it's just a variable (an array). Try:
<?php
echo $_GET['link'];
In particular, it's a superglobal: a built-in variable that's populated by PHP and is available in all scopes (you can use it from inside a function without the global keyword).
Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:
<?php
if (isset($_GET['link'])) {
echo $_GET['link'];
} else {
// Fallback behaviour goes here
}
Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:
<?php
echo filter_input(INPUT_GET, 'link', FILTER_SANITIZE_URL);
Last but not least, you can use the null coalescing operator (available since PHP/7.0) to handle missing parameters:
echo $_GET['link'] ?? 'Fallback value';
Like the comments suggest, the solution is to use nested spans/rows.
<div class="container">
<div class="row">
<div class="span4">1</div>
<div class="span8">
<div class="row">
<div class="span4">2</div>
<div class="span4">3</div>
</div>
<div class="row">
<div class="span4">4</div>
<div class="span4">5</div>
</div>
</div>
</div>
<div class="row">
<div class="span4">6</div>
<div class="span4">7</div>
<div class="span4">8</div>
</div>
</div>
As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:
<p>Hello</p>
<p><?= _("World"); ?></p>
It depends on how accurate you need it to be, if you need pinpoint accuracy, is best to look at an algorithm with uses an ellipsoid, rather than a sphere, such as Vincenty's algorithm, which is accurate to the mm. http://en.wikipedia.org/wiki/Vincenty%27s_algorithm
There is a numpy built-in function to help with that.
import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])
One simple query will do it:
SELECT *
FROM table
GROUP BY email
HAVING COUNT(*) = 1;
This is not a direct answer to the question. Rather it answers this question: "How do I choose a specific function output from many possible options?".
If you are able to write the function (ie, it is not in a library you cannot modify), then add an input argument that indicates what you want out of the function. Make it a named argument with a default value so in the "common case" you don't even have to specify it.
def fancy_function( arg1, arg2, return_type=1 ):
ret_val = None
if( 1 == return_type ):
ret_val = arg1 + arg2
elif( 2 == return_type ):
ret_val = [ arg1, arg2, arg1 * arg2 ]
else:
ret_val = ( arg1, arg2, arg1 + arg2, arg1 * arg2 )
return( ret_val )
This method gives the function "advanced warning" regarding the desired output. Consequently it can skip unneeded processing and only do the work necessary to get your desired output. Also because Python does dynamic typing, the return type can change. Notice how the example returns a scalar, a list or a tuple... whatever you like!
The difference can be summarized into this snippet:
alert(typeof(null)); // object
alert(typeof(undefined)); // undefined
alert(null !== undefined) //true
alert(null == undefined) //true
Checking
object == null
is different to check if ( !object )
.
The latter is equal to ! Boolean(object)
, because the unary !
operator automatically cast the right operand into a Boolean.
Since Boolean(null)
equals false then !false === true
.
So if your object is not null, but false or 0 or "", the check will pass because:
alert(Boolean(null)) //false
alert(Boolean(0)) //false
alert(Boolean("")) //false
I don't know why chrome team don't allow this silly feature ... but the only way I could change variable values with success is to modify the script directly in the chrome editor under "Sources" Tab (this changes the behavior of your script until you refresh the page), but that changes will lost when refresh, so be carefull.
Although the best way to do this is to use % if you insist on using strings this will work
public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}
but I just wrote this for completeness. Do not use this code. it is just awful.
Here is a simple way to do it, without any module. It's similar to this answer, but has the benefit to also work if it's a big file that doesn't fit in RAM:
with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g:
while True:
block = f.read(16*1024*1024) # work by blocks of 16 MB
if not block: # end of file
break
g.write(block)
Since we're writing a new file, it does not preserve the modification time, etc.
We can then use os.utime
for this if needed.
I like to start with a class like this class settings { public int X {get;set;} public string Y { get; set; } // repeat as necessary
public settings()
{
this.X = defaultForX;
this.Y = defaultForY;
// repeat ...
}
public void Parse(Uri uri)
{
// parse values from query string.
// if you need to distinguish from default vs. specified, add an appropriate property
}
This has worked well on 100's of projects. You can use one of the many other parsing solutions to parse values.
For chart.js 2.0+, this has changed (no more tooltipTemplate/multiTooltipTemplate). For those that just want to access the current, unformatted value and start tweaking it, the default tooltip is the same as:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return tooltipItem.yLabel;
}
}
}
}
I.e., you can return modifications to tooltipItem.yLabel
, which holds the y-axis value. In my case, I wanted to add a dollar sign, rounding, and thousands commas for a financial chart, so I used:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return "$" + Number(tooltipItem.yLabel).toFixed(0).replace(/./g, function(c, i, a) {
return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
});
}
}
}
}
you need to add in web.config
<endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="WcfRest.IService1"/>
<bindings>
<customBinding>
<binding name="basicConfig">
<binaryMessageEncoding/>
<httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864"/>
</binding>
</customBinding>
You override __hash__
if you want special hash-semantics, and __cmp__
or __eq__
in order to make your class usable as a key. Objects who compare equal need to have the same hash value.
Python expects __hash__
to return an integer, returning Banana()
is not recommended :)
User defined classes have __hash__
by default that calls id(self)
, as you noted.
There is some extra tips from the documentation.:
Classes which inherit a
__hash__()
method from a parent class but change the meaning of__cmp__()
or__eq__()
such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting__hash__ = None
in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checkingisinstance(obj, collections.Hashable)
(unlike classes which define their own__hash__()
to explicitly raise TypeError).
vi can show all characters.
JXcore will allow you to turn any nodejs application into a single executable, including all dependencies, in either Windows, Linux, or Mac OS X.
Here is a link to the installer: https://github.com/jxcore/jxcore-release
And here is a link to how to set it up: http://jxcore.com/turn-node-applications-into-executables/
It is very easy to use and I have tested it in both Windows 8.1 and Ubuntu 14.04.
FYI: JXcore is a fork of NodeJS so it is 100% NodeJS compatible, with some extra features.
You have to use DENSE_RANK rather than RANK. The only difference is that it doesn't leave gaps. You also shouldn't partition by contender_num, otherwise you're ranking each contender in a separate group, so each is 1st-ranked in their segregated groups!
SELECT contendernum,totals, DENSE_RANK() OVER (ORDER BY totals desc) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
GROUP BY ContenderNum
) AS a
order by contendernum
A hint for using StackOverflow, please post DDL and sample data so people can help you using less of their own time!
create table Cat1GroupImpersonation (
contendernum int,
criteria1 int,
criteria2 int,
criteria3 int,
criteria4 int);
insert Cat1GroupImpersonation select
1,196,0,0,0 union all select
2,181,0,0,0 union all select
3,192,0,0,0 union all select
4,181,0,0,0 union all select
5,179,0,0,0;
In my experience, I always just use an external program to generate the graph (mathematica, gnuplot, matlab, etc.) and export the graph as a pdf or eps file. Then I include it into the document with includegraphics
.
I found the best way to send input is to use cat and a text file to pass along whatever input you need.
cat "input.txt" | ./Script.sh
I think you are looking for instance_of?
. is_a?
and kind_of?
will return true for instances from derived classes.
class X < String
end
foo = X.new
foo.is_a? String # true
foo.kind_of? String # true
foo.instance_of? String # false
foo.instance_of? X # true
For someone not using the signing configs and trying to test out the Cordova Release command by typing all the parameters at command line, you may need to enclose your passwords with single quotes if you have special characters in your password
cordova run android --release -- --keystore=../my-release-key.keystore --storePassword='password' --alias=alias_name --password='password'
You could try using this tool which automatically removes the Team Foundation Bindings from a project. http://www.softpedia.com/get/Programming/Other-Programming-Files/Team-Foundation-Binding-Remover.shtml
Redefine the CI_Loader::view function by adding a file named as 'MY_Loader.php' in your application/core folder and adding the following content
/**
* /application/core/MY_Loader.php
*/
class MY_Loader extends CI_Loader
{
public function view($view, $vars = array(), $return = FALSE, $include_template=TRUE)
{
$header='';
$footer='';
if($include_template)
{
$header=parent::view('templates/header',$vars,$return);
}
$content=parent::view($view, $vars,$return);
if($include_template)
{
$footer=parent::view('templates/footer',$vars,$return);
}
if($return)
return "$header$content$footer";
return $this;
}
}
I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util
instead of implementing my own class.
So if the previous answers did not help you, please check that you import
the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.
For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :
import java.util.*; // replace this line
import myCollections.Queue; // by this line
Queue<Edge> theQueue = new Queue<Edge>();
I saw a question the other day where someone inadvertently used an incomplete type by specifying something like
struct a {
int q;
};
struct A *x;
x->q = 3;
The compiler knew that struct A
was a struct, despite A
being totally undefined, by virtue of the struct
keyword.
That was in C++, where such usage of struct
is atypical (and, it turns out, can lead to foot-shooting). In C if you do
typedef struct a {
...
} a;
then you can use a
as the typename and omit the struct
later. This will lead the compiler to give you an undefined identifier error later, rather than incomplete type, if you mistype the name or forget a header.
In cross-platform, lowest-common-denominator sh
you use:
#!/bin/sh
value=`cat config.txt`
echo "$value"
In bash
or zsh
, to read a whole file into a variable without invoking cat
:
#!/bin/bash
value=$(<config.txt)
echo "$value"
Invoking cat
in bash
or zsh
to slurp a file would be considered a Useless Use of Cat.
Note that it is not necessary to quote the command substitution to preserve newlines.
See: Bash Hacker's Wiki - Command substitution - Specialities.
Sure. Add an Axes
using add_subplot
. (Edited import
.) (Edited show
.)
import matplotlib.pyplot as plt
f1 = plt.figure()
f2 = plt.figure()
ax1 = f1.add_subplot(111)
ax1.plot(range(0,10))
ax2 = f2.add_subplot(111)
ax2.plot(range(10,20))
plt.show()
Alternatively, use add_axes
.
ax1 = f1.add_axes([0.1,0.1,0.8,0.8])
ax1.plot(range(0,10))
ax2 = f2.add_axes([0.1,0.1,0.8,0.8])
ax2.plot(range(10,20))
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);
To keep the previous typeface
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)
Just declare it outside the functions, and assign values inside the functions. Something like:
<script type="text/javascript">
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage = null ; // Global variable
function makeObj(address) {
trailimage = [address, 50, 50]; // Assign value
Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
function makeObj(address) {
trailimage = [address, 50, 50]; // Global variable, assign value
I hope this example explains more: http://jsfiddle.net/qCrGE/
var globalOne = 3;
testOne();
function testOne()
{
globalOne += 2;
alert("globalOne is :" + globalOne );
globalOne += 1;
}
alert("outside globalOne is: " + globalOne);
testTwo();
function testTwo()
{
globalTwo = 20;
alert("globalTwo is " + globalTwo);
globalTwo += 5;
}
alert("outside globalTwo is:" + globalTwo);
I had the same problem, tnsnames.ora
worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.
It turns out that the database was caching backup copies of tnsnames.ora
like tnsnames.ora.bk2
, tnsnames09042811AM4501.bak
, tnsnames.ora.bk
etc. These files were not readable by the average user.
I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.
The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.
As BalusC indicated, the actionListener
by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.
This happens through a call like this:
context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,
new ExceptionQueuedEventContext(context, exception, source, phaseId)
);
The default listener for this event is the ExceptionHandler
which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl
. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.
This ExceptionHandler
can be replaced however in faces-config.xml with a custom implementation:
<exception-handlerfactory>
com.foo.myExceptionHandler
</exception-handlerfactory>
Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:
@ManagedBean
@RequestScoped
public class MyBean {
public void actionMethod(ActionEvent event) {
FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
throw new RuntimeException(content.getException());
}
@Override
public boolean isListenerForSource(Object source) {
return true;
}
});
throw new RuntimeException("test");
}
}
(note, this is not how one should normally code listeners, this is only for demonstration purposes!)
Calling this from a Facelet like this:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<h:form>
<h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
</h:form>
</h:body>
</html>
Will result in an error page being displayed.
Check out the "--only-keep-debug" option of the strip command.
From the link:
The intention is that this option will be used in conjunction with --add-gnu-debuglink to create a two part executable. One a stripped binary which will occupy less space in RAM and in a distribution and the second a debugging information file which is only needed if debugging abilities are required.
I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).
Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
On Macs, (assuming you have the right version installed)
JAVA_HOME=`/usr/libexec/java_home -v 1.8` mvn clean install -DskipTests
Using sshpass works best. To just include your password in scp use the ' ':
scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:
grid-auto-rows: 1fr
Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr
unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow
property in flexbox.
If you set all rows in a grid container to 1fr
, let's say like this:
grid-auto-rows: 1fr;
... then all rows will be equal height.
It doesn't really make sense off-the-bat because fr
is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.
Except, buried deep in the grid spec is this little nugget:
7.2.3. Flexible Lengths: the
fr
unit...
When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (
fr
) grid tracks are sized to their contents while retaining their respective proportions.The used size of each flex-sized grid track is computed by determining the
max-content
size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical1fr
size”.The maximum of those is used as the resolved
1fr
length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.
So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.
The height of each row is determined by the tallest (max-content
) grid item.
The maximum height of those rows becomes the length of 1fr
.
That's how 1fr
creates equal height rows in a grid container.
As noted in the question, equal height rows are not possible with flexbox.
Flex items can be equal height on the same row, but not across multiple rows.
This behavior is defined in the flexbox spec:
In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.
In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.
Suppose you want to add those flags (better to declare them in a constant):
SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS "-lgcov")
There are several ways to add them:
The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):
add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
Appending to corresponding CMake variables:
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
Using target properties, cf. doc CMake compile flag target property and need to know the target name.
get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
if(TEMP STREQUAL "TEMP-NOTFOUND")
SET(TEMP "") # Set to empty string
else()
SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
endif()
# Append our values
SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
Right now I use method 2.
You need to pass a function to setTimeout
$(window).load(function () {
window.setTimeout(function () {
window.location.href = "https://www.google.co.in";
}, 5000)
});
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
You could try this:
{% if not profile.user.first_name.value %}
<p> -- </p>
{% else %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}
This way, you're essentially checking to see if the form field first_name
has any value associated with it. See {{ field.value }}
in Looping over the form's fields in Django Documentation.
I'm using Django 3.0.
AJAX is a technique to do an XMLHttpRequest (out of band Http request) from a web page to the server and send/retrieve data to be used on the web page. AJAX stands for Asynchronous Javascript And XML. It uses javascript to construct an XMLHttpRequest, typically using different techniques on various browsers.
jQuery (website) is a javascript framework that makes working with the DOM easier by building lots of high level functionality that can be used to search and interact with the DOM. Part of the functionality of jQuery implements a high-level interface to do AJAX requests. jQuery implements this interface abstractly, shielding the developer from the complexity of multi-browser support in making the request.
or without linq
foreach(MyObject obj in myList)
{
if(obj.prop == someValue)
{
obj.otherProp = newValue;
break;
}
}
AngularJS and jQuery adopt very different ideologies. If you're coming from jQuery you may find some of the differences surprising. Angular may make you angry.
This is normal, you should push through. Angular is worth it.
jQuery gives you a toolkit for selecting arbitrary bits of the DOM and making ad-hoc changes to them. You can do pretty much anything you like piece by piece.
AngularJS instead gives you a compiler.
What this means is that AngularJS reads your entire DOM from top to bottom and treats it as code, literally as instructions to the compiler. As it traverses the DOM, It looks for specific directives (compiler directives) that tell the AngularJS compiler how to behave and what to do. Directives are little objects full of JavaScript which can match against attributes, tags, classes or even comments.
When the Angular compiler determines that a piece of the DOM matches a particular directive, it calls the directive function, passing it the DOM element, any attributes, the current $scope (which is a local variable store), and some other useful bits. These attributes may contain expressions which can be interpreted by the Directive, and which tell it how to render, and when it should redraw itself.
Directives can then in turn pull in additional Angular components such as controllers, services, etc. What comes out the bottom of the compiler is a fully formed web application, wired up and ready to go.
This means that Angular is Template Driven. Your template drives the JavaScript, not the other way around. This is a radical reversal of roles, and the complete opposite of the unobtrusive JavaScript we have been writing for the last 10 years or so. This can take some getting used to.
If this sounds like it might be over-prescriptive and limiting, nothing could be farther from the truth. Because AngularJS treats your HTML as code, you get HTML level granularity in your web application. Everything is possible, and most things are surprisingly easy once you make a few conceptual leaps.
Let's get down to the nitty gritty.
Angular and jQuery do different things. AngularJS gives you a set of tools to produce web applications. jQuery mainly gives you tools for modifying the DOM. If jQuery is present on your page, AngularJS will use it automatically. If it isn't, AngularJS ships with jQuery Lite, which is a cut down, but still perfectly usable version of jQuery.
Misko likes jQuery and doesn't object to you using it. However you will find as you advance that you can get a pretty much all of your work done using a combination of scope, templates and directives, and you should prefer this workflow where possible because your code will be more discrete, more configurable, and more Angular.
If you do use jQuery, you shouldn't be sprinkling it all over the place. The correct place for DOM manipulation in AngularJS is in a directive. More on these later.
jQuery is typically applied unobtrusively. Your JavaScript code is linked in the header (or the footer), and this is the only place it is mentioned. We use selectors to pick out bits of the page and write plugins to modify those parts.
The JavaScript is in control. The HTML has a completely independent existence. Your HTML remains semantic even without JavaScript. Onclick attributes are very bad practice.
One of the first things your will notice about AngularJS is that custom attributes are everywhere. Your HTML will be littered with ng attributes, which are essentially onClick attributes on steroids. These are directives (compiler directives), and are one of the main ways in which the template is hooked to the model.
When you first see this you might be tempted to write AngularJS off as old school intrusive JavaScript (like I did at first). In fact, AngularJS does not play by those rules. In AngularJS, your HTML5 is a template. It is compiled by AngularJS to produce your web page.
This is the first big difference. To jQuery, your web page is a DOM to be manipulated. To AngularJS, your HTML is code to be compiled. AngularJS reads in your whole web page and literally compiles it into a new web page using its built in compiler.
Your template should be declarative; its meaning should be clear simply by reading it. We use custom attributes with meaningful names. We make up new HTML elements, again with meaningful names. A designer with minimal HTML knowledge and no coding skill can read your AngularJS template and understand what it is doing. He or she can make modifications. This is the Angular way.
One of the first questions I asked myself when starting AngularJS and running through the tutorials is "Where is my code?". I've written no JavaScript, and yet I have all this behaviour. The answer is obvious. Because AngularJS compiles the DOM, AngularJS is treating your HTML as code. For many simple cases it's often sufficient to just write a template and let AngularJS compile it into an application for you.
Your template drives your application. It's treated as a DSL. You write AngularJS components, and AngularJS will take care of pulling them in and making them available at the right time based on the structure of your template. This is very different to a standard MVC pattern, where the template is just for output.
It's more similar to XSLT than Ruby on Rails for example.
This is a radical inversion of control that takes some getting used to.
Stop trying to drive your application from your JavaScript. Let the template drive the application, and let AngularJS take care of wiring the components together. This also is the Angular way.
With jQuery your HTML page should contain semantic meaningful content. If the JavaScript is turned off (by a user or search engine) your content remains accessible.
Because AngularJS treats your HTML page as a template. The template is not supposed to be semantic as your content is typically stored in your model which ultimately comes from your API. AngularJS compiles your DOM with the model to produce a semantic web page.
Your HTML source is no longer semantic, instead, your API and compiled DOM are semantic.
In AngularJS, meaning lives in the model, the HTML is just a template, for display only.
At this point you likely have all sorts of questions concerning SEO and accessibility, and rightly so. There are open issues here. Most screen readers will now parse JavaScript. Search engines can also index AJAXed content. Nevertheless, you will want to make sure you are using pushstate URLs and you have a decent sitemap. See here for a discussion of the issue: https://stackoverflow.com/a/23245379/687677
Separation of concerns (SOC) is a pattern that grew up over many years of web development for a variety of reasons including SEO, accessibility and browser incompatibility. It looks like this:
Again, AngularJS does not play by their rules. In a stroke, AngularJS does away with a decade of received wisdom and instead implements an MVC pattern in which the template is no longer semantic, not even a little bit.
It looks like this:
MVC and SOC are not on opposite ends of the same scale, they are on completely different axes. SOC makes no sense in an AngularJS context. You have to forget it and move on.
If, like me, you lived through the browser wars, you might find this idea quite offensive. Get over it, it'll be worth it, I promise.
Plugins extend jQuery. AngularJS Directives extend the capabilities of your browser.
In jQuery we define plugins by adding functions to the jQuery.prototype. We then hook these into the DOM by selecting elements and calling the plugin on the result. The idea is to extend the capabilities of jQuery.
For example, if you want a carousel on your page, you might define an unordered list of figures, perhaps wrapped in a nav element. You might then write some jQuery to select the list on the page and restyle it as a gallery with timeouts to do the sliding animation.
In AngularJS, we define directives. A directive is a function which returns a JSON object. This object tells AngularJS what DOM elements to look for, and what changes to make to them. Directives are hooked in to the template using either attributes or elements, which you invent. The idea is to extend the capabilities of HTML with new attributes and elements.
The AngularJS way is to extend the capabilities of native looking HTML. You should write HTML that looks like HTML, extended with custom attributes and elements.
If you want a carousel, just use a <carousel />
element, then define a directive to pull in a template, and make that sucker work.
The tendency with jQuery is to write great big plugins like lightbox which we then configure by passing in numerous values and options.
This is a mistake in AngularJS.
Take the example of a dropdown. When writing a dropdown plugin you might be tempted to code in click handlers, perhaps a function to add in a chevron which is either up or down, perhaps change the class of the unfolded element, show hide the menu, all helpful stuff.
Until you want to make a small change.
Say you have a menu that you want to unfold on hover. Well now we have a problem. Our plugin has wired in our click handler for us, we're going to need to add a configuration option to make it behave differently in this specific case.
In AngularJS we write smaller directives. Our dropdown directive would be ridiculously small. It might maintain the folded state, and provide methods to fold(), unfold() or toggle(). These methods would simply update $scope.menu.visible which is a boolean holding the state.
Now in our template we can wire this up:
<a ng-click="toggle()">Menu</a>
<ul ng-show="menu.visible">
...
</ul>
Need to update on mouseover?
<a ng-mouseenter="unfold()" ng-mouseleave="fold()">Menu</a>
<ul ng-show="menu.visible">
...
</ul>
The template drives the application so we get HTML level granularity. If we want to make case by case exceptions, the template makes this easy.
JQuery plugins are created in a closure. Privacy is maintained within that closure. It's up to you to maintain your scope chain within that closure. You only really have access to the set of DOM nodes passed in to the plugin by jQuery, plus any local variables defined in the closure and any globals you have defined. This means that plugins are quite self contained. This is a good thing, but can get restrictive when creating a whole application. Trying to pass data between sections of a dynamic page becomes a chore.
AngularJS has $scope objects. These are special objects created and maintained by AngularJS in which you store your model. Certain directives will spawn a new $scope, which by default inherits from its wrapping $scope using JavaScript prototypical inheritance. The $scope object is accessible in the controller and the view.
This is the clever part. Because the structure of $scope inheritance roughly follows the structure of the DOM, elements have access to their own scope, and any containing scopes seamlessly, all the way up to the global $scope (which is not the same as the global scope).
This makes it much easier to pass data around, and to store data at an appropriate level. If a dropdown is unfolded, only the dropdown $scope needs to know about it. If the user updates their preferences, you might want to update the global $scope, and any nested scopes listening to the user preferences would automatically be alerted.
This might sound complicated, in fact, once you relax into it, it's like flying. You don't need to create the $scope object, AngularJS instantiates and configures it for you, correctly and appropriately based on your template hierarchy. AngularJS then makes it available to your component using the magic of dependency injection (more on this later).
In jQuery you make all your DOM changes by hand. You construct new DOM elements programatically. If you have a JSON array and you want to put it to the DOM, you must write a function to generate the HTML and insert it.
In AngularJS you can do this too, but you are encouraged to make use of data binding. Change your model, and because the DOM is bound to it via a template your DOM will automatically update, no intervention required.
Because data binding is done from the template, using either an attribute or the curly brace syntax, it's super easy to do. There's little cognitive overhead associated with it so you'll find yourself doing it all the time.
<input ng-model="user.name" />
Binds the input element to $scope.user.name
. Updating the input will update the value in your current scope, and vice-versa.
Likewise:
<p>
{{user.name}}
</p>
will output the user name in a paragraph. It's a live binding, so if the $scope.user.name
value is updated, the template will update too.
In jQuery making an Ajax call is fairly simple, but it's still something you might think twice about. There's the added complexity to think about, and a fair chunk of script to maintain.
In AngularJS, Ajax is your default go-to solution and it happens all the time, almost without you noticing. You can include templates with ng-include. You can apply a template with the simplest custom directive. You can wrap an Ajax call in a service and create yourself a GitHub service, or a Flickr service, which you can access with astonishing ease.
In jQuery, if we want to accomplish a small non-dom related task such as pulling a feed from an API, we might write a little function to do that in our closure. That's a valid solution, but what if we want to access that feed often? What if we want to reuse that code in another application?
AngularJS gives us service objects.
Services are simple objects that contain functions and data. They are always singletons, meaning there can never be more than one of them. Say we want to access the Stack Overflow API, we might write a StackOverflowService
which defines methods for doing so.
Let's say we have a shopping cart. We might define a ShoppingCartService which maintains our cart and contains methods for adding and removing items. Because the service is a singleton, and is shared by all other components, any object that needs to can write to the shopping cart and pull data from it. It's always the same cart.
Service objects are self-contained AngularJS components which we can use and reuse as we see fit. They are simple JSON objects containing functions and Data. They are always singletons, so if you store data on a service in one place, you can get that data out somewhere else just by requesting the same service.
AngularJS manages your dependencies for you. If you want an object, simply refer to it and AngularJS will get it for you.
Until you start to use this, it's hard to explain just what a massive time boon this is. Nothing like AngularJS DI exists inside jQuery.
DI means that instead of writing your application and wiring it together, you instead define a library of components, each identified by a string.
Say I have a component called 'FlickrService' which defines methods for pulling JSON feeds from Flickr. Now, if I want to write a controller that can access Flickr, I just need to refer to the 'FlickrService' by name when I declare the controller. AngularJS will take care of instantiating the component and making it available to my controller.
For example, here I define a service:
myApp.service('FlickrService', function() {
return {
getFeed: function() { // do something here }
}
});
Now when I want to use that service I just refer to it by name like this:
myApp.controller('myController', ['FlickrService', function(FlickrService) {
FlickrService.getFeed()
}]);
AngularJS will recognise that a FlickrService object is needed to instantiate the controller, and will provide one for us.
This makes wiring things together very easy, and pretty much eliminates any tendency towards spagettification. We have a flat list of components, and AngularJS hands them to us one by one as and when we need them.
jQuery says very little about how you should organise your code. AngularJS has opinions.
AngularJS gives you modules into which you can place your code. If you're writing a script that talks to Flickr for example, you might want to create a Flickr module to wrap all your Flickr related functions in. Modules can include other modules (DI). Your main application is usually a module, and this should include all the other modules your application will depend on.
You get simple code reuse, if you want to write another application based on Flickr, you can just include the Flickr module and voila, you have access to all your Flickr related functions in your new application.
Modules contain AngularJS components. When we include a module, all the components in that module become available to us as a simple list identified by their unique strings. We can then inject those components into each other using AngularJS's dependency injection mechanism.
AngularJS and jQuery are not enemies. It's possible to use jQuery within AngularJS very nicely. If you're using AngularJS well (templates, data-binding, $scope, directives, etc.) you will find you need a lot less jQuery than you might otherwise require.
The main thing to realise is that your template drives your application. Stop trying to write big plugins that do everything. Instead write little directives that do one thing, then write a simple template to wire them together.
Think less about unobtrusive JavaScript, and instead think in terms of HTML extensions.
I got so excited about AngularJS, I wrote a short book on it which you're very welcome to read online http://nicholasjohnson.com/angular-book/. I hope it's helpful.
SELECT colA, colB FROM tableA WHERE colA > 1
UNION
SELECT colX, colA FROM tableB
x86 is a 32 bit instruction set, x86_64 is a 64 bit instruction set... the difference is simple architecture. in case of windows os you better use the x86/32bit version for compatibility issues. in case of Linux you will not be able to use a 64 bit s/w if the os does not have the long mode flag.
Whatever I recommend if you have a windows 7 32 bit OS then go for 32bit or x86 binaries and as for Ubuntu 12.04 use command uname -a
or grep lm /proc/cpuinfo
(grep lm /proc/cpuinfo
does not return value for 32 bit as 32 bit os does not has the cpuinfo flag) to know the architecture OS your OS then use the binaries according to your OS.
** Note. Remember you can always install 64 bit os in 32 bit system as long as it supports enhanced 64 bit.. 64 bit os works better some times for multi purpose work and also supports more ram than 32bits. also you can install 32bit s/w in 64 bit os..
** OS = Operating system.
Using the OCI8 extension to access Oracle Database. So Download php_oci8.dll from 1https://pecl.php.net/package/oci8/2.0.8/windows. (5.6 Thread Safe (TS) x86 ) php_oci8.dll must be the same version with your php version.Then unzipped it and you will find
1.php_oci8.dll
2.php_oci8_11g.dll (as per your oralce version) these two file pasted into your
(xampp\php\ext) folder.
Open your php.ini file and add these extension=php_oci8.dll extension=php_oci8_11g.dll
Check your oracle version and service name using these commands
show parameter service_name; service_name is orcl (you should remember this service name)
After downloading instantclient_11_1 unzipped it and then pasted in your Local Disk. And copy the path C:\instantclient_11_1 and then set this path as your user variable & system variable. Note is that my code is working without setting path variable.
Open your cmd and enter into SQL, create your schema following these commands
grant connect,resource to dbname;
Create table user_info and insert data into your table and commit out. Note: you must commit your data either data is not inserted.
<html>_x000D_
<head><title>Oracle demo</title></head>_x000D_
<body>_x000D_
<?php_x000D_
_x000D_
// Create connection to Oracle_x000D_
$conn = oci_connect("dbname", "pass123", "//localhost/orcl"); // orcl is your service_name_x000D_
_x000D_
$query = 'select * from user_info';_x000D_
$stid = oci_parse($conn, $query);_x000D_
$r = oci_execute($stid);_x000D_
_x000D_
// Fetch each row in an associative array_x000D_
print '<table border="1">';_x000D_
while ($row = oci_fetch_array($stid, OCI_RETURN_NULLS+OCI_ASSOC)) {_x000D_
print '<tr>';_x000D_
foreach ($row as $item) {_x000D_
print '<td>'.($item !== null ? htmlentities($item, ENT_QUOTES) : ' ').'</td>';_x000D_
}_x000D_
print '</tr>';_x000D_
}_x000D_
print '</table>';
_x000D_
The easiest way to fix this is to add a new factor to your column. Use the levels function to determine how many factors you have and then add a new factor.
> levels(data$Fireplace.Qu)
[1] "Ex" "Fa" "Gd" "Po" "TA"
> levels(data$Fireplace.Qu) = c("Ex", "Fa", "Gd", "Po", "TA", "None")
[1] "Ex" "Fa" "Gd" "Po" " TA" "None"
And if you can't repeat the background image (for esthetic reasons), then this handy JQuery plugin will stretch the background image to fit the window.
Backstretch http://srobbin.com/jquery-plugins/backstretch/
Works great...
~Cheers!
You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly
The JsonValue.Parse() Method parses JSON text and returns a JsonValue:
JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");
If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:
using System.Json;
JsonObject result = value as JsonObject;
Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);
The classes are quite similar to those found in the System.Xml.Linq Namespace.
That's not the way to concat in MYSQL. Use the CONCAT function Have a look here: http://dev.mysql.com/doc/refman/4.1/en/string-functions.html#function_concat
You could just use index
on the list to find where somevalue
is and then get the previous and next as needed:
def find_prev_next(elem, elements):
previous, next = None, None
index = elements.index(elem)
if index > 0:
previous = elements[index -1]
if index < (len(elements)-1):
next = elements[index +1]
return previous, next
foo = 'three'
list = ['one','two','three', 'four', 'five']
previous, next = find_prev_next(foo, list)
print previous # should print 'two'
print next # should print 'four'
How old is Frank? I don't know (null).
How old is Shirley? I don't know (null).
Are Frank and Shirley the same age?
Correct answer should be "I don't know" (null), not "no", as Frank and Shirley might be the same age, we simply don't know.
Get the time in milliseconds, minus your minutes in milliseconds and convert it to Date. Here you need to objectify one!!!
int minutes = 60;
long currentDateTime = System.currentTimeMillis();
Date currentDate = new Date(currentDateTime - minutes*60*1000);
System.out.println(currentDate);
I have faced the same issue with you, then solved it,
Here are solutions, I wish it maybe can help
First
In the IIS modules
Configuration, loop up the WebDAVModule, if your web server has it, then remove it
Second
In the IIS handler mappings
configuration, you can see the list of enabling handler, to choose the PHP item
, edit it, on the edit page, click request restrictions button, then select the verbs tab
in the modal, in the specify the verbs to be handle label, check the all verbs radio
, then click ok, you also maybe see a warning, it shows us that use double quotation marks to PHP-CGI execution, then do it
if done it, then restart IIS server, it will be ok
@Francisco Goldenstein, just a minor correction. The COMMIT must be used after you set the variable, otherwise the WHILE will be executed just once:
DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;
WHILE (@Deleted_Rows > 0)
BEGIN
BEGIN TRANSACTION
-- Delete some small number of rows at a time
DELETE TOP (10000) LargeTable
WHERE readTime < dateadd(MONTH,-7,GETDATE())
SET @Deleted_Rows = @@ROWCOUNT;
COMMIT TRANSACTION
CHECKPOINT -- for simple recovery model
END
You seem to be using Windows Forms. Look at the SelectedIndex or SelectedItem properties.
if (this.combo1.SelectedItem == MY_OBJECT)
{
// do stuff
}
What worked here : on the client
1) ssh-add
2) ssh-copy-id user@server
The keys has been created some time ago with plain "ssh-keygen -t rsa" I sw the error message because I copied across my ssh public key from client to server (with ssh-id-copy) without running ssh-add first, since I erroneously assumed I'd added them some time earlier.
I just got that problem when converting from %
formatting to .format()
.
Previous code:
"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}
Problematic syntax:
"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)
The problem is that format
is a function that needs parameters. They cannot be strings.
That is one of worst python error messages I've ever seen.
Corrected code:
"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)
Using
try:
with open("path", "r") as file:#or just open
may cause some troubles when file is opened by some other processes (i.e. user opened it manually). You can solve your poblem using win32com library. Below code checks if any excel files are opened and if none of them matches the name of your particular one, openes a new one.
import win32com.client as win32
xl = win32.gencache.EnsureDispatch('Excel.Application')
my_workbook = "wb_name.xls"
xlPath="my_wb_path//" + my_workbook
if xl.Workbooks.Count > 0:
# if none of opened workbooks matches the name, openes my_workbook
if not any(i.Name == my_workbook for i in xl.Workbooks):
xl.Workbooks.Open(Filename=xlPath)
xl.Visible = True
#no workbooks found, opening
else:
xl.Workbooks.Open(Filename=xlPath)
xl.Visible = True
'xl.Visible = True is not necessary, used just for convenience'
Hope this will help
The reason you're getting this error has to do with how the list comprehension is performed.
Keep in mind the following:
[ expression for item in list if conditional ]
Is equivalent to:
for item in list:
if conditional:
expression
Where the expression
is in a slightly different format (think switching the subject and verb order in a sentence).
Therefore, your code [x+1 for x in l if x >= 45]
does this:
for x in l:
if x >= 45:
x+1
However, this code [x+1 if x >= 45 else x+5 for x in l]
does this (after rearranging the expression
):
for x in l:
if x>=45: x+1
else: x+5
This is a faster solution as it doesn't suffer for string concatenation computation complexity O(n^2). On the other hand its loop free, fully recursive
public static void main(String[] args) {
permutation("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
private static void permutation(String str) {
char[] stringArray = str.toCharArray();
printPermutation(stringArray, 0, stringArray.length, 0, 1);
}
private static void printPermutation(char[] string, int loopCounter, int length, int indexFrom, int indexTo) {
// Stop condition
if (loopCounter == length)
return;
/*
When reaching the end of the array:
1- Reset loop indices.
2- Increase length counter.
*/
if (indexTo == length) {
indexFrom = 0;
indexTo = 1;
++loopCounter;
}
// Print.
System.out.println(string);
// Swap from / to indices.
char temp = string[indexFrom];
string[indexFrom] = string[indexTo];
string[indexTo] = temp;
// Go for next iteration.
printPermutation(string, loopCounter, length, ++indexFrom, ++indexTo);
}
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
You can define your escape character, but you can only use it with a LIKE
clause.
Example:
SELECT columns FROM table
WHERE column LIKE '%\%%' ESCAPE '\'
Here it will search for %
in whole string and this is how one can use ESCAPE
identifier in SQL Server
.
In my app/build.gradle file , version code was like this:-
In place of versionCode flutterVersionCode.toInteger() , i replaced it with as versionCode 2
^https?://
You might have to escape the forward slashes though, depending on context.
They are found on either one of the below locations depending on how chrome was installed
~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions
/Library/Application\ Support/Google/Chrome/Default/Extensions
volatile
only guarantees that all threads, even themselves, are incrementing. For example: a counter sees the same face of the variable at the same time. It is not used instead of synchronized or atomic or other stuff, it completely makes the reads synchronized. Please do not compare it with other java keywords. As the example shows below volatile variable operations are also atomic they fail or succeed at once.
package io.netty.example.telnet;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static volatile int a = 0;
public static void main(String args[]) throws InterruptedException{
List<Thread> list = new ArrayList<Thread>();
for(int i = 0 ; i<11 ;i++){
list.add(new Pojo());
}
for (Thread thread : list) {
thread.start();
}
Thread.sleep(20000);
System.out.println(a);
}
}
class Pojo extends Thread{
int a = 10001;
public void run() {
while(a-->0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Main.a++;
System.out.println("a = "+Main.a);
}
}
}
Even you put volatile or not results will always differ. But if you use AtomicInteger as below results will be always same. This is same with synchronized also.
package io.netty.example.telnet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static volatile AtomicInteger a = new AtomicInteger(0);
public static void main(String args[]) throws InterruptedException{
List<Thread> list = new ArrayList<Thread>();
for(int i = 0 ; i<11 ;i++){
list.add(new Pojo());
}
for (Thread thread : list) {
thread.start();
}
Thread.sleep(20000);
System.out.println(a.get());
}
}
class Pojo extends Thread{
int a = 10001;
public void run() {
while(a-->0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
Main.a.incrementAndGet();
System.out.println("a = "+Main.a);
}
}
}
Ctrl + Alt + O to optimize imports
I ran into this exact issue upon a new install of Apache 2.4. After a few hours of googling and testing I finally found out that I also had to allow access to the directory that contains the (non-existent) target of the Alias directive. That is, this worked for me:
# File: /etc/apache2/conf-available/php5-fpm.conf
<IfModule mod_fastcgi.c>
AddHandler php5-fcgi .php
Action php5-fcgi /php5-fcgi
Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization
# NOTE: using '/usr/lib/cgi-bin/php5-cgi' here does not work,
# it doesn't exist in the filesystem!
<Directory /usr/lib/cgi-bin>
Require all granted
</Directory>
</Ifmodule>
Throw it away and start again. Ignore all these answers - don't waste your time.
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);
SSIS Integration with Visual Studio 2017 available from Aug 2017.
SSIS designer is now available for Visual Studio 2017! ARCHIVE
I installed in July 2018 and appears working fine. See Download link
There is an inspiration here. Just utilize shell regex
or git regex
.
git checkout commit_id */*.bat # *.bat in 1-depth subdir exclude current dir, shell regex
git checkout commit_id '*.bat' # *.bat in all subdir include current dir, git regex
Use quotation to escape shell regex interpretation and pass wildcards to git.
The first one is not recursive, only files in 1-depth subdir
. But the second one is recursive.
As for your situation, the following may be enough.
git checkout master */*/wp-content/*/*
git checkout master '*/wp-content/*'
Just hack the lines as required.
with the massive remit by google to stop both spam and the scraping of their search database, I believe that this is part of the effort to track bots etc.
some simple anti bot pseudo could go like this.
On GET (google.*) Save RemoteEndPoint
{
If RemoteEndPoint GETs (clients1.google.com/generate_204) Then
Set botAlert_stage1 = false;
Else
Set botAlert_stage1 = true;
End If
}
I also believe that the latest google frontpage 'theme' is also a new tool to help with the anti spam/bot activity.
** NOTE ** ipv6.google.com also includes this measure.
Just my unfounded unproofed two 2p.
That depends. Is it just a variable (in a method)? Or a class-member?
If it's just a variable you'll get an error that no value has been set when trying to read from it without first assinging it a value.
If it's a class-member it will be initialized to null by the VM.
Adding a summary answer as the accepted one is quite long. The terms "row" and "column" are used in the context of CQL, not how Cassandra is actually implemented.
Examples:
PRIMARY KEY (a)
: The partition key is a
.PRIMARY KEY (a, b)
: The partition key is a
, the clustering key is b
.PRIMARY KEY ((a, b))
: The composite partition key is (a, b)
.PRIMARY KEY (a, b, c)
: The partition key is a
, the composite clustering key is (b, c)
.PRIMARY KEY ((a, b), c)
: The composite partition key is (a, b)
, the clustering key is c
.PRIMARY KEY ((a, b), c, d)
: The composite partition key is (a, b)
, the composite clustering key is (c, d)
.There is a better why to determine type of an image. with exif_imagetype
If you use this function, you can tell image's real extension.
with this function filename's extension is completely irrelevant, which is good.
function setHeaderContentType(string $filePath): void
{
$numberToContentTypeMap = [
'1' => 'image/gif',
'2' => 'image/jpeg',
'3' => 'image/png',
'6' => 'image/bmp',
'17' => 'image/ico'
];
$contentType = $numberToContentTypeMap[exif_imagetype($filePath)] ?? null;
if ($contentType === null) {
throw new Exception('Unable to determine content type of file.');
}
header("Content-type: $contentType");
}
You can add more types from the link.
Hope it helps.
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
This is the way to disable all constraints from a specific view
NSLayoutConstraint.deactivate(myView.constraints)
It should be at least this:
public function login(Request $loginCredentials){
$data = $loginCredentials->all();
return $data['username'];
}
Here is an alternative which uses a custom output iterator. This example behaves correctly for the case of an empty list. This example demonstrates how to create a custom output iterator, similar to std::ostream_iterator
.
#include <iterator>
#include <vector>
#include <iostream>
#include <sstream>
struct CommaIterator
:
public std::iterator<std::output_iterator_tag, void, void, void, void>
{
std::ostream *os;
std::string comma;
bool first;
CommaIterator(std::ostream& os, const std::string& comma)
:
os(&os), comma(comma), first(true)
{
}
CommaIterator& operator++() { return *this; }
CommaIterator& operator++(int) { return *this; }
CommaIterator& operator*() { return *this; }
template <class T>
CommaIterator& operator=(const T& t) {
if(first)
first = false;
else
*os << comma;
*os << t;
return *this;
}
};
int main () {
// The vector to convert
std::vector<int> v(3,3);
// Convert vector to string
std::ostringstream oss;
std::copy(v.begin(), v.end(), CommaIterator(oss, ","));
std::string result = oss.str();
const char *c_result = result.c_str();
// Display the result;
std::cout << c_result << "\n";
}
Examining Android source code, you can find that there already is a member function of ScrollView
– scrollToChild(View)
– that does exactly what is requested. Unfortunatelly, this function is for some obscure reason marked private
. Based on that function I've written following function that finds the first ScrollView
above the View
specified as a parameter and scrolls it so that it becomes visible within the ScrollView
:
private void make_visible(View view)
{
int vt = view.getTop();
int vb = view.getBottom();
View v = view;
for(;;)
{
ViewParent vp = v.getParent();
if(vp == null || !(vp instanceof ViewGroup))
break;
ViewGroup parent = (ViewGroup)vp;
if(parent instanceof ScrollView)
{
ScrollView sv = (ScrollView)parent;
// Code based on ScrollView.computeScrollDeltaToGetChildRectOnScreen(Rect rect) (Android v5.1.1):
int height = sv.getHeight();
int screenTop = sv.getScrollY();
int screenBottom = screenTop + height;
int fadingEdge = sv.getVerticalFadingEdgeLength();
// leave room for top fading edge as long as rect isn't at very top
if(vt > 0)
screenTop += fadingEdge;
// leave room for bottom fading edge as long as rect isn't at very bottom
if(vb < sv.getChildAt(0).getHeight())
screenBottom -= fadingEdge;
int scrollYDelta = 0;
if(vb > screenBottom && vt > screenTop)
{
// need to move down to get it in view: move down just enough so
// that the entire rectangle is in view (or at least the first
// screen size chunk).
if(vb-vt > height) // just enough to get screen size chunk on
scrollYDelta += (vt - screenTop);
else // get entire rect at bottom of screen
scrollYDelta += (vb - screenBottom);
// make sure we aren't scrolling beyond the end of our content
int bottom = sv.getChildAt(0).getBottom();
int distanceToBottom = bottom - screenBottom;
scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
}
else if(vt < screenTop && vb < screenBottom)
{
// need to move up to get it in view: move up just enough so that
// entire rectangle is in view (or at least the first screen
// size chunk of it).
if(vb-vt > height) // screen size chunk
scrollYDelta -= (screenBottom - vb);
else // entire rect at top
scrollYDelta -= (screenTop - vt);
// make sure we aren't scrolling any further than the top our content
scrollYDelta = Math.max(scrollYDelta, -sv.getScrollY());
}
sv.smoothScrollBy(0, scrollYDelta);
break;
}
// Transform coordinates to parent:
int dy = parent.getTop()-parent.getScrollY();
vt += dy;
vb += dy;
v = parent;
}
}
TortoiseSVN doesn't use svn.exe it has SVN library compiled in. If you need to run your own tasks you would have to install stand alone subversion client. You either from Cygwin [http://cygwin.com ] or get a native version from http://subversion.apache.org/packages.html#windows
It works on firefox, if you change onClick() to click() in javascript part.
$("img.foo").click(function()_x000D_
{_x000D_
// Get the src of the image_x000D_
var src = $(this).attr("src");_x000D_
_x000D_
// Send Ajax request to backend.php, with src set as "img" in the POST data_x000D_
$.post("/backend.php", {"img": src});_x000D_
});
_x000D_
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
I'm sure it is a late response, but maybe is useful for somebody else.
You can put all your <li>
element content into <a>
tag and add the following css:
li a {
display: block;
/* and you can use padding for additional space if needs, as a clickable area / or other styling */
padding: 5px 20px;
}
Site I have inherited, had a scroll on links. To disable this scroll on click on specific button temporary, this worked for me:
$(document).ready(function() {
$('button.class-name').click(function(event) {
disableScroll();
setTimeout(enableScroll, 500);
});
});
function disableScroll() {
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
window.onscroll = function() {
window.scrollTo(scrollLeft, scrollTop);
};
}
function enableScroll() {
window.onscroll = function() {};
}
The Angular version with no third-party libraries (based on personal_cloud's answer):
import { Component, Renderer2, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit, OnDestroy {
@ViewChild('leftPanel', {static: true})
leftPanelElement: ElementRef;
@ViewChild('rightPanel', {static: true})
rightPanelElement: ElementRef;
@ViewChild('separator', {static: true})
separatorElement: ElementRef;
private separatorMouseDownFunc: Function;
private documentMouseMoveFunc: Function;
private documentMouseUpFunc: Function;
private documentSelectStartFunc: Function;
private mouseDownInfo: any;
constructor(private renderer: Renderer2) {
}
ngAfterViewInit() {
// Init page separator
this.separatorMouseDownFunc = this.renderer.listen(this.separatorElement.nativeElement, 'mousedown', e => {
this.mouseDownInfo = {
e: e,
offsetLeft: this.separatorElement.nativeElement.offsetLeft,
leftWidth: this.leftPanelElement.nativeElement.offsetWidth,
rightWidth: this.rightPanelElement.nativeElement.offsetWidth
};
this.documentMouseMoveFunc = this.renderer.listen('document', 'mousemove', e => {
let deltaX = e.clientX - this.mouseDownInfo.e.x;
// set min and max width for left panel here
const minLeftSize = 30;
const maxLeftSize = (this.mouseDownInfo.leftWidth + this.mouseDownInfo.rightWidth + 5) - 30;
deltaX = Math.min(Math.max(deltaX, minLeftSize - this.mouseDownInfo.leftWidth), maxLeftSize - this.mouseDownInfo.leftWidth);
this.leftPanelElement.nativeElement.style.width = this.mouseDownInfo.leftWidth + deltaX + 'px';
});
this.documentSelectStartFunc = this.renderer.listen('document', 'selectstart', e => {
e.preventDefault();
});
this.documentMouseUpFunc = this.renderer.listen('document', 'mouseup', e => {
this.documentMouseMoveFunc();
this.documentSelectStartFunc();
this.documentMouseUpFunc();
});
});
}
ngOnDestroy() {
if (this.separatorMouseDownFunc) {
this.separatorMouseDownFunc();
}
if (this.documentMouseMoveFunc) {
this.documentMouseMoveFunc();
}
if (this.documentMouseUpFunc) {
this.documentMouseUpFunc();
}
if (this.documentSelectStartFunc()) {
this.documentSelectStartFunc();
}
}
}
_x000D_
.main {
display: flex;
height: 400px;
}
.left {
width: calc(50% - 5px);
background-color: rgba(0, 0, 0, 0.1);
}
.right {
flex: auto;
background-color: rgba(0, 0, 0, 0.2);
}
.separator {
width: 5px;
background-color: red;
cursor: col-resize;
}
_x000D_
<div class="main">
<div class="left" #leftPanel></div>
<div class="separator" #separator></div>
<div class="right" #rightPanel></div>
</div>
_x000D_
first off, to be a bit of a henpeck, its best NOT to use just the <background>
tag. rather, use the proper, more specific, <background-image>
tag.
the only way that i'm aware of to do such a thing is to build the padding into the image by extending the matte. since the empty pixels aren't stripped, you have your padding right there. so if you need a 10px border, create 10px of empty pixels all around your image. this is mui simple in Photoshop, Fireworks, GIMP, &c.
i'd also recommend trying out the PNG8 format instead of the dying GIF... much better.
there may be an alternate solution to your problem if we knew a bit more of how you're using it. :) it LOOKS like you're trying to add an accordion button. this would be best placed in the HTML because then you can target it with JavaScript/PHP; something you cannot do if it's in the background (at least not simply). in such a case, you can style the heck out of the image you currently have in CSS by using the following:
#hello img { padding: 10px; }
WR!
Retrieving Files
$contents = Storage::get('file.jpg');
Downloading Files
return Storage::download('file.jpg');
File URLs
$url = Storage::url('file.jpg');
You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.
The command line would be done this way:
c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt
and the java code accesses the value like this:
String context = System.getProperty("myvar");
See this question about argument passing in Java.
Activator.CreateInstance()
returns an object, which doesn't have an Output method.
It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.
Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?
If you absolutely want to load the assembly via Assembly.Load
, you will have to go via reflection to call any members on c
Something like type.GetMethod("Output").Invoke(c, null);
should do it.
I present a small hybrid script [BAT/VBS] to create a desktop shortcut. And you can of course modifie it to your purpose.
@echo off
mode con cols=87 lines=5 & color 9B
Title Shortcut Creator for your batch and applications files by Hackoo 2015
Set MyFile=%~f0
Set ShorcutName=HackooTest
(
echo Call Shortcut("%MyFile%","%ShorcutName%"^)
echo ^'**********************************************************************************************^)
echo Sub Shortcut(ApplicationPath,Nom^)
echo Dim objShell,DesktopPath,objShortCut,MyTab
echo Set objShell = CreateObject("WScript.Shell"^)
echo MyTab = Split(ApplicationPath,"\"^)
echo If Nom = "" Then
echo Nom = MyTab(UBound(MyTab^)^)
echo End if
echo DesktopPath = objShell.SpecialFolders("Desktop"^)
echo Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^)
echo objShortCut.TargetPath = Dblquote(ApplicationPath^)
echo ObjShortCut.IconLocation = "Winver.exe,0"
echo objShortCut.Save
echo End Sub
echo ^'**********************************************************************************************
echo ^'Fonction pour ajouter les doubles quotes dans une variable
echo Function DblQuote(Str^)
echo DblQuote = Chr(34^) ^& Str ^& Chr(34^)
echo End Function
echo ^'**********************************************************************************************
) > Shortcutme.vbs
Start /Wait Shortcutme.vbs
Del Shortcutme.vbs
::***************************************Main Batch*******************************************
cls
echo Done and your main batch goes here !
echo i am a test
Pause > Nul
::********************************************************************************************
In order of preference:
{{ var|e('html_attr') }}
htmlentities($var, ENT_QUOTES | ENT_HTML5, $charset)
and make sure the rest of your document uses the same character set as $charset
. In most cases, 'UTF-8'
is the desired character set.Also, make sure you escape on output, not on input.
Cast the operands to floats:
float ans = (float)a / (float)b;
Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.
On PSv5.1 or higher, where >
and >>
are effectively aliases of Out-File
, you can set the default encoding for >
/ >>
/ Out-File
via the $PSDefaultParameterValues
preference variable:
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
On PSv5.0 or below, you cannot change the encoding for >
/ >>
, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File
.
(The $PSDefaultParameterValues
preference variable was introduced in PSv3.0).
On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
an -Encoding
parameter (which in PSv5.1+ includes >
and >>
), use:
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
If you place this command in your $PROFILE
, cmdlets such as Out-File
and Set-Content
will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding
parameter.
Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues
:
$PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }
Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.
For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.
The automatic $OutputEncoding
variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.
PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.
This means that source-code files without a BOM are assumed to be UTF-8, and using >
/ Out-File
/ Set-Content
defaults to BOM-less UTF-8; explicit use of the utf8
-Encoding
argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom
value.
If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1
file will typically not have a UTF-8 pseudo-BOM:
Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat
, sed
, and awk
- and even some editors such as gedit
- to pass the pseudo-BOM through, i.e., to treat it as data.
bash
with, say, text=$(cat file)
or text=$(<file)
- the resulting variable will contain the pseudo-BOM as the first 3 bytes.Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.
Note:
The following doesn't aspire to cover all standard cmdlets.
Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.
As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.
Cmdlets that write:
Out-File
and >
/ >>
create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content
/ Add-Content
(see next point); New-ModuleManifest
and Export-CliXml
also create UTF-16LE files.
Set-Content
(and Add-Content
if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default
).
Export-Csv
indeed creates ASCII files, as documented, but see the notes re -Append
below.
Export-PSSession
creates UTF-8 files with BOM by default.
New-Item -Type File -Value
currently creates BOM-less(!) UTF-8.
The Send-MailMessage
help topic also claims that ASCII encoding is the default - I have not personally verified that claim.
Start-Transcript
invariably creates UTF-8 files with BOM, but see the notes re -Append
below.
Re commands that append to an existing file:
>>
/ Out-File -Append
make no attempt to match the encoding of a file's existing content.
That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding
, which is not an option with >>
(except indirectly in PSv5.1+, via $PSDefaultParameterValues
, as shown above).
In short: you must know the encoding of an existing file's content and append using that same encoding.
Add-Content
is the laudable exception: in the absence of an explicit -Encoding
argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.
This inconsistency between Out-File -Append
/ >>
and Add-Content
, which also affects PowerShell Core, is discussed in this GitHub issue.
Export-Csv -Append
partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append
assumes UTF-8 is, whereas Add-Content
assumes ANSI.
Start-Transcript -Append
partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.
Cmdlets that read (that is, the encoding used in the absence of a BOM):
Get-Content
and Import-PowerShellDataFile
default to ANSI (Default
), which is consistent with Set-Content
.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.
By contrast, Import-Csv
, Import-CliXml
and Select-String
assume UTF-8 in the absence of a BOM.
Switch to some other branch and delete Test_Branch
, as follows:
$ git checkout master
$ git branch -d Test_Branch
If above command gives you error - The branch 'Test_Branch' is not fully merged. If you are sure you want to delete it
and still you want to delete it, then you can force delete it using -D
instead of -d
, as:
$ git branch -D Test_Branch
To delete Test_Branch
from remote as well, execute:
git push origin --delete Test_Branch
you can remove last comma from a string by using slice() method, find the below example:
var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
strVal = strVal.slice(0, -1);
}
Here is an Example
function myFunction() {_x000D_
var strVal = $.trim($('.txtValue').text());_x000D_
var lastChar = strVal.slice(-1);_x000D_
if (lastChar == ',') { // check last character is string_x000D_
strVal = strVal.slice(0, -1); // trim last character_x000D_
$("#demo").text(strVal);_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p class="txtValue">Striing with Commma,</p>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<p id="demo"></p>
_x000D_
when(dao.doSearch(dto)).thenReturn(inspectionsSummaryList);//got error in this line
verify(dao).doSearchInspections(dto);
The when
here configures your mock to do something. However, you donot use this mock in any way anymore after this line (apart from doing a verify
). Mockito warns you that the when
line therefore is pointless. Perhaps you made a logic error?
As best I can tell, it is not possible to update the select2 options without refreshing the entire list or entering some search text and using a query function.
What are those buttons supposed to do? If they are used to determine the select options, why not put them outside of the select box, and have them programmatically set the select box data and then open it? I don't understand why you would want to put them on top of the search box. If the user is not supposed to search, you can use the minimumResultsForSearch option to hide the search feature.
Edit: How about this...
HTML:
<input type="hidden" id="select2" class="select" />
Javascript
var data = [{id: 0, text: "Zero"}],
select = $('#select2');
select.select2({
query: function(query) {
query.callback({results: data});
},
width: '150px'
});
console.log('Opening select2...');
select.select2('open');
setTimeout(function() {
console.log('Updating data...');
data = [{id: 1, text: 'One'}];
}, 1500);
setTimeout(function() {
console.log('Fake keyup-change...');
select.data().select2.search.trigger('keyup-change');
}, 3000);
Example: Plunker
Edit 2: That will at least get it to update the list, however there is still some weirdness if you have entered search text before triggering the keyup-change
event.
You can't use CUDA for GPU Programming as CUDA is supported by NVIDIA devices only. If you want to learn GPU Computing I would suggest you to start CUDA and OpenCL simultaneously. That would be very much beneficial for you.. Talking about CUDA, you can use mCUDA. It doesn't require NVIDIA's GPU..
As of 2017-10.
Solution that solved my issue.
Currently that FB renders this surprise.
...app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on...
The settings to adjust are located here https://developers.facebook.com/apps/[your_app_itentifier]/fb-login/.
The trailing slash is important. They must match in your app code and in FB admin settings. So this is a config somewhere in your code (see below how to get any domain name for a dev app):
{
callbackURL: `http://my_local_app.com:3000/callback/`, // trailing slash
}
and here
To get any domain name for an app on a local Windows machine, edit host
file. Custom names are good in order to get rid of all those localhost:8080
, 0.0.0.0:30303
, 127.0.0.0:8000
, so forth. Because some third party services like FB sometimes fail to let you use 127.0.0.0
names.
On Windows 10 hosts
file is here:
C:\Windows\System32\drivers\etc\hosts
Backup initial file, create a copy with different name (Doesn't work in native Windows CMD. I use Git for Windows, it has many Unix commands)
$ cp hosts hosts.bak
Add this in hosts
127.0.0.1 myfbapp.com # you can access it in a browser http://myfbapp.com:3000
127.0.0.1 www.myotherapp.io # In a browser http://www.myotherapp.io:2020
In order to get rid of port part :3000
set up NGINX, for example.
Frequently we deal with other fellow java programmers work which create these Stored Procedure. and we do not want to mess around with it. but there is possibility you get the result set where these exec sample return 0 (almost Stored procedure call returning zero).
check this sample :
public void generateINOUT(String USER, int DPTID){
try {
conUrl = JdbcUrls + dbServers +";databaseName="+ dbSrcNames+";instance=MSSQLSERVER";
con = DriverManager.getConnection(conUrl,dbUserNames,dbPasswords);
//stat = con.createStatement();
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate("DECLARE @RC int\n" +
"DECLARE @pUserID nvarchar(50)\n" +
"DECLARE @pDepartmentID int\n" +
"DECLARE @pStartDateTime datetime\n" +
"DECLARE @pEndDateTime datetime\n" +
"EXECUTE [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] \n" +
""+USER +
"," +DPTID+
",'"+STARTDATE +
"','"+ENDDATE+"'");
ResultSet rs = st.getGeneratedKeys();
while (rs.next()){
String userID = rs.getString("UserID");
Timestamp timeIN = rs.getTimestamp("timeIN");
Timestamp timeOUT = rs.getTimestamp ("timeOUT");
int totTime = rs.getInt ("totalTime");
int pivot = rs.getInt ("pivotvalue");
timeINS = sdz.format(timeIN);
userIN.add(timeINS);
timeOUTS = sdz.format(timeOUT);
userOUT.add(timeOUTS);
System.out.println("User : "+userID+" |IN : "+timeIN+" |OUT : "+timeOUT+"| Total Time : "+totTime+" | PivotValue : "+pivot);
}
con.commit();
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
if (e.getCause() != null) {
e.getCause().printStackTrace();}
}
}
I came to this solutions after few days trial and error, googling and get confused ;) it execute below Stored Procedure :
USE [AccessManager]
GO
/****** Object: StoredProcedure [dbo].[SP_GenerateInOutDetailReportSimple]
Script Date: 04/05/2013 15:54:11 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_GenerateInOutDetailReportSimple]
(
@pUserID nvarchar(50),
@pDepartmentID int,
@pStartDateTime datetime,
@pEndDateTime datetime
)
AS
Declare @ErrorCode int
Select @ErrorCode = @@Error
Declare @TransactionCountOnEntry int
If @ErrorCode = 0
Begin
Select @TransactionCountOnEntry = @@TranCount
BEGIN TRANSACTION
End
If @ErrorCode = 0
Begin
-- Create table variable instead of SQL temp table because report wont pick up the temp table
DECLARE @tempInOutDetailReport TABLE
(
UserID nvarchar(50),
LogDate datetime,
LogDay varchar(20),
TimeIN datetime,
TimeOUT datetime,
TotalTime int,
RemarkTimeIn nvarchar(100),
RemarkTimeOut nvarchar(100),
TerminalIPTimeIn varchar(50),
TerminalIPTimeOut varchar(50),
TerminalSNTimeIn nvarchar(50),
TerminalSNTimeOut nvarchar(50),
PivotValue int
)
-- Declare variables for the while loop
Declare @LogUserID nvarchar(50)
Declare @LogEventID nvarchar(50)
Declare @LogTerminalSN nvarchar(50)
Declare @LogTerminalIP nvarchar(50)
Declare @LogRemark nvarchar(50)
Declare @LogTimestamp datetime
Declare @LogDay nvarchar(20)
-- Filter off userID, departmentID, StartDate and EndDate if specified, only process the remaining logs
-- Note: order by user then timestamp
Declare LogCursor Cursor For
Select distinct access_event_logs.USERID, access_event_logs.EVENTID,
access_event_logs.TERMINALSN, access_event_logs.TERMINALIP,
access_event_logs.REMARKS, access_event_logs.LOCALTIMESTAMP, Datename(dw,access_event_logs.LOCALTIMESTAMP) AS WkDay
From access_event_logs
Left Join access_user on access_user.User_ID = access_event_logs.USERID
Left Join access_user_dept on access_user.User_ID = access_user_dept.User_ID
Where ((Dept_ID = @pDepartmentID) OR (@pDepartmentID IS NULL))
And ((access_event_logs.USERID LIKE '%' + @pUserID + '%') OR (@pUserID IS NULL))
And ((access_event_logs.LOCALTIMESTAMP >= @pStartDateTime ) OR (@pStartDateTime IS NULL))
And ((access_event_logs.LOCALTIMESTAMP < DATEADD(day, 1, @pEndDateTime) ) OR (@pEndDateTime IS NULL))
And (access_event_logs.USERID != 'UNKNOWN USER') -- Ignore UNKNOWN USER
Order by access_event_logs.USERID, access_event_logs.LOCALTIMESTAMP
Open LogCursor
Fetch Next
From LogCursor
Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
-- Temp storage for IN event details
Declare @InEventUserID nvarchar(50)
Declare @InEventDay nvarchar(20)
Declare @InEventTimestamp datetime
Declare @InEventRemark nvarchar(100)
Declare @InEventTerminalIP nvarchar(50)
Declare @InEventTerminalSN nvarchar(50)
-- Temp storage for OUT event details
Declare @OutEventUserID nvarchar(50)
Declare @OutEventTimestamp datetime
Declare @OutEventRemark nvarchar(100)
Declare @OutEventTerminalIP nvarchar(50)
Declare @OutEventTerminalSN nvarchar(50)
Declare @CurrentUser varchar(50) -- used to indicate when we change user group
Declare @CurrentDay varchar(50) -- used to indicate when we change day
Declare @FirstEvent int -- indicate the first event we received
Declare @ReceiveInEvent int -- indicate we have received an IN event
Declare @PivotValue int -- everytime we change user or day - we reset it (reporting purpose), if same user..keep increment its value
Declare @CurrTrigger varchar(50) -- used to keep track of the event of the current event log trigger it is handling
Declare @CurrTotalHours int -- used to keep track of total hours of the day of the user
Declare @FirstInEvent datetime
Declare @FirstInRemark nvarchar(100)
Declare @FirstInTerminalIP nvarchar(50)
Declare @FirstInTerminalSN nvarchar(50)
Declare @FirstRecord int -- indicate another day of same user
Set @PivotValue = 0 -- initialised
Set @CurrentUser = '' -- initialised
Set @FirstEvent = 1 -- initialised
Set @ReceiveInEvent = 0 -- initialised
Set @CurrTrigger = '' -- Initialised
Set @CurrTotalHours = 0 -- initialised
Set @FirstRecord = 1 -- initialised
Set @CurrentDay = '' -- initialised
While @@FETCH_STATUS = 0
Begin
-- use to track current log trigger
Set @CurrTrigger =LOWER(@LogEventID)
If (@CurrentUser != '' And @CurrentUser != @LogUserID) -- new batch of user
Begin
If @ReceiveInEvent = 1 -- previous IN event is not cleared (no OUT is found)
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else -- same day
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Set @FirstEvent = 1 -- Reset flag (we are having a new user group)
Set @ReceiveInEvent = 0 -- Reset
Set @PivotValue = 0 -- Reset
--Set @CurrentDay = '' -- Reset
End
If LOWER(@LogEventID) = 'in' -- IN event
Begin
If @ReceiveInEvent = 1 -- previous IN event is not cleared (no OUT is found)
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Begin
Set @PivotValue = 0 -- Reset
--Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
-- RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
-- LogDate)
--values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp, @CurrTotalHours,
-- @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
-- DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
If((@CurrentDay != @LogDay And @CurrentDay != '') Or (@CurrentUser != @LogUserID And @CurrentUser != '') )
Begin
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
LogDate)
values( @CurrentUser, @CurrentDay, @FirstInEvent, @OutEventTimestamp, @CurrTotalHours,
@FirstInRemark, @OutEventRemark, @FirstInTerminalIP, @OutEventTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
Set @FirstRecord = 1
End
-- Save it
Set @InEventUserID = @LogUserID
Set @InEventDay = @LogDay
Set @InEventTimestamp = @LogTimeStamp
Set @InEventRemark = @LogRemark
Set @InEventTerminalIP = @LogTerminalIP
Set @InEventTerminalSN = @LogTerminalSN
If (@FirstRecord = 1) -- save for first in event record of the day
Begin
Set @FirstInEvent = @LogTimestamp
Set @FirstInRemark = @LogRemark
Set @FirstInTerminalIP = @LogTerminalIP
Set @FirstInTerminalSN = @LogTerminalSN
Set @CurrTotalHours = 0 --initialise total hours for another day
End
Set @FirstRecord = 0 -- no more first record of the day
Set @ReceiveInEvent = 1 -- indicate we have received an "IN" event
Set @FirstEvent = 0 -- no more "first" event
End
Else If LOWER(@LogEventID) = 'out' -- OUT event
Begin
If @FirstEvent = 1 -- the first OUT record when change users
Begin
-- Check day
If (@CurrentDay != @LogDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @LogDay -- update the day
-- Only an OUT event (no IN event) - invalid record but we show it anyway
Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
PivotValue, LogDate )
values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)))
Set @FirstEvent = 0 -- not "first" anymore
End
Else -- Not first event
Begin
If @ReceiveInEvent = 1 -- if there are IN event previously
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
Set @CurrTotalHours = @CurrTotalHours + DATEDIFF(second,@InEventTimestamp, @LogTimeStamp) -- update total time
Set @OutEventRemark = @LogRemark
Set @OutEventTerminalIP = @LogTerminalIP
Set @OutEventTerminalSN = @LogTerminalSN
Set @OutEventTimestamp = @LogTimestamp
-- valid row
--Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
-- RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
-- LogDate)
--values( @LogUserID, @InEventDay, @InEventTimestamp, @LogTimestamp, Datediff(second, @InEventTimestamp, @LogTimeStamp),
-- @InEventRemark, @LogRemark, @InEventTerminalIP, @LogTerminalIP, @InEventTerminalSN, @LogTerminalSN, @PivotValue,
-- DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
Set @ReceiveInEvent = 0 -- Reset
End
Else -- no IN event previously
Begin
-- Check day
If (@CurrentDay != @LogDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @LogDay -- update the day
-- invalid row (only has OUT event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
PivotValue, LogDate )
values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)) )
End
End
End
Set @CurrentUser = @LogUserID -- update user
Fetch Next
From LogCursor
Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay
End
-- Need to handle the last log if its IN log as it will not be processed by the while loop
if @CurrTrigger='in'
Begin
-- Check day
If (@CurrentDay != @InEventDay) -- change to another day
Set @PivotValue = 0 -- Reset
Else -- same day
Set @PivotValue = @PivotValue + 1 -- increment
Set @CurrentDay = @InEventDay -- update the day
-- invalid row (only has IN event)
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn,
TerminalSNTimeIn, PivotValue, LogDate )
values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP,
@InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
else if @CurrTrigger = 'out'
Begin
Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
LogDate)
values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp, @CurrTotalHours,
@FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))
End
Close LogCursor
Deallocate LogCursor
Select *
From @tempInOutDetailReport tempTable
Left Join access_user on access_user.User_ID = tempTable.UserID
Order By tempTable.UserID, LogDate
End
If @@TranCount > @TransactionCountOnEntry
Begin
If @ErrorCode = 0
COMMIT TRANSACTION
Else
ROLLBACK TRANSACTION
End
return @ErrorCode
you will get the "java SQL Code" by right click on stored procedure in your database. something like this :
DECLARE @RC int
DECLARE @pUserID nvarchar(50)
DECLARE @pDepartmentID int
DECLARE @pStartDateTime datetime
DECLARE @pEndDateTime datetime
-- TODO: Set parameter values here.
EXECUTE @RC = [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple]
@pUserID,@pDepartmentID,@pStartDateTime,@pEndDateTime
GO
check the query String I've done, that is your homework ;) so sorry answering this long, this is my first answer since I register few weeks ago to get answer.
Smoke testing is about checking if the requirements are satisfied or not. Smoke testing is a general health check up.
Sanity testing is about checking if a particular module is completely working or not. Sanity testing is specialized in particular health check up.
Globally, disabling the back button is indeed bad practice. But, in certain situations, the back button functionality doesn't make sense.
Here's one way to prevent unwanted navigation between pages:
Top page (file top.php
):
<?php
session_start();
$_SESSION[pid]++;
echo "top page $_SESSION[pid]";
echo "<BR><a href='secondary.php?pid=$_SESSION[pid]'>secondary page</a>";
?>
Secondary page (file secondary.php
):
<?php
session_start();
if ($_SESSION[pid] != $_GET[pid])
header("location: top.php");
else {
echo "secondary page $_SESSION[pid]";
echo "<BR><a href='top.php'>top</a>";
}
?>
The effect is to allow navigating from the top page forward to the secondary page and back (e.g. Cancel) using your own links. But, after returning to the top page the browser back button is prevented from navigating to the secondary page.
$LogPath = "E:\" # Your local of directories
$Folders = Get-Childitem $LogPath -dir -r | Where-Object {$_.name -like "*grav*"} # Your keyword name directories
foreach ($Folder in $Folders)
{
$Item = $Folder.FullName
Write-Output $Item
Remove-Item $Item -Force -Recurse -ErrorAction SilentlyContinue
}
This has obviously been fixed in newer releases (SE 6 and 7). I experience a 30 second caching time max when running the following code snippet while watching port 53 activity using tcpdump.
/**
* http://stackoverflow.com/questions/1256556/any-way-to-make-java-honor-the-dns-caching-timeout-ttl
*
* Result: Java 6 distributed with Ubuntu 12.04 and Java 7 u15 downloaded from Oracle have
* an expiry time for dns lookups of approx. 30 seconds.
*/
import java.util.*;
import java.text.*;
import java.security.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class Test {
final static String hostname = "www.google.com";
public static void main(String[] args) {
// only required for Java SE 5 and lower:
//Security.setProperty("networkaddress.cache.ttl", "30");
System.out.println(Security.getProperty("networkaddress.cache.ttl"));
System.out.println(System.getProperty("networkaddress.cache.ttl"));
System.out.println(Security.getProperty("networkaddress.cache.negative.ttl"));
System.out.println(System.getProperty("networkaddress.cache.negative.ttl"));
while(true) {
int i = 0;
try {
makeRequest();
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println(new Date());
inetAddress = InetAddress.getByName(hostname);
displayStuff(hostname, inetAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
Thread.sleep(5L*1000L);
} catch(Exception ex) {}
i++;
}
}
public static void displayStuff(String whichHost, InetAddress inetAddress) {
System.out.println("Which Host:" + whichHost);
System.out.println("Canonical Host Name:" + inetAddress.getCanonicalHostName());
System.out.println("Host Name:" + inetAddress.getHostName());
System.out.println("Host Address:" + inetAddress.getHostAddress());
}
public static void makeRequest() {
try {
URL url = new URL("http://"+hostname+"/");
URLConnection conn = url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
InputStreamReader ird = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(ird);
String res;
while((res = rd.readLine()) != null) {
System.out.println(res);
break;
}
rd.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Well, weeks ago I made a very similiar question (Get CDN url from uploaded file via Storage): I wanted the CDN url to show the image in my view (as you are requiring ).
However, after review the package API I confirmed that there is no way do this task. So, my solution was avoid using flysystem
. In my case, I needed to play with RackSpace. So, finally decide to create my use package and make my own storage package using The PHP SDK for OpenStack.
By this way, you have full access for functions that you need like getPublicUrl()
in order to get the public URL from a cdn container:
/** @var DataObject $file */
$file = \OpenCloud::container('cdn')->getObject('screenshots/1.jpg');
// $url: https://d224d291-8316ade.ssl.cf1.rackcdn.com/screenshots/1.jpg
$url = (string) $file->getPublicUrl(UrlType::SSL);
In conclusion, if need to take storage service to another level, then flysystem
is not enough. For local
purposes, you can try @nXu's solution
Try the following to see if you have the proper repository installed:
# yum search java | grep 'java-'
This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:
http://dag.wieers.com/rpm/FAQ.php#B
After you've got it installed try yum search again... This time you'll have a bunch of java stuff.
# yum search java | grep 'java-'
This will return the list of the available java packages. You can install one like this:
# yum install java-1.7.0-openjdk.x86_64
Just change moveCamera to animateCamera like below
Googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(locate, 16F))
If you used
brew install python
before 'unlink' you got
brew info python
/usr/local/Cellar/python/2.7.11
python -V
Python 2.7.10
so do
brew unlink python && brew link python
and open a new terminal shell
python -V
Python 2.7.11
If you happen to be using the amqplib library as I am, they have a handy example of an implementation of the Publish/Subscribe RabbitMQ tutorial which you might find handy.
Annoyingly Javascript's date.getSeconds()
et al will not pad the result with zeros 11:0:0
instead of 11:00:00
.
So I like to use
date.toLocaleTimestring()
Which renders 11:00:00 AM
. Just beware when using the extra options, some browsers don't support them (Safari)
If you have a xml like below
<e:Envelope
xmlns:d = "http://www.w3.org/2001/XMLSchema"
xmlns:e = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:wn0 = "http://systinet.com/xsd/SchemaTypes/"
xmlns:i = "http://www.w3.org/2001/XMLSchema-instance">
<e:Header>
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
</e:Header>
<e:Body>
<n0:ForAnsiHeaderOperResponse xmlns:n0 = "http://systinet.com/wsdl/com/magicsoftware/ibolt/localhost/ForAnsiHeader/ForAnsiHeaderImpl#ForAnsiHeaderOper?KExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS9sYW5nL1N0cmluZzs=">
<response i:type = "d:string">12--abc--pqr</response>
</n0:ForAnsiHeaderOperResponse>
</e:Body>
</e:Envelope>
and wanted to extract the below xml
<e:Header>
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
</e:Header>
The below code helps to achieve the same
public static void main(String[] args) {
File fXmlFile = new File("C://Users//abhijitb//Desktop//Test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document;
Node result = null;
try {
document = dbf.newDocumentBuilder().parse(fXmlFile);
XPath xPath = XPathFactory.newInstance().newXPath();
String xpathStr = "//Envelope//Header";
result = (Node) xPath.evaluate(xpathStr, document, XPathConstants.NODE);
System.out.println(nodeToString(result));
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException
| TransformerException e) {
e.printStackTrace();
}
}
private static String nodeToString(Node node) throws TransformerException {
StringWriter buf = new StringWriter();
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xform.transform(new DOMSource(node), new StreamResult(buf));
return (buf.toString());
}
Now if you want only the xml like below
<Friends>
<friend>
<Name>Testabc</Name>
<Age>12121</Age>
<Phone>Testpqr</Phone>
</friend>
</Friends>
You need to change the
String xpathStr = "//Envelope//Header";
to String xpathStr = "//Envelope//Header/*";
VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.
Object variables are guaranteed to be cleaned (set to Nothing
) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.
There are only two cases when you want an explicit cleanup:
When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).
When you have a circular reference between two or more objects.
If objectA
stores a references to objectB
, and objectB
stores a reference to objectA
, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing
or objectB.ReferenceToA = Nothing
.
The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.
If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.
).
If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.
).
Access level of a variable (public vs. private) does not affect its life time.
Apache Commons Lang has a Range
class for doing arbitrary ranges.
Range<Integer> test = Range.between(1, 3);
System.out.println(test.contains(2));
System.out.println(test.contains(4));
Guava Range
has similar API.
If you are just wanting to check if a number fits into a long value or an int value, you could try using it through BigDecimal
. There are methods for longValueExact
and intValueExact
that throw exceptions if the value is too big for those precisions.
Add store name to template like {% url 'app_name:url_name' %}
App_name = store
In urls.py,
path('search', views.searched, name="searched"),
<form action="{% url 'store:searched' %}" method="POST">
Using testflight :
1) create the ipa file by development certificate
2) upload the ipa file on testflight
3) Now, to identify the device to be tested on , add the device id on apple account and refresh your development certificate. Download the updated certificate and upload it on testflight website. Check the device id you are getting.
4) Now email the ipa file to the testers.
5) While downloading the ipa file, if the testers are not getting any warnings, this means the device token + provisioning profile has been verified. So, the testers can now download the ipa file on device and do the testing job...
Try this :
$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");
Just replace option[value="Bruce Jones"]
by option[value=result[0]]
And before selecting a new option, you might want to "unselect" the previous :
$('select[name^="salesrep"] option:selected').attr("selected",null);
You may want to read this too : jQuery get specific option tag text
Edit: Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/>
element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/>
element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.
If you want to stay with underscore so your predicate function can be more flexible, here are 2 ideas.
Since the predicate for _.find
receives both the value and index of an element, you can use side effect to retrieve the index, like this:
var idx;
_.find(tv, function(voteItem, voteIdx){
if(voteItem.id == voteID){ idx = voteIdx; return true;};
});
Looking at underscore source, this is how _.find
is implemented:
_.find = _.detect = function(obj, predicate, context) {
var result;
any(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
To make this a findIndex
function, simply replace the line result = value;
with result = index;
This is the same idea as the first method. I included it to point out that underscore uses side effect to implement _.find
as well.
__construct is always called when creating new objects or they are invoked when initialization takes place.it is suitable for any initialization that the object may need before it is used. __construct method is the first method executed in class.
class Test
{
function __construct($value1,$value2)
{
echo "Inside Construct";
echo $this->value1;
echo $this->value2;
}
}
//
$testObject = new Test('abc','123');
class stack
{ private int top;
private int[] element;
stack()
{element=new int[10];
top=-1;
}
void push(int item)
{top++;
if(top==9)
System.out.println("Overflow");
else
{
top++;
element[top]=item;
}
void pop()
{if(top==-1)
System.out.println("Underflow");
else
top--;
}
void display()
{
System.out.println("\nTop="+top+"\nElement="+element[top]);
}
public static void main(String args[])
{
stack s1=new stack();
s1.push(10);
s1.display();
s1.push(20);
s1.display();
s1.push(30);
s1.display();
s1.pop();
s1.display();
}
}
Output
Top=0
Element=10
Top=1
Element=20
Top=2
Element=30
Top=1
Element=20
You can use the old way:
public List magicalListGetter() {
List list = doMagicalVooDooHere();
return list;
}
or you can use Object
and the parent class of everything:
public List<Object> magicalListGetter() {
List<Object> list = doMagicalVooDooHere();
return list;
}
Note Perhaps there is a better parent class for all the objects you will put in the list. For example, Number
would allow you to put Double
and Integer
in there.
This is not a question about make, it is a question about the semantic of the #include
directive.
The problem is, that there is no file at the path "../StdCUtil/StdCUtil/split.h". This is the path that results when the compiler combines the include path "../StdCUtil" with the relative path from the #include
directive "StdCUtil/split.h".
To fix this, just use -I..
instead of -I../StdCUtil
.
public class Array {
static int a[] = new int[101];
int counter = 0;
public int add(int num) {
if (num <= 100) {
Array.a[this.counter] = num;
System.out.println(a[this.counter]);
this.counter++;
return add(num + 1);
}
return 0;
}
public static void main(String[] args) {
Array c = new Array();
c.add(1);
}
}
if your value is a pure text (like 'test') you could use the text() method as well. like this:
$('div.total-title').text('test');
anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:
$(document).ready(
function() {
$('div.total-title').text('test');
}
);
this way the script executes after the HTML of the div is parsed by the browser.
This is actually a JDK bug. It has been reported several times over the years, but only in 8139507 was it finally taken seriously by Oracle.
The problem was in the JDK source code for WindowsPreferences.java
. In this class, both nodes userRoot
and systemRoot
were declared static as in:
/**
* User root node.
*/
static final Preferences userRoot =
new WindowsPreferences(USER_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);
/**
* System root node.
*/
static final Preferences systemRoot =
new WindowsPreferences(SYSTEM_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);
This means that the first time the class is referenced both static variables would be initiated and by this the Registry Key for HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs
(= system tree) will be attempted to be created if it doesn't already exist.
So even if the user took every precaution in his own code and never touched or referenced the system tree, then the JVM would actually still try to instantiate systemRoot
, thus causing the warning. It is an interesting subtle bug.
There's a fix committed to the JDK source in June 2016 and it is part of Java9 onwards. There's also a backport for Java8 which is in u202.
What you see is really a warning from the JDK's internal logger. It is not an exception. I believe that the warning can be safely ignored .... unless the user code is indeed wanting the system preferences, but that is very rarely the case.
The bug did not reveal itself in versions prior to Java 1.7.21, because up until then the JRE installer would create Registry key HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs
for you and this would effectively hide the bug. On the other hand you've never really been required to run an installer in order to have a JRE on your machine, or at least this hasn't been Sun/Oracle's intent. As you may be aware Oracle has been distributing the JRE for Windows in .tar.gz
format for many years.
Try setting the initial value when you instantiate the form:
form = MyForm(initial={'max_number': '3'})
Thank you all for your help. This is my final version, and it works thanks to your combined help ! I am only showing the changes i made, all the rest is taken from Joe Chung's work
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
[DataMember]
public string responseDetails { get; set; }
[DataMember]
public int responseStatus { get; set; }
}
and
[DataContract]
public class ResponseData
{
[DataMember]
public List<Results> results { get; set; }
}
For finding value use below
if let a = companies["AAPL"] {
// a is the value
}
For traversing through the dictionary
for (key, value) in companies {
print(key,"---", value)
}
Finally for searching key by value you firstly add the extension
extension Dictionary where Value: Equatable {
func findKey(forValue val: Value) -> Key? {
return first(where: { $1 == val })?.key
}
}
Then just call
companies.findKey(val : "Apple Inc")
I think you're making this a bit more complicated than it needs to be.
SELECT
ProductID,
SUM(IF(PaymentMethod = 'Cash', Amount, 0)) AS 'Cash',
-- snip
SUM(Amount) AS Total
FROM
Payments
WHERE
SaleDate = '2012-02-10'
GROUP BY
ProductID
The relative path works in in java using the . operator.
So the question is how do you know the path where the java is currently looking?
do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output , you will come to know the current directory where java is looking . From there , simply use the ./ operator to locate your file.
for example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder MyProject simply use
File resourceFile = new File("../myFile.txt");
Hope this helps
try converting the date first.
$date = "2012-08-06";
mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('" . $_POST['post_title'] . "',
'" . $date . "')")
or die(mysql_error());
SQL Server / MS Access Syntax:
SELECT TOP 1 * FROM table_name ORDER BY RAND()
MySQL Syntax:
SELECT * FROM table_name ORDER BY RAND() LIMIT 1
There is no rocket science in deleting items from array. To delete items from any array you need to use splice
: $scope.items.splice(index, 1);
. Here is an example:
HTML
<!DOCTYPE html>
<html data-ng-app="demo">
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div data-ng-controller="DemoController">
<ul>
<li data-ng-repeat="item in items">
{{item}}
<button data-ng-click="removeItem($index)">Remove</button>
</li>
</ul>
<input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
</div>
</body>
</html>
JavaScript
"use strict";
var demo = angular.module("demo", []);
function DemoController($scope){
$scope.items = [
"potatoes",
"tomatoes",
"flour",
"sugar",
"salt"
];
$scope.addItem = function(item){
$scope.items.push(item);
$scope.newItem = null;
}
$scope.removeItem = function(index){
$scope.items.splice(index, 1);
}
}
You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ...
, it's not recommended. Take a closer look here
With the help of jquery it can be done as follows.
$("#color").prop('disabled', true);
It would look like this:
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
If the constants are for use just in a single class, you'd want to make them private
instead of public
.
https://github.com/aidanmelen/json_pretty_print
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import json
import jsonschema
def _validate(data):
schema = {"$schema": "http://json-schema.org/draft-04/schema#"}
try:
jsonschema.validate(data, schema,
format_checker=jsonschema.FormatChecker())
except jsonschema.exceptions.ValidationError as ve:
sys.stderr.write("Whoops, the data you provided does not seem to be " \
"valid JSON.\n{}".format(ve))
def pprint(data, python_obj=False, **kwargs):
_validate(data)
kwargs["indent"] = kwargs.get("indent", 4)
pretty_data = json.dumps(data, **kwargs)
if python_obj:
print(pretty_data)
else:
repls = (("u'",'"'),
("'",'"'),
("None",'null'),
("True",'true'),
("False",'false'))
print(reduce(lambda a, kv: a.replace(*kv), repls, pretty_data))
you need just in scss varible
$input-btn-focus-width: .05rem !default;
I have had this problem after a windows update. Windows Process Activation Service is dependent service for W3SVC. First, make sure that Windows Process Activation Service is running. In my case, it was not running and when I tried to run it manually, I got below error.
Windows Process Activation Service Error 2: The system cannot find the file specified
The issue seems to be, that windows adds an incorrect parameter to the WAS service startup parameters. I fixed the issue using the following steps:
Start regedit (just type it into start) Navigate to
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WAS\Parameters
Delete the NanoSetup variable. This variable is preventing WAS from starting
Start the WAS service using task manager
Now start the W3SVC service
You can now start your website in IIS again
I found above WPA service solution in this stack overflow thread.
For those who might be trying to create a Travis Build, the default path from which Django is installed from the requirements.txt
file points to a repo whose django_extensions
module has not been updated. The only workaround, for now, is to install from the master branch using pip. That is where the patch is made. But for now, we'll have to wait.
You can try this in the meantime, it might help
- pip install git+https://github.com/chibisov/drf-extensions.git@master
- pip install git+https://github.com/django-extensions/django-extensions.git@master
$('#message').val('');
Explanation (from @BalusC):
textarea
is an input
element with a value. You actually want to "empty" the value. So as for every other input
element (input
, select
, textarea
) you need to use element.val('');
.
Also see docs
Following is for fetching even number:: Select * from MEN where Men_ID%2=0;
Following is for fetching odd number:: Select * from MEN where Men_ID%2!=0;
Here MEN is your table_name Men_ID is the column in MEN Table.
Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.
It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\
I already wrote up the answer to this but it seems to have been deleted. The issue was that YUI added background-color:white
to the HTML element. I overwrote that and everything was easy to handle from there.
I had a similar issue that cropped up when using tight_layout
for a very large grid of plots (more than 200 subplots) and rendering in a jupyter notebook. I made a quick solution that always places your suptitle
at a certain distance above your top subplot:
import matplotlib.pyplot as plt
n_rows = 50
n_col = 4
fig, axs = plt.subplots(n_rows, n_cols)
#make plots ...
# define y position of suptitle to be ~20% of a row above the top row
y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
fig.suptitle('My Sup Title', y=y_title_pos)
For variably-sized subplots, you can still use this method to get the top of the topmost subplot, then manually define an additional amount to add to the suptitle.
Yesterday's date can be calculated as,
var prev_date = new Date();
prev_date.setDate(prev_date.getDate() - 1);
I suspect you haven't set up last_name
properly in the caller.
With the statement Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name)
this will only work if last_name
is a string, i.e.
Dim last_name as String
appears in the caller somewhere.
The reason for this is that VBA passes in variables by reference by default which means that the data types have to match exactly between caller and callee.
1) Force ByVal -- Change your function to pass variable ByVal: Public Function ProcessString(ByVal input_string As String) As String
, or
2) Dim varname -- put Dim last_name As String
in the caller before you use it.
(1) works because for ByVal
, a copy of input_string is taken when passing to the function which will coerce it into the correct data type. It also leads to better program stability since the function cannot modify the variable in the caller.
Slide animation can be applied to activity transitions by calling overridePendingTransition and passing animation resources for enter and exit activities.
Slide animations can be slid right, slide left, slide up and slide down.
Slide up
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale
android:duration="800"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
Slide down
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale
android:duration="800"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
overridePendingTransition(R.anim.slide_down, R.anim.slide_up);
See activity transition animation examples for more activity transition examples.
Found the simple official way after wading through the walls of text above that would make you think there is none.
Create a complete bundle with:
$ git bundle create <filename> --all
Restore it with:
$ git clone <filename> <folder>
This operation is atomic AFAIK. Check official docs for the gritty details.
Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.
in a Microsoft SQL Server you can use this:
declare @sql2 nvarchar(2000)
set @sql2 ='
use ?
if ( db_name(db_id()) not in (''master'',''tempdb'',''model'',''msdb'',''SSISDB'') )
begin
select
db_name() as db,
SS.name as schemaname,
SO.name tablename,
SC.name columnname,
ST.name type,
case when ST.name in (''nvarchar'', ''nchar'')
then convert(varchar(10), ( SC.max_length / 2 ))
when ST.name in (''char'', ''varchar'')
then convert(varchar(10), SC.max_length)
else null
end as length,
case when SC.is_nullable = 0 then ''No'' when SC.is_nullable = 1 then ''Yes'' else null end as nullable,
isnull(SC.column_id,0) as col_number
from sys.objects SO
join sys.schemas SS
on SS.schema_id = SO.schema_id
join sys.columns SC
on SO.object_id = SC.object_id
left join sys.types ST
on SC.user_type_id = ST.user_type_id and SC.system_type_id = ST.system_type_id
where SO.is_ms_shipped = 0
end
'
exec sp_msforeachdb @command1 = @sql2
this shows you all tables and columns ( and their definition ) from all userdefined databases.
I think you will need to edit the doxys file and set GENERATE_UML (something like that) to true. And you need to have dot/graphviz installed.