To spool from a BEGIN
END
block is pretty simple. For example if you need to spool result from two tables into a file, then just use the for loop
. Sample code is given below.
BEGIN
FOR x IN
(
SELECT COLUMN1,COLUMN2 FROM TABLE1
UNION ALL
SELECT COLUMN1,COLUMN2 FROM TABLEB
)
LOOP
dbms_output.put_line(x.COLUMN1 || '|' || x.COLUMN2);
END LOOP;
END;
/
There is the new open-source Nodeclipse project (as a Eclipse plugin or Enide Studio):
Nodeclipse became #1 in Eclipse Top 10 NEW Plugins for 2013. It uses a modified V8 debugger (from Google Chrome Developer Tools for Java).
Nodeclipse is free open-source software released at the start of every month.
Check out your TNS Names, this must not have spaces at the left side of the ALIAS
Best regards
Based on the @trashgod's comment, this is the simpliest way to calculate >distance:
double distance = Math.hypot(x1-x2, y1-y2);
From documentation of Math.hypot:Returns:
sqrt(x²+ y²)
without intermediate overflow or underflow.Bob
Below Bob's approved comment he said he couldn't explain what the
Math.hypot(x1-x2, y1-y2);
did. To explain a triangle has three sides. With two points you can find the length of those points based on the x,y
of each. Xa=0, Ya=0
If thinking in Cartesian coordinates that is (0,0)
and then Xb=5, Yb=9
Again, cartesian coordinates is (5,9)
. So if you were to plot those on a grid, the distance from from x to another x assuming they are on the same y axis is +5
. and the distance along the Y axis from one to another assuming they are on the same x-axis is +9
. (think number line) Thus one side of the triangle's length is 5, another side is 9. A hypotenuse is
(x^2) + (y^2) = Hypotenuse^2
which is the length of the remaining side of a triangle. Thus being quite the same as a standard distance formula where
Sqrt of (x1-x2)^2 + (y1-y2)^2 = distance
because if you do away with the sqrt on the lefthand side of the operation and instead make distance^2 then you still have to get the sqrt from the distance. So the distance formula is the Pythagorean theorem but in a way that teachers can call it something different to confuse people.
Just remove this line android:screenOrientation="portrait"
of activity in Manifiest.xml
That activity will get orientation from it's previous activity so no need to apply orientation which has <item name="android:windowIsTranslucent">true</item>
.
i had the same problem and was already using the code in the selected answer. this link was the answer for me; maybe for others also.
Just add this line to your php.ini if you are using XAMPP etc. also check if it is already there just remove ; from front of it
extension= php_mysqli.dll
and stop and start apache and MySQL it will work.
Probably the jstl libraries are missing from your classpath/not accessible by tomcat.
You need to add at least the following jar files in your WEB-INF/lib
directory:
If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1")
to get the POST (or PUT) data value.
If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:
@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
//do stuff with valueOne variable here
}
I would recommend you work out the minimum permission set that your service really needs and use that, rather than the far too privileged Local System context. For example, Local Service.
Interactive services no longer work - or at least, no longer show UI - on Windows Vista and Windows Server 2008 due to session 0 isolation.
Aghhh... i was missing some code when i first tried the .submit function.....
This works:
$('#create-card-process.design').submit(function() {
var textStyleCSS = $("#cover-text").attr('style');
var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
$("#cover_text_css").val(textStyleCSS);
$("#cover_text_background_css").val(textbackgroundCSS);
});
Thanks for all the comments.
You always need to check for XACT_STATE()
, irrelevant of the XACT_ABORT
setting. I have an example of a template for stored procedures that need to handle transactions in the TRY/CATCH context at Exception handling and nested transactions:
create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(),
@message = ERROR_MESSAGE(),
@xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
end catch
end
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime
x = [
datetime.datetime(2011, 1, 4, 0, 0),
datetime.datetime(2011, 1, 5, 0, 0),
datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)
y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]
ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()
plt.show()
I don't know what's the "y values are also overlapping" means, does the following code solve your problem?
ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)
plt.show()
In my case, I deleted the Previous Project & created a new project with different name, when i was building the Project it shows me the same error.
I just edited the Project Name in csproj file of the Project & it Worked...!
Try this and let me know if it does not work on your end:
<input type="checkbox" name='agree' ref={input => this.inputElement = input}/>
<div onClick={() => this.inputElement.click()}>Click</div>
Clicking on the div
should simulate a click on the input
element
You don't need to go to 64-bit to see something like this. Consider int32_t
on common 32-bit platforms. It might be typedef
'ed as int
or as a long
, but obviously only one of the two at a time. int
and long
are of course distinct types.
It's not hard to see that there is no workaround which makes int == int32_t == long
on 32-bit systems. For the same reason, there's no way to make long == int64_t == long long
on 64-bit systems.
If you could, the possible consequences would be rather painful for code that overloaded foo(int)
, foo(long)
and foo(long long)
- suddenly they'd have two definitions for the same overload?!
The correct solution is that your template code usually should not be relying on a precise type, but on the properties of that type. The whole same_type
logic could still be OK for specific cases:
long foo(long x);
std::tr1::disable_if(same_type(int64_t, long), int64_t)::type foo(int64_t);
I.e., the overload foo(int64_t)
is not defined when it's exactly the same as foo(long)
.
[edit] With C++11, we now have a standard way to write this:
long foo(long x);
std::enable_if<!std::is_same<int64_t, long>::value, int64_t>::type foo(int64_t);
[edit] Or C++20
long foo(long x);
int64_t foo(int64_t) requires (!std::is_same_v<int64_t, long>);
Try this:
decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together
It can be writen shorter, but this is more descriptive.
EDIT: Short way:
decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));
How about System.currentTimeMillis()
?
From the JavaDoc:
Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC
Java 8 introduces the java.time
framework, particularly the Instant
class which "...models a ... point on the time-line...":
long now = Instant.now().toEpochMilli();
Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)
Cheers,
I had exactly the same problem lately, and I installed Wireshark (it is a network monitoring tool). You can see everything with this, except encrypted traffic (HTTPS).
Pass your comma-separated string into this function and it will return an array, and if a comma-separated string is not found then it will return null.
function splitTheString(CommaSepStr) {
var ResultArray = null;
// Check if the string is null or so.
if (CommaSepStr!= null) {
var SplitChars = ',';
// Check if the string has comma of not will go to else
if (CommaSepStr.indexOf(SplitChars) >= 0) {
ResultArray = CommaSepStr.split(SplitChars);
}
else {
// The string has only one value, and we can also check
// the length of the string or time and cross-check too.
ResultArray = [CommaSepStr];
}
}
return ResultArray;
}
Make a new Image
var img = new Image();
Set the src
img.src = your_src
Get the width
and the height
//img.width
//img.height
I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.
I guess you should differentiate the target (before and after Oreo)
int LAYOUT_FLAG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
LAYOUT_FLAG,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
My solution is in the DataContext instance (or ViewModel if using MVVM). I add a property that returns true if the Not Null condition I want is met.
Public ReadOnly Property IsSomeFieldNull() As Boolean
Get
Return If(SomeField is Null, True, False)
End Get
End Property
and bind the DataTrigger to the above property. Note: In VB.NET be sure to use the operator If and NOT the IIf function, which doesn't work with Null objects. Then the XAML is:
<DataTrigger Binding="{Binding IsSomeFieldNull}" Value="False">
<Setter Property="TextBlock.Text" Value="It's NOT NULL Baby!" />
</DataTrigger>
So I was running 300 PHP processes simulatenously and was getting a rate of between 60 - 90 per second (my process involves 3x queries). I upped it to 400 and this fell to about 40-50 per second. I dropped it to 200 and am back to between 60 and 90!
So my advice to anyone with this problem is experiment with running less than more and see if it improves. There will be less memory and CPU being used so the processes that do run will have greater ability and the speed may improve.
void input_from_key_board(int &ri, int &ci)
{
char ch = 'x';
if (_kbhit())
{
ch = _getch();
if (ch == -32)
{
ch = _getch();
switch (ch)
{
case 72: { ri--; break; }
case 80: { ri++; break; }
case 77: { ci++; break; }
case 75: { ci--; break; }
}
}
else if (ch == '\r'){ gotoRowCol(ri++, ci -= ci); }
else if (ch == '\t'){ gotoRowCol(ri, ci += 5); }
else if (ch == 27) { system("ipconfig"); }
else if (ch == 8){ cout << " "; gotoRowCol(ri, --ci); if (ci <= 0)gotoRowCol(ri--, ci); }
else { cout << ch; gotoRowCol(ri, ci++); }
gotoRowCol(ri, ci);
}
}
Another method for Swift (without using NSString):
let percentage = 33.3333
let text = String.localizedStringWithFormat("%.02f %@", percentage, "%")
P.S. this solution is not working with CGFloat type only tested with Float
& Double
I faced same issue in android studio 3.2.1, solved the issue by setting git path in System Environment variable
C:\Program Files\Git\bin\,C:\Program Files\Git\bin\
And I imported the project once again and solved the issue!!!
Note : Check your android studio git settings has properly set the correct path to git.exe
Yes, rightly said. Hive does not support UPDATE option. But the following alternative could be used to achieve the result:
Update records in a partitioned Hive table
:
Join the two tables (main & staging tables) using a LEFT OUTER JOIN
operation as below:
insert overwrite table main_table partition (c,d)
select t2.a, t2.b, t2.c,t2.d from staging_table t2 left outer join main_table t1 on t1.a=t2.a;
In the above example, the main_table
& the staging_table
are partitioned using the (c,d)
keys. The tables are joined via a LEFT OUTER JOIN
and the result is used to OVERWRITE
the partitions in the main_table
.
A similar approach could be used in the case of un-partitioned Hive table
UPDATE
operations too.
function convert(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth()+1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
hours = ("0" + date.getHours()).slice(-2);
minutes = ("0" + date.getMinutes()).slice(-2);
return [ date.getFullYear(), mnth, day, hours, minutes ].join("-");
}
I used this efficiently in angular because i was losing two hours on updating a $scope.STARTevent, and $scope.ENDevent, IN console.log was fine, however saving to mYsql dropped two hours.
var whatSTART = $scope.STARTevent;
whatSTART = convert(whatever);
THIS WILL ALSO work for END
I switched to a different USB port and it suddenly got recognized...
I solved the problem by enabling the mod_autoindex
from Apache. It was disabled by default.
sudo a2enmod autoindex
I was also facing this issue. You might have more than JAVA versions installed. Make sure that JAVA_HOME variable is set to the correct version.
What does position four represent, the one that has 'false' as an value? Shouldn't that be false, (i.e. without quotes?). It's possible that earlier versions of IE would coerce the string to a boolean, but newer ones don't.
As others have said, in general you use @synthesize to have the compiler generate the getters and/ or settings for you, and @dynamic if you are going to write them yourself.
There is another subtlety not yet mentioned: @synthesize will let you provide an implementation yourself, of either a getter or a setter. This is useful if you only want to implement the getter for some extra logic, but let the compiler generate the setter (which, for objects, is usually a bit more complex to write yourself).
However, if you do write an implementation for a @synthesize'd accessor it must still be backed by a real field (e.g., if you write -(int) getFoo();
you must have an int foo;
field). If the value is being produce by something else (e.g. calculated from other fields) then you have to use @dynamic.
Key differences:
C++ is a general-purpose programming language, but is developed from the originally C programming language. It was developed by Bjarne Stroustrup at Bell Labs starting in 1979. C++ was originally named C with Classes. It was renamed C++ in 1983.
Visual C++, on the other hand, is not a programming language at all. It is in fact a development environment. It is an “integrated development environment (IDE) product from Microsoft for the C, C++, and C++/CLI programming languages.” Microsoft Visual C++, also known as MSVC or VC++, is sold as part of the Microsoft Visual Studio app.
For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient
. Make sure that you import javax.persistence.transient
and not some other package.
<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>
You have few problems with your code like using .
for concatenation
Try this -
$(function () {
$('input').on('click', function () {
var Status = $(this).val();
$.ajax({
url: 'Ajax/StatusUpdate.php',
data: {
text: $("textarea[name=Status]").val(),
Status: Status
},
dataType : 'json'
});
});
});
All of them seemed good candidates:
/etc/my.cnf
/etc/mysql/my.cnf
/var/lib/mysql/my.cnf
...
in many cases you could simply check system process list using ps:
server ~ # ps ax | grep '[m]ysqld'
Output
10801 ? Ssl 0:27 /usr/sbin/mysqld --defaults-file=/etc/mysql/my.cnf --basedir=/usr --datadir=/var/lib/mysql --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock
Or
which mysqld
/usr/sbin/mysqld
Then
/usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"
/etc/mysql/my.cnf ~/.my.cnf /usr/etc/my.cnf
You must write that function body outside the ready();
because ready is used to call a function or to bind a function with binding id like this.
$(document).ready(function() {
$("Some id/class name").click(function(){
alert("i'm in");
});
});
but you can't do this if you are calling "showAmount" function onchange/onclick event
$(document).ready(function() {
function showAmount(value){
alert(value);
}
});
You have to write "showAmount" outside the ready();
function showAmount(value){
alert(value);//will be called on event it is bind with
}
$(document).ready(function() {
alert("will display on page load")
});
you can use the following command line:
java -jar -Dspring.profiles.active=[yourProfileName] target/[yourJar].jar
app.component.html
<select [(ngModel)]='nrSelect' class='form-control'>
<option value='47'>47</option>
<option value='46'>46</option>
<option value='45'>45</option>
</select>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
nrSelect = 47
}
You can always run this:
java -cp HelloWorld.jar HelloWorld
-cp HelloWorld.jar
adds the jar to the classpath, then HelloWorld
runs the class you wrote.
To create a runnable jar with a main class with no package, add Class-Path: .
to the manifest:
Manifest-Version: 1.0
Class-Path: .
Main-Class: HelloWorld
I would advise using a package
to give your class its own namespace. E.g.
package com.stackoverflow.user.blrp;
public class HelloWorld {
...
}
A new clean way might be to write your xml like so:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE rootElement>
<rootElement>
....
</rootElement>
The above works in Eclipse Juno+
<div id="about">About Snakelane</div>
<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">
<script>
var about;
function init() {
about = document.getElementById("about");
about.style.color = 'blue';
}
I think you are asking for something like the code below:
public interface A
{
void foo()
throws AException;
}
public class B
implements A
{
@Overrides
public void foo()
throws AException,
BException
{
}
}
This will not work unless BException is a subclass of AException. When you override a method you must conform to the signature that the parent provides, and exceptions are part of the signature.
The solution is to declare the the interface also throws a BException.
The reason for this is you do not want code like:
public class Main
{
public static void main(final String[] argv)
{
A a;
a = new B();
try
{
a.foo();
}
catch(final AException ex)
{
}
// compiler will not let you write a catch BException if the A interface
// doesn't say that it is thrown.
}
}
What would happen if B::foo threw a BException? The program would have to exit as there could be no catch for it. To avoid situations like this child classes cannot alter the types of exceptions thrown (except that they can remove exceptions from the list).
Actually Apache is a web server and Tomcat is an application server. When as HTTP request comes to web server. Then static contents send back to browser by web server. Is there and logic do to done, then that request send to the application server. after processing the logic then response send to web server and send to the client.
Another option is to use "localStorage". You can easealy request the value with javascript in another page.
On the first page, you use the following snippet of javascript code to set the localStorage:
<script>
localStorage.setItem("serialNumber", "abc123def456");
</script>
On the second page, you can retrieve the value with the following javascript code snippet:
<script>
console.log(localStorage.getItem("serialNumber"));
</script>
On Google Chrome You can vizualize the values pressing F12 > Application > Local Storage.
Source: https://www.w3schools.com/jsref/prop_win_localstorage.asp
Anytime you have a question about a particular function in PHP, the easiest way to get quick answers is by visiting php.net, which has great documentation on all of the language's capabilities.
Looking up a function is easy, just visit http://php.net/<function name>
and it will forward you to the appropriate place. For the date function, we'll visit http://php.net/date.
We immediately learn a couple things about this function by examining its signature:
string date ( string $format [, int $timestamp = time() ] )
First, it returns a string. That's what the first string
in the above code means. Secondly, the first parameter is expected to be a string containing the format. There is an optional second parameter for passing in your own timestamp (to construct strings from some time other than now).
date("d-m-Y") // produces something like 03-12-2012
In this code, d
represents the day of the month (with a leading 0 is necessary). m
represents the month, again with a leading zero if necessary. And Y
represents the full 4-digit year. All of these are documented in the aforementioned link.
To satisfy your request of getting the hours, minutes, and seconds, we need to give a quick look at the documentation to see which characters represents those particular units of time. When we do that, we find the following:
h 12-hour format of an hour with leading zeros 01 through 12
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
With this in mind, we can no create a new format string:
date("d-m-Y h:i:s"); // produces something like 03-12-2012 03:29:13
Hope this is helpful, and I hope you find the documentation has benefiting to your development as I have to mine.
Updating the accepted answer (can't comment yet). As of 1/12/16 using the demo jsfiddle in chrome, switch-immediate is the fastest solution.
Results: Time resolution: 1.33
25ms "if-immediate" 150878146
29ms "if-indirect" 150878146
24ms "switch-immediate" 150878146
128ms "switch-range" 150878146
45ms "switch-range2" 150878146
47ms "switch-indirect-array" 150878146
43ms "array-linear-switch" 150878146
72ms "array-binary-switch" 150878146
Finished
1.04 ( 25ms) if-immediate
1.21 ( 29ms) if-indirect
1.00 ( 24ms) switch-immediate
5.33 ( 128ms) switch-range
1.88 ( 45ms) switch-range2
1.96 ( 47ms) switch-indirect-array
1.79 ( 43ms) array-linear-switch
3.00 ( 72ms) array-binary-switch
What do you mean by impacts? Content will flow around a float. That's how they work.
If you want it to appear above your design, try setting:
z-index: 10;
position: absolute;
right: 0;
top: 0;
Something like:
find /path/ -type f -exec stat \{} --printf="%y\n" \; |
sort -n -r |
head -n 1
Explanation:
The way it's often done is as follows:
I find that this pattern comes up pretty frequently.
What's interesting about this method is that it allows one to insert N
elements into an empty array one-by-one in amortized O(N)
time without knowing N
in advance.
this should do it.
my $dir = "bla/bla/upload";
opendir DIR,$dir;
my @dir = readdir(DIR);
close DIR;
foreach(@dir){
if (-f $dir . "/" . $_ ){
print $_," : file\n";
}elsif(-d $dir . "/" . $_){
print $_," : folder\n";
}else{
print $_," : other\n";
}
}
You can see a detailed description here.
ini_set('display_errors', 1);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
Changelog
5.4.0 E_STRICT became part of E_ALL
5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.
5.2.0 E_RECOVERABLE_ERROR introduced.
5.0.0 E_STRICT introduced (not part of E_ALL).
mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
myRoundedList = [round(x,2) for x in mylist]
# [0.3, 0.5, 0.2]
It's all in your things.size()
type. It isn't int
, but size_t
(it exists in C++, not in C) which equals to some "usual" unsigned type, i.e. unsigned int
for x86_32.
Operator "less" (<) cannot be applied to two operands of different sign. There's just no such opcodes, and standard doesn't specify, whether compiler can make implicit sign conversion. So it just treats signed number as unsigned and emits that warning.
It would be correct to write it like
for (size_t i = 0; i < things.size(); ++i) { /**/ }
or even faster
for (size_t i = 0, ilen = things.size(); i < ilen; ++i) { /**/ }
I managed to get it working by following Option 2 on the Windows installation instructions on the following page: https://github.com/nodejs/node-gyp.
I had to close the current command line interface and reopen it after doing the installation on another one logged in as Administrator.
I'm using Sublime Text 3.2.1, a 4k display and a Mac. Tab titles and the sidebar are difficult to read with default ST3 settings. I used the menus Sublime Text -> Preferences -> Settings which opens two files: Preferences.sublime-settings--Default and Preferences.sublime-settings--User.
You can only edit the User file. The Default file is useful for showing what variables you can set. Around line 350 of the Default file are two variables as shown below:
// Magnifies the entire user interface. Sublime Text must be restarted for
// this to take effect.
"ui_scale": 1.0,
// Linux only. Sets the app DPI scale - a decimal number such as 1.0, 1.5,
// 2.0, etc. A value of 0 auto-detects the DPI scale. Sublime Text must be
// restarted for this to take effect.
"dpi_scale": 0,
"dpi_scale": 3.0
did nothing on my Mac "ui_scale": 1.5
worked well. The following is my User file.
{
"dictionary": "Packages/Language - English/en_US.dic",
"font_size": 17,
"ignored_packages":
[
"Vintage"
],
"theme": "Default.sublime-theme",
"ui_scale": 1.5
}
A rather separable way of doing this is to use
import tensorflow as tf
from keras import backend as K
num_cores = 4
if GPU:
num_GPU = 1
num_CPU = 1
if CPU:
num_CPU = 1
num_GPU = 0
config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
inter_op_parallelism_threads=num_cores,
allow_soft_placement=True,
device_count = {'CPU' : num_CPU,
'GPU' : num_GPU}
)
session = tf.Session(config=config)
K.set_session(session)
Here, with booleans
GPU
and CPU
, we indicate whether we would like to run our code with the GPU or CPU by rigidly defining the number of GPUs and CPUs the Tensorflow session is allowed to access. The variables num_GPU
and num_CPU
define this value. num_cores
then sets the number of CPU cores available for usage via intra_op_parallelism_threads
and inter_op_parallelism_threads
.
The intra_op_parallelism_threads
variable dictates the number of threads a parallel operation in a single node in the computation graph is allowed to use (intra). While the inter_ops_parallelism_threads
variable defines the number of threads accessible for parallel operations across the nodes of the computation graph (inter).
allow_soft_placement
allows for operations to be run on the CPU if any of the following criterion are met:
there is no GPU implementation for the operation
there are no GPU devices known or registered
there is a need to co-locate with other inputs from the CPU
All of this is executed in the constructor of my class before any other operations, and is completely separable from any model or other code I use.
Note: This requires tensorflow-gpu
and cuda
/cudnn
to be installed because the option is given to use a GPU.
Refs:
instead of
mySelect.toSource()
use
mySelect.val()
I got the same error. it was because I was accessing the https port using http.. The issue solved when I changed http to https.
Use strlen
to get the length of a null-terminated string.
sizeof
returns the length of the array not the string. If it's a pointer (char *s
), not an array (char s[]
), it won't work, since it will return the size of the pointer (usually 4 bytes on 32-bit systems). I believe an array will be passed or returned as a pointer, so you'd lose the ability to use sizeof
to check the size of the array.
So, only if the string spans the entire array (e.g. char s[] = "stuff"
), would using sizeof
for a statically defined array return what you want (and be faster as it wouldn't need to loop through to find the null-terminator) (if the last character is a null-terminator, you will need to subtract 1). If it doesn't span the entire array, it won't return what you want.
An alternative to all this is actually storing the size of the string.
As an extension to Mark Rajcok's second solution
Assign a new array to rawLapsData whenever you make any changes to the array contents. Then ngOnChanges() will be called because the array (reference) will appear as a change
you can clone the contents of the array like this:
rawLapsData = rawLapsData.slice(0);
I am mentioning this because
rawLapsData = Object.assign({}, rawLapsData);
didn't work for me. I hope this helps.
With Hibernate 5.2, you can now force the UTC time zone using the following configuration property:
<property name="hibernate.jdbc.time_zone" value="UTC"/>
v
has 10
element, the index starts from 0
to 9
.
for(int j=10;j>0;--j)
{
cout<<v[j]; // v[10] out of range
}
you should update for
loop to
for(int j=9; j>=0; --j)
// ^^^^^^^^^^
{
cout<<v[j]; // out of range
}
Or use reverse iterator to print element in reverse order
for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
std::cout << *ri << std::endl;
}
If you get this message in RStudio, clicking the 'broomstick' figure "Clear All Plots" in Plots tab and try plot() again.
Moreover Execute the command
graphics.off()
I have done exactly this with an ICustomTypeDescriptor interface and a Dictionary.
Implementing ICustomTypeDescriptor for dynamic properties:
I have recently had a requirement to bind a grid view to a record object that could have any number of properties that can be added and removed at runtime. This was to allow a user to add a new column to a result set to enter an additional set of data.
This can be achieved by having each data 'row' as a dictionary with the key being the property name and the value being a string or a class that can store the value of the property for the specified row. Of course having a List of Dictionary objects will not be able to be bound to a grid. This is where the ICustomTypeDescriptor comes in.
By creating a wrapper class for the Dictionary and making it adhere to the ICustomTypeDescriptor interface the behaviour for returning properties for an object can be overridden.
Take a look at the implementation of the data 'row' class below:
/// <summary>
/// Class to manage test result row data functions
/// </summary>
public class TestResultRowWrapper : Dictionary<string, TestResultValue>, ICustomTypeDescriptor
{
//- METHODS -----------------------------------------------------------------------------------------------------------------
#region Methods
/// <summary>
/// Gets the Attributes for the object
/// </summary>
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return new AttributeCollection(null);
}
/// <summary>
/// Gets the Class name
/// </summary>
string ICustomTypeDescriptor.GetClassName()
{
return null;
}
/// <summary>
/// Gets the component Name
/// </summary>
string ICustomTypeDescriptor.GetComponentName()
{
return null;
}
/// <summary>
/// Gets the Type Converter
/// </summary>
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return null;
}
/// <summary>
/// Gets the Default Event
/// </summary>
/// <returns></returns>
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return null;
}
/// <summary>
/// Gets the Default Property
/// </summary>
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return null;
}
/// <summary>
/// Gets the Editor
/// </summary>
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return null;
}
/// <summary>
/// Gets the Events
/// </summary>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return new EventDescriptorCollection(null);
}
/// <summary>
/// Gets the events
/// </summary>
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return new EventDescriptorCollection(null);
}
/// <summary>
/// Gets the properties
/// </summary>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
List<propertydescriptor> properties = new List<propertydescriptor>();
//Add property descriptors for each entry in the dictionary
foreach (string key in this.Keys)
{
properties.Add(new TestResultPropertyDescriptor(key));
}
//Get properties also belonging to this class also
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this.GetType(), attributes);
foreach (PropertyDescriptor oPropertyDescriptor in pdc)
{
properties.Add(oPropertyDescriptor);
}
return new PropertyDescriptorCollection(properties.ToArray());
}
/// <summary>
/// gets the Properties
/// </summary>
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor)this).GetProperties(null);
}
/// <summary>
/// Gets the property owner
/// </summary>
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion Methods
//---------------------------------------------------------------------------------------------------------------------------
}
Note: In the GetProperties method I Could Cache the PropertyDescriptors once read for performance but as I'm adding and removing columns at runtime I always want them rebuilt
You will also notice in the GetProperties method that the Property Descriptors added for the dictionary entries are of type TestResultPropertyDescriptor. This is a custom Property Descriptor class that manages how properties are set and retrieved. Take a look at the implementation below:
/// <summary>
/// Property Descriptor for Test Result Row Wrapper
/// </summary>
public class TestResultPropertyDescriptor : PropertyDescriptor
{
//- PROPERTIES --------------------------------------------------------------------------------------------------------------
#region Properties
/// <summary>
/// Component Type
/// </summary>
public override Type ComponentType
{
get { return typeof(Dictionary<string, TestResultValue>); }
}
/// <summary>
/// Gets whether its read only
/// </summary>
public override bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets the Property Type
/// </summary>
public override Type PropertyType
{
get { return typeof(string); }
}
#endregion Properties
//- CONSTRUCTOR -------------------------------------------------------------------------------------------------------------
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public TestResultPropertyDescriptor(string key)
: base(key, null)
{
}
#endregion Constructor
//- METHODS -----------------------------------------------------------------------------------------------------------------
#region Methods
/// <summary>
/// Can Reset Value
/// </summary>
public override bool CanResetValue(object component)
{
return true;
}
/// <summary>
/// Gets the Value
/// </summary>
public override object GetValue(object component)
{
return ((Dictionary<string, TestResultValue>)component)[base.Name].Value;
}
/// <summary>
/// Resets the Value
/// </summary>
public override void ResetValue(object component)
{
((Dictionary<string, TestResultValue>)component)[base.Name].Value = string.Empty;
}
/// <summary>
/// Sets the value
/// </summary>
public override void SetValue(object component, object value)
{
((Dictionary<string, TestResultValue>)component)[base.Name].Value = value.ToString();
}
/// <summary>
/// Gets whether the value should be serialized
/// </summary>
public override bool ShouldSerializeValue(object component)
{
return false;
}
#endregion Methods
//---------------------------------------------------------------------------------------------------------------------------
}
The main properties to look at on this class are GetValue and SetValue. Here you can see the component being casted as a dictionary and the value of the key inside it being Set or retrieved. Its important that the dictionary in this class is the same type in the Row wrapper class otherwise the cast will fail. When the descriptor is created the key (property name) is passed in and is used to query the dictionary to get the correct value.
Taken from my blog at:
for XML line width, update preferences > XML > XML Files > Editor > Line width
Check this below code, it works
#define MAX_BYTE_RANGE 255
template <typename T>
class string
{
public:
typedef char *pointer;
typedef const char *const_pointer;
typedef __gnu_cxx::__normal_iterator<pointer, string> iterator;
typedef __gnu_cxx::__normal_iterator<const_pointer, string> const_iterator;
string() : length(0)
{
}
size_t size() const
{
return length;
}
void operator=(const_pointer value)
{
if (value == nullptr)
throw std::invalid_argument("value cannot be null");
auto count = strlen(value);
if (count > 0)
_M_copy(value, count);
}
void operator=(const string &value)
{
if (value.length != 0)
_M_copy(value.buf, value.length);
}
iterator begin()
{
return iterator(buf);
}
iterator end()
{
return iterator(buf + length);
}
const_iterator begin() const
{
return const_iterator(buf);
}
const_iterator end() const
{
return const_iterator(buf + length);
}
const_pointer c_str() const
{
return buf;
}
~string()
{
}
private:
unsigned char length;
T buf[MAX_BYTE_RANGE];
void _M_copy(const_pointer value, size_t count)
{
memcpy(buf, value, count);
length = count;
}
};
Store a timestamp in the session
<?php
$user = $_POST['user_name'];
$pass = $_POST['user_pass'];
require ('db_connection.php');
// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($user), mysql_real_escape_string($pass));
if( mysql_num_rows( $result ) > 0)
{
$array = mysql_fetch_assoc($result);
session_start();
$_SESSION['user_id'] = $user;
$_SESSION['login_time'] = time();
header("Location:loggedin.php");
}
else
{
header("Location:login.php");
}
?>
Now, Check if the timestamp is within the allowed time window (1800 seconds is 30 minutes)
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800)
{
header("Location:login.php");
}
else
{
// uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login
//$_SESSION['login_time'] = time();
echo ( "this session is ". $_SESSION['user_id'] );
//show rest of the page and all other content
}
?>
The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:
http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http
810 style = "body { background-color: white; color: black; font-family: "
811 "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812 "hr { border: 0; border-bottom: 1px dashed; }\n";
E.g., try this:
font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;
I used app.all
The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches.
In my case, I'm using confit for configuration management,
app.all('*', function (req, res, next) {
confit(basedir).create(function (err, config) {
if (err) {
throw new Error('Failed to load configuration ', err);
}
app.set('config', config);
next();
});
});
In routes, you simply do req.app.get('config').get('cookie');
Use dispatch group
dispatchGroup.enter()
FirstOperation(completion: { _ in
dispatchGroup.leave()
})
dispatchGroup.enter()
SecondOperation(completion: { _ in
dispatchGroup.leave()
})
dispatchGroup.wait() // Waits here on this thread until the two operations complete executing.
Unchecked all Device orientation and checked only "Requires full screen". Its working properly
git remote show origin
Enter passphrase for key ....ssh/id_rsa:
* remote origin
Fetch URL: [email protected]:mamaque/systems.git
Push URL: [email protected]:mamaque/systems.git
HEAD branch: main
Remote branch:
main tracked
Local ref configured for 'git push':
main pushes to main (up-to-date)
Both are up to date
main pushes to main (fast-forwardable)
Remote can be updated with Local
main pushes to main (local out of date)
Local can be update with Remote
I upgraded to my Git for Windows to latest (2.30.0) 64-bit and it works fine now. get the latest from the url https://git-scm.com/download/win and run the commands below to verify. $ git --version $ git version 2.30.0.windows.1
Turns out for me that SET NOCOUNT ON
was set in the stored procedure script (by default on SQL Server Management Studio) and SqlCommand.ExecuteNonQuery();
always returned -1.
I just set it off: SET NOCOUNT OFF
without needing to use @@ROWCOUNT
.
More details found here : SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete
Your program is still running. You have to kill it by closing the command line window. If you press control alt delete, task manager, process`s (kill the ones that match your filename).
#include <stdio.h>
#include <string.h>
int main(void){
char word[17], outword[33];//17:16+1, 33:16*2+1
int i, len;
printf("Intro word:");
fgets(word, sizeof(word), stdin);
len = strlen(word);
if(word[len-1]=='\n')
word[--len] = '\0';
for(i = 0; i<len; i++){
sprintf(outword+i*2, "%02X", word[i]);
}
printf("%s\n", outword);
return 0;
}
select TO_CHAR(TRUNC(SYSDATE)+(to_date( '31-MAY-2012 12:25', 'DD-MON-YYYY HH24:MI')
- to_date( '31-MAY-2012 10:37', 'DD-MON-YYYY HH24:MI')),
'HH24:MI:SS') from dual
-- result : 01:48:00
OK it's not quite what the OP asked, but it's what I wanted to do :-)
swift 4:
let username = "username"
let password = "password"
let loginString = "\(username):\(password)"
guard let loginData = loginString.data(using: String.Encoding.utf8) else {
return
}
let base64LoginString = loginData.base64EncodedString()
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
You should declare toString()
and valueOf()
method in enum
.
import java.io.Serializable;
public enum Gesture implements Serializable {
ROCK,PAPER,SCISSORS;
public String toString(){
switch(this){
case ROCK :
return "Rock";
case PAPER :
return "Paper";
case SCISSORS :
return "Scissors";
}
return null;
}
public static Gesture valueOf(Class<Gesture> enumType, String value){
if(value.equalsIgnoreCase(ROCK.toString()))
return Gesture.ROCK;
else if(value.equalsIgnoreCase(PAPER.toString()))
return Gesture.PAPER;
else if(value.equalsIgnoreCase(SCISSORS.toString()))
return Gesture.SCISSORS;
else
return null;
}
}
Datanewolf's code is ALMOST right. I had to reverse both the winding and the normals to make it work properly with the fixed pipeline. The below works correctly with cull on or off for me:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = -x;
*n++ = -y;
*n++ = -z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings-1; r++)
for(s = 0; s < sectors-1; s++) {
/*
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
*/
*i++ = (r+1) * sectors + s;
*i++ = (r+1) * sectors + (s+1);
*i++ = r * sectors + (s+1);
*i++ = r * sectors + s;
}
Edit: There was a question on how to draw this... in my code I encapsulate these values in a G3DModel class. This is my code to setup the frame, draw the model, and end it:
void GraphicsProvider3DPriv::BeginFrame()const{
int win_width;
int win_height;// framework of choice here
glfwGetWindowSize(window, &win_width, &win_height); // retrieve window
float const win_aspect = (float)win_width / (float)win_height;
// set lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
GLfloat lightpos[] = {0, 0.0, 0, 0.};
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
GLfloat lmodel_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
// set up world transform
glClearColor(0.f, 0.f, 0.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT|GL_ACCUM_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
}
void GraphicsProvider3DPriv::DrawModel(const G3DModel* model, const Transform3D transform)const{
G3DModelPriv* privModel = (G3DModelPriv *)model;
glPushMatrix();
glLoadMatrixf(transform.GetOGLData());
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &privModel->vertices[0]);
glNormalPointer(GL_FLOAT, 0, &privModel->normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &privModel->texcoords[0]);
glEnable(GL_TEXTURE_2D);
//glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, privModel->texname);
glDrawElements(GL_QUADS, privModel->indices.size(), GL_UNSIGNED_SHORT, &privModel->indices[0]);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
void GraphicsProvider3DPriv::EndFrame()const{
/* Swap front and back buffers */
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
glDisable(GL_CULL_FACE);
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
ResourceManager and .resx are bit messy.
You could use Lexical.Localization¹ which allows embedding default value and culture specific values into the code, and be expanded in external localization files for futher cultures (like .json or .resx).
public class MyClass
{
/// <summary>
/// Localization root for this class.
/// </summary>
static ILine localization = LineRoot.Global.Type<MyClass>();
/// <summary>
/// Localization key "Ok" with a default string, and couple of inlined strings for two cultures.
/// </summary>
static ILine ok = localization.Key("Success")
.Text("Success")
.fi("Onnistui")
.sv("Det funkar");
/// <summary>
/// Localization key "Error" with a default string, and couple of inlined ones for two cultures.
/// </summary>
static ILine error = localization.Key("Error")
.Format("Error (Code=0x{0:X8})")
.fi("Virhe (Koodi=0x{0:X8})")
.sv("Sönder (Kod=0x{0:X8})");
public void DoOk()
{
Console.WriteLine( ok );
}
public void DoError()
{
Console.WriteLine( error.Value(0x100) );
}
}
¹ (I'm maintainer of that library)
"Select your text, right click, then choose
Style Token
and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."
It should be default, but it might be hidden.
"It might be that something happened to your
contextMenu.xml
so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\
) if thecontextMenu.xml
is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at thecontextmenu.xml
itself - because you're allowed to change it to your own needs."
See this for more information
Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below
CREATE TABLE `table1` (
`col1` VARCHAR(50) NULL DEFAULT NULL
)
Now if you want to insert number from 1 to 50 in that table then use following stored procedure
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
DECLARE a INT Default 1 ;
simple_loop: LOOP
insert into table1 values(a);
SET a=a+1;
IF a=51 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
To call that stored procedure use
CALL `ABC`()
Since version v4.x you should use _.map
:
_.map(users, 'id'); // [12, 14, 16, 18]
this way it is corresponds to native Array.prototype.map method where you would write (ES2015 syntax):
users.map(user => user.id); // [12, 14, 16, 18]
Before v4.x you could use _.pluck
the same way:
_.pluck(users, 'id'); // [12, 14, 16, 18]
Check out the example from enable-cors.org:
In your ExpressJS app on node.js, do the following with your routes:
app.all('/', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.get('/', function(req, res, next) { // Handle the get for this route }); app.post('/', function(req, res, next) { // Handle the post for this route });
The first call (app.all
) should be made before all the other routes in your app (or at least the ones you want to be CORS enabled).
[Edit]
If you want the headers to show up for static files as well, try this (make sure it's before the call to use(express.static())
:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
I tested this with your code, and got the headers on assets from the public
directory:
var express = require('express')
, app = express.createServer();
app.configure(function () {
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(app.router);
});
app.configure('development', function () {
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function () {
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler());
});
app.listen(8888);
console.log('express running at http://localhost:%d', 8888);
You could, of course, package the function up into a module so you can do something like
// cors.js
module.exports = function() {
return function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
};
}
// server.js
cors = require('./cors');
app.use(cors());
Assuming you want an actual SQL Server MERGE
statement:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
ON target.webmeterID = source.webmeterID
AND target.DateTime = source.DateTime
WHEN MATCHED THEN
UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
INSERT (webmeterID, DateTime, kWh)
VALUES (source.webmeterID, source.DateTime, source.kWh);
If you also want to delete records in the target that aren't in the source:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
ON target.webmeterID = source.webmeterID
AND target.DateTime = source.DateTime
WHEN MATCHED THEN
UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
INSERT (webmeterID, DateTime, kWh)
VALUES (source.webmeterID, source.DateTime, source.kWh)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
Because this has become a bit more popular, I feel like I should expand this answer a bit with some caveats to be aware of.
First, there are several blogs which report concurrency issues with the MERGE
statement in older versions of SQL Server. I do not know if this issue has ever been addressed in later editions. Either way, this can largely be worked around by specifying the HOLDLOCK
or SERIALIZABLE
lock hint:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
[...]
You can also accomplish the same thing with more restrictive transaction isolation levels.
There are several other known issues with MERGE
. (Note that since Microsoft nuked Connect and didn't link issues in the old system to issues in the new system, these older issues are hard to track down. Thanks, Microsoft!) From what I can tell, most of them are not common problems or can be worked around with the same locking hints as above, but I haven't tested them.
As it is, even though I've never had any problems with the MERGE
statement myself, I always use the WITH (HOLDLOCK)
hint now, and I prefer to use the statement only in the most straightforward of cases.
use the fully qualified name instead of importing the class.
e.g.
//import java.util.Date; //delete this
//import my.own.Date;
class Test{
public static void main(String [] args){
// I want to choose my.own.Date here. How?
my.own.Date myDate = new my.own.Date();
// I want to choose util.Date here. How ?
java.util.Date javaDate = new java.util.Date();
}
}
The following is what I wrote and compiled in .NET.
double r0;
for (int i = 0; i < 1000; i++) {
r0 = i*i;
Console.WriteLine(r0);
}
for (int j = 0; j < 1000; j++) {
double r1 = j*j;
Console.WriteLine(r1);
}
This is what I get from .NET Reflector when CIL is rendered back into code.
for (int i = 0; i < 0x3e8; i++)
{
double r0 = i * i;
Console.WriteLine(r0);
}
for (int j = 0; j < 0x3e8; j++)
{
double r1 = j * j;
Console.WriteLine(r1);
}
So both look exactly same after compilation. In managed languages code is converted into CL/byte code and at time of execution it's converted into machine language. So in machine language a double may not even be created on the stack. It may just be a register as code reflect that it is a temporary variable for WriteLine
function. There are a whole set optimization rules just for loops. So the average guy shouldn't be worried about it, especially in managed languages. There are cases when you can optimize manage code, for example, if you have to concatenate a large number of strings using just string a; a+=anotherstring[i]
vs using StringBuilder
. There is very big difference in performance between both. There are a lot of such cases where the compiler cannot optimize your code, because it cannot figure out what is intended in a bigger scope. But it can pretty much optimize basic things for you.
With the solutions already discussed above the most reliable one is using Browsermob-Proxy
But while working with the remote grid machine, Browsermob-proxy isn't really helpful.
This is how I fixed the problem in my case. Hopefully, might be helpful for anyone with a similar setup.
How to download the Modheader? Link
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(C://Downloads//modheader//modheader.crx));
// Set the Desired capabilities
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
// Instantiate the chrome driver with capabilities
WebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
.
// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");
Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
Javascript
.
((Javascript)driver).executeScript(
"localStorage.setItem('profiles', JSON.stringify([{ title: 'Selenium', hideComment: true, appendMode: '',
headers: [
{enabled: true, name: 'token-1', value: 'value-1', comment: ''},
{enabled: true, name: 'token-2', value: 'value-2', comment: ''}
],
respHeaders: [],
filters: []
}]));");
Where token-1
, value-1
, token-2
, value-2
are the request headers and values that are to be added.
Now navigate to the required web-application.
driver.get("your-desired-website");
I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.
I'd declared a string and was formatting it for use with JQTree which requires curly braces ({}). You have to use doubled curly braces for it to be accepted as a properly formatted string:
string measurements = string.empty;
measurements += string.Format(@"
{{label: 'Measurement Name: {0}',
children: [
{{label: 'Measured Value: {1}'}},
{{label: 'Min: {2}'}},
{{label: 'Max: {3}'}},
{{label: 'Measured String: {4}'}},
{{label: 'Expected String: {5}'}},
]
}},",
drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
drv["Min"] == null ? "NULL" : drv["Min"],
drv["Max"] == null ? "NULL" : drv["Max"],
drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);
Hopefully this will help other folks who find this question but aren't parsing numerical data.
Use Application.GetSaveAsFilename()
in the same way that you used Application.GetOpenFilename()
impdp
exports the DDL of a dmp
backup to a file if you use the SQLFILE
parameter. For example, put this into a text file
impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt
Then check ddl_dump.txt
for the tablespaces, users, and schemas in the backup.
According to the documentation, this does not actually modify the database:
The SQL is not actually executed, and the target system remains unchanged.
At the Maven repo, there are samples to add the dependency in maven, sbt, gradle, etc.
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore/4.4.11
ie for Maven, you just create a project, for example
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4
then look at the pom.xml, then at the library at the dependencies xml element:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
</dependency>
For sbt do something like
sbt new scala/hello-world.g8
then edit the build.sbt to add the library
libraryDependencies += "org.apache.httpcomponents" % "httpcore" % "4.4.11"
<?php
$string = '`~!@#$%^&^&*()_+{}[]|\/;:"< >,.?-<h1>You .</h1><p> text</p>'."'";
$string=strip_tags($string,"");
$string = preg_replace('/[^A-Za-z0-9\s.\s-]/','',$string);
echo $string = str_replace( array( '-', '.' ), '', $string);
?>
You might also want to look at the subprocess
module, which was built to replace the whole family of Python popen
-type calls.
import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)
The advantage it has is that there is a ton of flexibility with how you invoke commands, where the standard in/out/error streams are connected, etc.
If someone has to steal your code, it likely means your business model is not working. What do I mean by that? For example, I buy your product and then I ask for support. You're too busy or believe my request is not valid and a waste of your time. I decode your product in order to support my relative business. Your product becomes more valuable to me and I prioritize my time in a way to resolve the business model for leveraging your product. I recode and re-brand your product and then go out and make the money that you decided to leave on the table. There are reasons for protecting code, but most likely you are looking at the problem from the wrong perspective. Of course you are. You're the "coder", and I'm the business man. ;-) Cheers!
ps. I'm also a developer. i.e. "coder"
Regarding whitehawk's accepted answer. I am just trying to add a bit hands on experience. Was just trying to add a comments, but SO complains it's too long.
Basically, without IE 9 installed, the registry switch FEATURE_BROWSER_EMULATION won't work AT ALL.
For example, my own experience today I was trying to get the .net webcontrol to work with IE10 mode because one html I am trying to render won't work with .netControl under VS2012, and not even work when I load the html to IE8 directly, still css won't render properly(even after I say allow blocked content). But I have tested the same html ok with IE10 on a friend's win 8 machine. That's why I am trying to set the .net webControl to IE 10 mode but just keeps failing...
Now I figured this is bcos my win 7 machine only have IE8 installed, so regardless which value I set to the FEATURE_BROWSER_EMULATION switch(value to IE9, IE10 IE11), it just won't work AT ALL !
Then I downloaded and installed IE 10 on my win 7 machine. Still it won't work, then I added the FEATURE_BROWSER_EMULATION, it started working !
Also I noticed regardless which value I set , even set it to value 0 by default, the webControl is still using IE 10 mode which still works for me.
So to summarise, If you have IE X installed but you want your .Net webControl to work under IE (X+N) N>0 modo, TWO things you need to do:
Go to MS website & download and install IE (X+N) on your machine, you will need to reboot after installation.
apply whitehawk's answer.
Basically: To control the value of this feature by using the registry, add the name of your executable file to the following setting and set the value to match the desired setting.
HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER)
SOFTWARE
Microsoft
Internet Explorer
Main
FeatureControl
FEATURE_BROWSER_EMULATION
contoso.exe = (DWORD) 00009000
Windows Internet Explorer 8 and later. The FEATURE_BROWSER_EMULATION feature defines the default emulation mode for Internet Explorer and supports the following values.
Value Description
11001 (0x2AF9 Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.
11000 (0x2AF8) IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.
10001 (0x2711) Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.
10000 (0x02710) Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.
9999 (0x270F) Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
9000 (0x2328) Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.
Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
8888 (0x22B8) Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
8000 (0x1F40) Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8 Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
7000 (0x1B58) Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.
Full ref here
Sometimes a BEFORE
trigger can be replaced with an AFTER
one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF
trigger one, as @marc_s has suggested in his comment.
Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE
trigger and an INSTEAD OF
one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF
trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE
trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.
But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW
. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.
So, it's really two things to solve then:
replace the BEFORE
functionality;
replace the FOR EACH ROW
functionality.
My attempt at solving these is below:
CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
DECLARE @new_super TABLE (
super_id int
);
INSERT INTO super (subtype_discriminator)
OUTPUT INSERTED.super_id INTO @new_super (super_id)
SELECT 'SUB1' FROM INSERTED;
INSERT INTO sub (super_id)
SELECT super_id FROM @new_super;
END;
This is how the above works:
The same number of rows as being inserted into sub1
is first added to super
. The generated super_id
values are stored in a temporary storage (a table variable called @new_super
).
The newly inserted super_id
s are now inserted into sub1
.
Nothing too difficult really, but the above will only work if you have no other columns in sub1
than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.
The problem is to assign the new super_id
s to every inserted row individually. One way to implement the mapping could be like below:
CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
DECLARE @new_super TABLE (
rownum int IDENTITY (1, 1),
super_id int
);
INSERT INTO super (subtype_discriminator)
OUTPUT INSERTED.super_id INTO @new_super (super_id)
SELECT 'SUB1' FROM INSERTED;
WITH enumerated AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
FROM inserted
)
INSERT INTO sub1 (super_id, other columns)
SELECT n.super_id, i.other columns
FROM enumerated AS i
INNER JOIN @new_super AS n
ON i.rownum = n.rownum;
END;
As you can see, an IDENTIY(1,1)
column is added to @new_user
, so the temporarily inserted super_id
values will additionally be enumerated starting from 1. To provide the mapping between the new super_id
s and the new data rows, the ROW_NUMBER
function is used to enumerate the INSERTED
rows as well. As a result, every row in the INSERTED
set can now be linked to a single super_id
and thus complemented to a full data row to be inserted into sub1
.
Note that the order in which the new super_id
s are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super
rows generated are identical save for the IDs. So, all you need here is just to take one new super_id
per new sub1
row.
If, however, the logic of inserting into super
is more complex and for some reason you need to remember precisely which new super_id
has been generated for which new sub
row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:
I had a similar issue with Intellij. The issue was that someone added the file that I am trying to compare in Intellij to .gitignore, without actually deleting the file from Git.
They can be differentiated with where they are coming from or which developers they're targeting mainly.
Groovy is a bit like scripting version of Java. Long time Java programmers feel at home when building agile applications backed by big architectures. Groovy on Grails is, as the name suggests similar to the Rails framework. For people who don't want to bother with Java's verbosity all the time.
Scala is an object oriented and functional programming language and Ruby or Python programmers may feel more closer to this one. It employs quite a lot of common good ideas found in these programming languages.
Clojure is a dialect of the Lisp programming language so Lisp, Scheme or Haskell developers may feel at home while developing with this language.
There's no such thing as a global variable in C#. Period.
You can have static members if you want:
public static class MyStaticValues
{
public static bool MyStaticBool {get;set;}
}
It is a not-often-acknowledged fact that the block size of a block cipher is also an important security consideration (though nowhere near as important as the key size).
Blowfish (and most other block ciphers of the same era, like 3DES and IDEA) have a 64 bit block size, which is considered insufficient for the large file sizes which are common these days (the larger the file, and the smaller the block size, the higher the probability of a repeated block in the ciphertext - and such repeated blocks are extremely useful in cryptanalysis).
AES, on the other hand, has a 128 bit block size. This consideration alone is justification to use AES instead of Blowfish.
According to this documentation:
DESC MY_TABLE
is equivalent to
SELECT column_name "Name", nullable "Null?", concat(concat(concat(data_type,'('),data_length),')') "Type" FROM user_tab_columns WHERE table_name='TABLE_NAME_TO_DESCRIBE';
I've roughly translated that to the SQL Server equivalent for you - just make sure you're running it on the EX
database.
SELECT column_name AS [name],
IS_NULLABLE AS [null?],
DATA_TYPE + COALESCE('(' + CASE WHEN CHARACTER_MAXIMUM_LENGTH = -1
THEN 'Max'
ELSE CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5))
END + ')', '') AS [type]
FROM INFORMATION_SCHEMA.Columns
WHERE table_name = 'EMP_MAST'
Two examples that work:
(Example ONE)
// Remove from Listing the Items Checked in Checkbox for Delete
let temp_products_images = store.state.c_products.products_images
if (temp_products_images != null) {
for (var l = temp_products_images.length; l--;) {
// 'mark' is the checkbox field
if (temp_products_images[l].mark == true) {
store.state.c_products.products_images.splice(l,1); // THIS WORKS
// this.$delete(store.state.c_products.products_images,l); // THIS ALSO WORKS
}
}
}
(Example TWO)
// Remove from Listing the Items Checked in Checkbox for Delete
let temp_products_images = store.state.c_products.products_images
if (temp_products_images != null) {
let l = temp_products_images.length
while (l--)
{
// 'mark' is the checkbox field
if (temp_products_images[l].mark == true) {
store.state.c_products.products_images.splice(l,1); // THIS WORKS
// this.$delete(store.state.c_products.products_images,l); // THIS ALSO WORKS
}
}
}
You can create a custom link as described here using a small jQuery script
$('.linkPinIt').click(function(){
var url = $(this).attr('href');
var media = $(this).attr('data-image');
var desc = $(this).attr('data-desc');
window.open("//www.pinterest.com/pin/create/button/"+
"?url="+url+
"&media="+media+
"&description="+desc,"_blank","top=0,right=0,width=750,height=320");
return false;
});
this will work for all links with class linkPinIt
which have the image and the description stored in the HTML 5 data attributes data-image
and data-desc
<a href="https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F"
data-image="https%3A%2F%2Fc4.staticflickr.com%2F8%2F7027%2F6851755809_df5b2051c9_b.jpg"
data-desc="Title for Pinterest Photo" class="linkPinIt">
Pin it!
</a>
see this jfiddle example
I use 'setAttribute' function:
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
document.getElementById("example").setAttribute('value','My default value');
</script>
At least on Oracle they are all the same: http://www.oracledba.co.uk/tips/count_speed.htm
Expanding upon the above code from @dreamlax
char *readFile(char *fileName) {
FILE *file = fopen(fileName, "r");
char *code;
size_t n = 0;
int c;
if (file == NULL) return NULL; //could not open file
fseek(file, 0, SEEK_END);
long f_size = ftell(file);
fseek(file, 0, SEEK_SET);
code = malloc(f_size);
while ((c = fgetc(file)) != EOF) {
code[n++] = (char)c;
}
code[n] = '\0';
return code;
}
This gives you the length of the file, then proceeds to read it character by character.
you can use winhttprequest object instead of internet explorer as it's good to load data excluding pictures n advertisement instead of downloading full webpage including advertisement n pictures those make internet explorer object heavy compare to winhttpRequest object.
For the lazy, here's my Objective-C port of @Grumdrig's solution above:
CGFloat sqr(CGFloat x) { return x*x; }
CGFloat dist2(CGPoint v, CGPoint w) { return sqr(v.x - w.x) + sqr(v.y - w.y); }
CGFloat distanceToSegmentSquared(CGPoint p, CGPoint v, CGPoint w)
{
CGFloat l2 = dist2(v, w);
if (l2 == 0.0f) return dist2(p, v);
CGFloat t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
if (t < 0.0f) return dist2(p, v);
if (t > 1.0f) return dist2(p, w);
return dist2(p, CGPointMake(v.x + t * (w.x - v.x), v.y + t * (w.y - v.y)));
}
CGFloat distanceToSegment(CGPoint point, CGPoint segmentPointV, CGPoint segmentPointW)
{
return sqrtf(distanceToSegmentSquared(point, segmentPointV, segmentPointW));
}
The storage_path
function returns the fully qualified path to the storage directory:
$path = storage_path();
You may also use the storage_path
function to generate a fully qualified path to a given file relative to the storage directory:
$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');
Source: Laravel Doc
This is a very c# type of code:
var bks: Book[] = new Book[2];
In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:
var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;
Now to explain what new Book[2];
would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:
Book[2] = function (){alert("hey");}
var foo = new Book[2]
and you should see hey. Try it
Try using .+
instead of [(\w)(\W)(\s)]+
.
Note that this actually includes more than you need - ASCII only defines the first 128 characters.
You can use Files#readAllLines()
to get all lines of a text file into a List<String>
.
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
// ...
}
Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files
You can use String#split()
to split a String
in parts based on a regular expression.
for (String part : line.split("\\s+")) {
// ...
}
Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String
You can use Integer#valueOf()
to convert a String
into an Integer
.
Integer i = Integer.valueOf(part);
Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings
You can use List#add()
to add an element to a List
.
numbers.add(i);
Tutorial: Interfaces > The List Interface
So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).
List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
for (String part : line.split("\\s+")) {
Integer i = Integer.valueOf(part);
numbers.add(i);
}
}
If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines()
.
List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
.map(line -> line.split("\\s+")).flatMap(Arrays::stream)
.map(Integer::valueOf)
.collect(Collectors.toList());
Tutorial: Processing data with Java 8 streams
Yes, CSS can do this:
input[type=checkbox] {_x000D_
display: none;_x000D_
}_x000D_
input[type=checkbox] + *:before {_x000D_
content: "";_x000D_
display: inline-block;_x000D_
margin: 0 0.4em;_x000D_
/* Make some horizontal space. */_x000D_
width: .6em;_x000D_
height: .6em;_x000D_
border-radius: 0.6em;_x000D_
box-shadow: 0px 0px 0px .5px #888_x000D_
/* An outer circle. */_x000D_
;_x000D_
/* No inner circle. */_x000D_
background-color: #ddd;_x000D_
/* Inner color. */_x000D_
}_x000D_
input[type=checkbox]:checked + *:before {_x000D_
box-shadow: 0px 0px 0px .5px #888_x000D_
/* An outer circle. */_x000D_
, inset 0px 0px 0px .14em #ddd;_x000D_
/* An inner circle with above inner color.*/_x000D_
background-color: #444;_x000D_
/* The dot color */_x000D_
}
_x000D_
<div>_x000D_
<input id="check1" type="checkbox" name="check" value="check1" checked>_x000D_
<label for="check1">Fake Checkbox1</label>_x000D_
</div>_x000D_
<div>_x000D_
<input id="check2" type="checkbox" name="check" value="check2">_x000D_
<label for="check2">Fake Checkbox2</label>_x000D_
</div>_x000D_
<div>_x000D_
<input id="check2" type="radio" name="check" value="radio1" checked>_x000D_
<label for="check2">Real Checkbox1</label>_x000D_
</div>_x000D_
<div>_x000D_
<input id="check2" type="radio" name="check" value="radio2">_x000D_
<label for="check2">Real Checkbox2</label>_x000D_
</div>
_x000D_
According to C17 6.7.2 §2:
Each list of type specifiers shall be one of the following multisets (delimited by commas, when there is more than one multiset per item); the type specifiers may occur in any order, possibly intermixed with the other declaration specifiers
— void
— char
— signed char
— unsigned char
— short, signed short, short int, or signed short int
— unsigned short, or unsigned short int
— int, signed, or signed int
— unsigned, or unsigned int
— long, signed long, long int, or signed long int
— unsigned long, or unsigned long int
— long long, signed long long, long long int, or signed long long int
— unsigned long long, or unsigned long long int
— float
— double
— long double
— _Bool
— float _Complex
— double _Complex
— long double _Complex
— atomic type specifier
— struct or union specifier
— enum specifier
— typedef name
So in case of unsigned int
we can either write unsigned
or unsigned int
, or if we are feeling crazy, int unsigned
. The latter since the standard is stupid enough to allow "...may occur in any order, possibly intermixed". This is a known flaw of the language.
Proper C code uses unsigned int
.
Since your "async property" is in a viewmodel, you could use AsyncMVVM:
class MyViewModel : AsyncBindableBase
{
public string Title
{
get
{
return Property.Get(GetTitleAsync);
}
}
private async Task<string> GetTitleAsync()
{
//...
}
}
It will take care of the synchronization context and property change notification for you.
In my case, I found out it was division by zero.
The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.
WITH PivotCTE AS
(
select * from mytransactions
pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
numericmonth,
chardate,
SUM(totalamount) AS totalamount,
SUM(ISNULL(Australia, 0)) AS Australia,
SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate
The ISNULL
is to stop a NULL
value from nullifying the sum (because NULL
+ any value = NULL
)
Copying the answer from Chris:
Got it working:
import {AfterViewInit} from 'angular2/core';
export class HomeCmp implements AfterViewInit {
ngAfterViewInit() {
//Copy in all the js code from the script.js. Typescript will complain but it works just fine
}
I had this same issue and this fiddle is the shizzle :) It uses a directive to properly style the file field and you can even make it an image or whatever.
http://jsfiddle.net/stereosteve/v5Rdc/7/
/*globals angular:true*/_x000D_
var buttonApp = angular.module('buttonApp', [])_x000D_
_x000D_
buttonApp.directive('fileButton', function() {_x000D_
return {_x000D_
link: function(scope, element, attributes) {_x000D_
_x000D_
var el = angular.element(element)_x000D_
var button = el.children()[0]_x000D_
_x000D_
el.css({_x000D_
position: 'relative',_x000D_
overflow: 'hidden',_x000D_
width: button.offsetWidth,_x000D_
height: button.offsetHeight_x000D_
})_x000D_
_x000D_
var fileInput = angular.element('<input type="file" multiple />')_x000D_
fileInput.css({_x000D_
position: 'absolute',_x000D_
top: 0,_x000D_
left: 0,_x000D_
'z-index': '2',_x000D_
width: '100%',_x000D_
height: '100%',_x000D_
opacity: '0',_x000D_
cursor: 'pointer'_x000D_
})_x000D_
_x000D_
el.append(fileInput)_x000D_
_x000D_
_x000D_
}_x000D_
}_x000D_
})
_x000D_
<div ng-app="buttonApp">_x000D_
_x000D_
<div file-button>_x000D_
<button class='btn btn-success btn-large'>Select your awesome file</button>_x000D_
</div>_x000D_
_x000D_
<div file-button>_x000D_
<img src='https://www.google.com/images/srpr/logo3w.png' />_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
For performance reasons, the use of +=
(String
concatenation) is discouraged. The reason why is: Java String
is an immutable, every time a new concatenation is done a new String
is created (the new one has a different fingerprint from the older one already in the String pool ). Creating new strings puts pressure on the GC and slows down the program: object creation is expensive.
Below code should make it more practical and clear at the same time.
public static void main(String[] args)
{
// warming up
for(int i = 0; i < 100; i++)
RandomStringUtils.randomAlphanumeric(1024);
final StringBuilder appender = new StringBuilder();
for(int i = 0; i < 100; i++)
appender.append(RandomStringUtils.randomAlphanumeric(i));
// testing
for(int i = 1; i <= 10000; i*=10)
test(i);
}
public static void test(final int howMany)
{
List<String> samples = new ArrayList<>(howMany);
for(int i = 0; i < howMany; i++)
samples.add(RandomStringUtils.randomAlphabetic(128));
final StringBuilder builder = new StringBuilder();
long start = System.nanoTime();
for(String sample: samples)
builder.append(sample);
builder.toString();
long elapsed = System.nanoTime() - start;
System.out.printf("builder - %d - elapsed: %dus\n", howMany, elapsed / 1000);
String accumulator = "";
start = System.nanoTime();
for(String sample: samples)
accumulator += sample;
elapsed = System.nanoTime() - start;
System.out.printf("concatenation - %d - elapsed: %dus\n", howMany, elapsed / (int) 1e3);
start = System.nanoTime();
String newOne = null;
for(String sample: samples)
newOne = new String(sample);
elapsed = System.nanoTime() - start;
System.out.printf("creation - %d - elapsed: %dus\n\n", howMany, elapsed / 1000);
}
Results for a run are reported below.
builder - 1 - elapsed: 132us
concatenation - 1 - elapsed: 4us
creation - 1 - elapsed: 5us
builder - 10 - elapsed: 9us
concatenation - 10 - elapsed: 26us
creation - 10 - elapsed: 5us
builder - 100 - elapsed: 77us
concatenation - 100 - elapsed: 1669us
creation - 100 - elapsed: 43us
builder - 1000 - elapsed: 511us
concatenation - 1000 - elapsed: 111504us
creation - 1000 - elapsed: 282us
builder - 10000 - elapsed: 3364us
concatenation - 10000 - elapsed: 5709793us
creation - 10000 - elapsed: 972us
Not considering the results for 1 concatenation (JIT was not yet doing its job), even for 10 concatenations the performance penalty is relevant; for thousands of concatenations, the difference is huge.
Lessons learned from this very quick experiment (easily reproducible with the above code): never use the +=
to concatenate strings together, even in very basic cases where a few concatenations are needed (as said, creating new strings is expensive anyway and puts pressure on the GC).
Try ZZ
to save and close.
Here is a bit more info on using vim with Git
This happens to me all the time.
Go to the error log, find the exception, and open a few levels until you can see something more like a root cause. Does it says "Resource is out of sync with the file system" ?
When renaming packages, of course, Eclipse has to move files around in the file system. Apparently what happens is that it later discovers that something it thinks it needs to clean up has been renamed, can't find it, throws an exception.
There are a couple of things you might try. First, go to Window: Preferences, Workspace, and enable "Refresh Automatically". In theory this should fix the problem, but for me, it didn't.
Second, if you are doing a large refactoring with subpackages, do the subpackages one at a time, from the bottom up, and explicitly refresh with the file system after each subpackage is renamed.
Third, just ignore the error: when the error dialog comes up, click Abort to preserve the partial change, instead of rolling it back. Try it again, and again, and you may find you can get through the entire operation using multiple retries.
ALTER TABLE tbl_Country DROP columnName;
GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev
command. View definitions will show in your configured editor.
julian@assange=# \ev {your_view_names}
Bonus. Some useful command to interact with query buffer.
Query Buffer
\e [FILE] [LINE] edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\ev [VIEWNAME [LINE]] edit view definition with external editor
\p show the contents of the query buffer
\r reset (clear) the query buffer
\s [FILE] display history or save it to file
\w FILE write query buffer to file
I had this problem despite:
main()
; andMy eventual fix was the following:
main()
was in a namespace, so was effectively called something::main()
...removing this namespace fixed the problem.The set of paths where the compiler looks for the header files can be checked by the command:-
cpp -v
If you declare #include "" , the compiler first searches in current directory of source file and if not found, continues to search in the above retrieved directories.
If you declare #include <> , the compiler searches directly in those directories obtained from the above command.
Source:- http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art026
I agree with Brandrew, the problem is most likely caused by some missing dlls that can't be found neither on the system path nor in the folder where the executable is. Try putting the following DLLs nearby the executable:
Alternatively, try loading the executable into Dependency Walker ( http://www.dependencywalker.com/ ), it should point out the missing dlls for you.
You should have that Python version installed. If you have it then basically,
With virtualenv,
virtualenv --python=python3.8 env/place/you/want/to/save/to
with venv
python3.8 -m venv env/place/you/want/to/save/to
The above examples are for python3.8, you can change it to have different versions of virtual environments given that they are installed in your computer.
I think that the answer is that it depends on a whole range of factors such as:
These make it hard to predict which will be better. But my intuition is that the difference will not be that great.
Two bits of advice on optimization:
Don't waste time trying to optimize this ... unless the application is objectively too slow AND measurement using a profiler tells you that this is a performance hotspot. (The chances are that one of those preconditions won't be true.)
If you do decide to optimize this, do it scientifically. Try both (all) of the alternatives and decide which is best by measuring the performance in your actual application on a realistic problem / workload / input set. (An artificial benchmark is liable to give you answers that do not predict real-world behavior, because of factors like those I listed previously.)
For a quick fix or test, I find it handy just adding #define _CRT_SECURE_NO_WARNINGS
to the top of the file before all #include
#define _CRT_SECURE_NO_WARNINGS
#include ...
int main(){
//...
}
(see detailed explanation here)
$text = Get-Content $filePath | Out-String
The IO.File.ReadAllText
didn't work for me with a relative path, it looks for the file in %USERPROFILE%\$filePath
instead of the current directory (when running from Powershell ISE at least):
$text = [IO.File]::ReadAllText($filePath)
$text = Get-Content $filePath -Raw
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).
Using Visual Studio IDE for porting Java to C#:
Currently I am using Visual Studio IDE environment for porting codes from Java to C#. Why? Java has a huge libraries and C# enables the access to the UWP ecosystem.
For supporting editing and debugging as well as examining Java Bytecode (disassembly), you could try:
For supporting Android (Java/C++) development, you could try:
No issues with the latest kartoza/qgis-desktop
I ran
docker pull kartoza/qgis-desktop
followed by
docker run -it --rm --name "qgis-desktop-2-4" -v ${HOME}:/home/${USER} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY kartoza/qgis-desktop:latest
I did try multiple times without the conflict error - you do have to exit the app beforehand. Also, please note the parameters do differ slightly.
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
best way for show login for and close login form before login successfully put login form in FrmMain after InitializeComponent.
public FrmMain()
{
FrmSplash FrmSplash = new FrmSplash();
FrmSplash.ShowDialog();
InitializeComponent();
//Login Section
{
In pandas 0.16.1+ you can drop columns only if they exist per the solution posted by @eiTanLaVi. Prior to that version, you can achieve the same result via a conditional list comprehension:
df.drop([col for col in ['col_name_1','col_name_2',...,'col_name_N'] if col in df],
axis=1, inplace=True)
The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.
Once it has implemented that interface, you could do anything you want in the method it overrides.
The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.
There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.
I hope this was helpful to you!
You can also use a Tuple<> for a strongly-typed grouping.
from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
{
LastName = grouping.Key.Item1,
FirstName = grouping.Key.Item2,
MiddleName = grouping.Key.Item3,
DayCount = grouping.Count(),
AmountBilled = grouping.Sum(x => x.Rate),
}
It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.
http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html
Data Type Date Type Storage Required
(CLOB) (BLOB)
TINYTEXT TINYBLOB L + 1 bytes, where L < 2**8 (255)
TEXT BLOB L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT MEDIUMBLOB L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT LONGBLOB L + 4 bytes, where L < 2**32 (4 GB)
where L stands for the byte length of a string
The error says "The index is out of range". That means you were trying to index an object with a value that was not valid. If you have two books, and I ask you to give me your third book, you will look at me funny. This is the computer looking at you funny. You said - "create a collection". So it did. But initially the collection is empty: not only is there nothing in it - it has no space to hold anything. "It has no hands".
Then you said "the first element of the collection is now 'ItemID'". And the computer says "I never was asked to create space for a 'first item'." I have no hands to hold this item you are giving me.
In terms of your code, you created a view, but never specified the size. You need a
dataGridView1.ColumnCount = 5;
Before trying to access any columns. Modify
DataGridView dataGridView1 = new DataGridView();
dataGridView1.Columns[0].Name = "ItemID";
to
DataGridView dataGridView1 = new DataGridView();
dataGridView1.ColumnCount = 5;
dataGridView1.Columns[0].Name = "ItemID";
See http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columncount.aspx
There are a couple of things wrong in this code:
<input>
the wrong way. You should use a <label>
if you want to make the text behind it clickable.enabled
attribute, which does not exist. Use disabled
instead.false
, use disabled="disabled"
or simply disabled
without a value..change()
instead.I'm not sure what your code is supposed to do. My guess is that you want to disable the input field with class roomNumber
once someone selects "Walk in" (and possibly re-enable when deselected). If so, try this code:
HTML:
<form class="type">
<p>
<input type="radio" name="type" checked="checked" id="guest" value="guest" />
<label for="guest">In House</label>
</p>
<p>
<input type="radio" name="type" id="walk_in" value="walk_in" />
<label for="walk_in">Walk in</label>
</p>
<p>
<input type="text" name="roomnumber" class="roomNumber" value="12345" />
</p>
</form>
Javascript:
$("form input:radio").change(function () {
if ($(this).val() == "walk_in") {
// Disable your roomnumber element here
$('.roomNumber').attr('disabled', 'disabled');
} else {
// Re-enable here I guess
$('.roomNumber').removeAttr('disabled');
}
});
I created a fiddle here: http://jsfiddle.net/k28xd/1/
I found this worked best for my usecase:
<i class="btn btn-light fa fa-dribbble fa-4x" href="#"></i>
<i class="btn btn-light fa fa-behance-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-linkedin-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-twitter-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-facebook-square fa-4x" href="#"></i>
Year(Date)
Year()
: Returns the year portion of the date argument.
Date
: Current date only.
Explanation of both of these functions from here.
Try the following:
document.getElementById("successAndErrorMessages").innerHTML="someContent";
msdn link for detail : innerHTML Property
You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
host = host.substring(idx); //remove scheme if present
}
You can have return
in a void method, you just can't return any value (as in return 5;
), that's why they call it a void method. Some people always explicitly end void methods with a return statement, but it's not mandatory. It can be used to leave a function early, though:
void someFunct(int arg)
{
if (arg == 0)
{
//Leave because this is a bad value
return;
}
//Otherwise, do something
}
The AlexFTPS library used in the question seems to be dead (was not updated since 2011).
You can try to implement this without any external library. But unfortunately, neither the .NET Framework nor PowerShell have any explicit support for downloading all files in a directory (let only recursive file downloads).
You have to implement that yourself:
Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET framework (FtpWebRequest
or WebClient
). The .NET framework unfortunately does not support the MLSD
command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.
Your options are:
ListDirectory
method (NLST
FTP command) and simply download all the "names" as files.LIST
command = ListDirectoryDetails
method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d
at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)function DownloadFtpDirectory($url, $credentials, $localPath)
{
$listRequest = [Net.WebRequest]::Create($url)
$listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
$listRequest.Credentials = $credentials
$lines = New-Object System.Collections.ArrayList
$listResponse = $listRequest.GetResponse()
$listStream = $listResponse.GetResponseStream()
$listReader = New-Object System.IO.StreamReader($listStream)
while (!$listReader.EndOfStream)
{
$line = $listReader.ReadLine()
$lines.Add($line) | Out-Null
}
$listReader.Dispose()
$listStream.Dispose()
$listResponse.Dispose()
foreach ($line in $lines)
{
$tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
$name = $tokens[8]
$permissions = $tokens[0]
$localFilePath = Join-Path $localPath $name
$fileUrl = ($url + $name)
if ($permissions[0] -eq 'd')
{
if (!(Test-Path $localFilePath -PathType container))
{
Write-Host "Creating directory $localFilePath"
New-Item $localFilePath -Type directory | Out-Null
}
DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
}
else
{
Write-Host "Downloading $fileUrl to $localFilePath"
$downloadRequest = [Net.WebRequest]::Create($fileUrl)
$downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$downloadRequest.Credentials = $credentials
$downloadResponse = $downloadRequest.GetResponse()
$sourceStream = $downloadResponse.GetResponseStream()
$targetStream = [System.IO.File]::Create($localFilePath)
$buffer = New-Object byte[] 10240
while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
$targetStream.Write($buffer, 0, $read);
}
$targetStream.Dispose()
$sourceStream.Dispose()
$downloadResponse.Dispose()
}
}
}
Use the function like:
$credentials = New-Object System.Net.NetworkCredential("user", "mypassword")
$url = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory $url $credentials "C:\target\directory"
The code is translated from my C# example in C# Download all files and subdirectories through FTP.
If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD
command and/or parsing various LIST
listing formats. And ideally with a support for downloading all files from a directory or even recursive downloads.
For example with WinSCP .NET assembly you can download whole directory with a single call to Session.GetFiles
:
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Ftp
HostName = "ftp.example.com"
UserName = "user"
Password = "mypassword"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Download files
$session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
Internally, WinSCP uses the MLSD
command, if supported by the server. If not, it uses the LIST
command and supports dozens of different listing formats.
The Session.GetFiles
method is recursive by default.
(I'm the author of WinSCP)
This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:
$(function () {
$('body').on('click', '.odom-submit', function (e) {
$(this.form).submit();
$('#myModal').modal('hide');
});
});
To make this work I did this in the modal footer
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary odom-submit">Save changes</button>
</div>
Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.
I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
MP4 is just a container - the video and audio stream inside it will both be encoded in different formats.
Android natively only supports certain types of formats. This is the list here.
Make sure the video and audio encoding type is supported. Just because it says "mp4" doesn't automatically mean it should be playable.
I somehow stumbled on this clever hack on the internet ... I'm not sure if it's nasty or beautiful, but it lets you create a "magical" operator that allows you to unpack multiple return values into their own variable. The :=
function is defined here, and included below for posterity:
':=' <- function(lhs, rhs) {
frame <- parent.frame()
lhs <- as.list(substitute(lhs))
if (length(lhs) > 1)
lhs <- lhs[-1]
if (length(lhs) == 1) {
do.call(`=`, list(lhs[[1]], rhs), envir=frame)
return(invisible(NULL))
}
if (is.function(rhs) || is(rhs, 'formula'))
rhs <- list(rhs)
if (length(lhs) > length(rhs))
rhs <- c(rhs, rep(list(NULL), length(lhs) - length(rhs)))
for (i in 1:length(lhs))
do.call(`=`, list(lhs[[i]], rhs[[i]]), envir=frame)
return(invisible(NULL))
}
With that in hand, you can do what you're after:
functionReturningTwoValues <- function() {
return(list(1, matrix(0, 2, 2)))
}
c(a, b) := functionReturningTwoValues()
a
#[1] 1
b
# [,1] [,2]
# [1,] 0 0
# [2,] 0 0
I don't know how I feel about that. Perhaps you might find it helpful in your interactive workspace. Using it to build (re-)usable libraries (for mass consumption) might not be the best idea, but I guess that's up to you.
... you know what they say about responsibility and power ...
Try this: Left-click the tab, making a copy of the whole sheet, then cut the cells you want to keep the same and paste them into your original worksheet.
I would suggest:
DECLARE @sqlStatement nvarchar(MAX),
@tableName nvarchar(50) = 'TripEvent',
@columnName nvarchar(50) = 'CreatedDate';
SELECT @sqlStatement = 'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + dc.name + ';'
FROM sys.default_constraints AS dc
LEFT JOIN sys.columns AS sc
ON (dc.parent_column_id = sc.column_id)
WHERE dc.parent_object_id = OBJECT_ID(@tableName)
AND type_desc = 'DEFAULT_CONSTRAINT'
AND sc.name = @columnName
PRINT' ['+@tableName+']:'+@@SERVERNAME+'.'+DB_NAME()+'@'+CONVERT(VarChar, GETDATE(), 127)+'; '+@sqlStatement;
IF(LEN(@sqlStatement)>0)EXEC sp_executesql @sqlStatement
The accepted answer from @arshajii is totally correct. However just being more explicit by saying below,
StringUtils.isBlank()
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
StringUtils.isEmpty
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.
A lot of student exercises use Scanner
because it has a variety of methods to parse numbers. I usually just start with an idiomatic line-oriented filter:
import java.io.*;
public class FilterLine {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null) {
System.out.println(s);
}
}
}
Here is what I did and it worked, created a session in PHP and used xmlhhtprequest to check if session is set whenever an HTML page loads and it worked for Cordova.
A slightly extended example to initialize all missing arguments with None
:
from collections import namedtuple
class Node(namedtuple('Node', ['value', 'left', 'right'])):
__slots__ = ()
def __new__(cls, *args, **kwargs):
# initialize missing kwargs with None
all_kwargs = {key: kwargs.get(key) for key in cls._fields}
return super(Node, cls).__new__(cls, *args, **all_kwargs)
It seems, that the simple way
-Dmaven.javadoc.skip=true
does not work with the release-plugin. in this case you have to pass the parameter as an "argument"
mvn release:perform -Darguments="-Dmaven.javadoc.skip=true"
The best way to do this is by running the command:
git diff --name-only --cached
When you check the manual you will likely find the following:
--name-only
Show only names of changed files.
And on the example part of the manual:
git diff --cached
Changes between the index and your current HEAD.
Combined together you get the changes between the index and your current HEAD
and Show only names of changed files.
Update: --staged
is also available as an alias for --cached
above in more recent git versions.
With hooks in React 16.8 onward, it's easy to do this with useEffect
I've created a CodeSandbox to demonstrate this.
useEffect(() => {
// code to be run when state variables in
// dependency array changes
}, [stateVariables, thatShould, triggerChange])
Basically, useEffect
synchronises with state changes and this can be used to render the canvas
import React, { useState, useEffect, useRef } from "react";
import { Stage, Shape } from "@createjs/easeljs";
import "./styles.css";
export default function App() {
const [rows, setRows] = useState(10);
const [columns, setColumns] = useState(10);
let stage = useRef()
useEffect(() => {
stage.current = new Stage("canvas");
var rectangles = [];
var rectangle;
//Rows
for (var x = 0; x < rows; x++) {
// Columns
for (var y = 0; y < columns; y++) {
var color = "Green";
rectangle = new Shape();
rectangle.graphics.beginFill(color);
rectangle.graphics.drawRect(0, 0, 32, 44);
rectangle.x = y * 33;
rectangle.y = x * 45;
stage.current.addChild(rectangle);
var id = rectangle.x + "_" + rectangle.y;
rectangles[id] = rectangle;
}
}
stage.current.update();
}, [rows, columns]);
return (
<div>
<div className="canvas-wrapper">
<canvas id="canvas" width="400" height="300"></canvas>
<p>Rows: {rows}</p>
<p>Columns: {columns}</p>
</div>
<div className="array-form">
<form>
<label>Number of Rows</label>
<select
id="numRows"
value={rows}
onChange={(e) => setRows(e.target.value)}
>
{getOptions()}
</select>
<label>Number of Columns</label>
<select
id="numCols"
value={columns}
onChange={(e) => setColumns(e.target.value)}
>
{getOptions()}
</select>
</form>
</div>
</div>
);
}
const getOptions = () => {
const options = [1, 2, 5, 10, 12, 15, 20];
return (
<>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</>
);
};
When your class implements Comparable, the compareTo
method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals()
comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b")
would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
It is not recommended to change in node modules as updates or re-installation may remove those changes. So better to change in angular cli
Angular 9 in angular.json
{
"projects": {
"targets": {
"serve": {
"options": {
"port": 5000
}
}
}
}
}
I Hope this will help somebody in the future but simply go to you config.xml
, inside the widget
tag, change the default id(io.ionic.starter
) to your own id. Have a look at this for android package naming.
In kibana 4.0.2 there is no --log-file option. If I start kibana as a service with systemctl start kibana
I find log in /var/log/messages
As @nos pointed out in the comments of the currently accepted answer to this question, the accepted answer is incorrect.
Yes, there IS a difference between using %
and localhost
for the user account host when connecting via a socket connect instead of a standard TCP/IP connect.
A host value of %
does not include localhost
for sockets and thus must be specified if you want to connect using that method.
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
Aside from all the steps Luke and Vaiden recommended, I also had to rename all the customModule properties in my Storyboard to match the new name, and this has to be case sensitive.
Do use this:
highp float rand(vec2 co)
{
highp float a = 12.9898;
highp float b = 78.233;
highp float c = 43758.5453;
highp float dt= dot(co.xy ,vec2(a,b));
highp float sn= mod(dt,3.14);
return fract(sin(sn) * c);
}
Don't use this:
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
You can find the explanation in Improvements to the canonical one-liner GLSL rand() for OpenGL ES 2.0
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:
startInfo.Verb = "runas";
This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.
This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.
Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).
In most cases, this error is the result of code which tries to instantiate a COM object. For example, here is a piece of code starting up Excel:
Excel.ApplicationClass xlapp = new Excel.ApplicationClass();
Typically, in .NET 4 you just need to remove the 'Class' suffix and compile the code:
Excel.Application xlapp = new Excel.Application();
An MSDN explanation is here.
Alternative way (but it's not python style. It's JS style)
{{ files and 'Update' or 'Continue' }}
This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.
Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.
The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.
Breaking up a loop with timers is relatively straightforward:
var i=0;
(function () {
for (; i < 6000000; i++) {
/*
Normal processing here
*/
// Every 100,000 iterations, take a break
if ( i > 0 && i % 100000 == 0) {
// Manually increment `i` because we break
i++;
// Set a timer for the next iteration
window.setTimeout(arguments.callee);
break;
}
}
})();
This means, it couldn't find any class which can be executed as jersey RESTful web service.
Check:
com.sun.jersey.config.property.packages
' is missing in your
web.xml. com.sun.jersey.config.property.packages
'
param is missing or invalid (the mentioned package doesn't exists). It should be a package where you have put your POJO classes which runs as jersey services.@Path
attribute.The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible
. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:
.month-grid {
display: grid;
grid-template: repeat(6, 1fr) / repeat(7, 1fr);
background: #fff;
grid-gap: 2px;
}
.day-item-wrapper {
position: relative;
}
.day-item {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 10px;
background: rgba(0,0,0,0.1);
}
Both do the same on all browsers, AFAIK. Checked on Chrome and Firefox, both append display:none
to the style
attribute of the element.
If you are on a 64bit build of ubuntu or debian (see e.g. 'cat /proc/version') you should simply use the 64bit cross compilers, if you cloned
git clone https://github.com/raspberrypi/tools
then the 64bit tools are in
tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64
use that directory for the gcc-toolchain. A useful tutorial for compiling that I followed is available here Building and compiling Raspberry PI Kernel (use the -x64 path from above as ${CCPREFIX})
The simplest possible solution if you know the value
document.querySelector('option[value=" + value +"]').selected = true
It's nuanced.
If you need to have other systems interface with your services, than a lot of clients will be happier with SOAP, due to the layers of "verification" you have with the contracts, WSDL, and the SOAP standard.
For day-to-day systems calling into systems, I think that SOAP is a lot of unnecessary overhead when a simple HTML call will do.
I know this is an older post, but for what it's worth, I've found that the "simplest" solution is to just right-click on the database, and select "Tasks" -> "Export Data-tier Application". It's possible that this option is only available because the server is hosted on Azure (from what I remember working with Azure in the past, the .bacpac format was quite common there).
Once that's done, you can right-click on your local server "Databases" list, and use the "Import Data-tier Application" to get the data to your local machine using the .bacpac file.
Just bear in mind the export could take a long time. Took roughly two hours for mine to finish exporting. Import part is much faster, though.
Extension for @Kleist answer:
Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB)
and file(GLOB_RECURSE)
. With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.
However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.
Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB)
or file(GLOB_RECURSE)
for collect the sources.
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile fileTree(include: 'Parse-*.jar', dir: 'libs')
compile 'com.android.support:appcompat-v7:23.2.0'
compile 'com.android.support:cardview-v7:23.2.0'
compile 'com.android.support:design:24.0.0-alpha1'
compile "com.google.firebase:firebase-invites:9.2.0"
compile "com.google.firebase:firebase-ads:9.2.0"
compile 'com.google.firebase:firebase-database:9.2.0'
compile 'com.google.firebase:firebase-core:9.2.0'
}
I add the com.google.firebase:firebase-core:9.2.0
line and choose the same version (9.2.0) for all firebase libraries and the issue was solved.
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event
, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event
. If you import both using the wildcard method, one of these three things happens:
java.awt.Event
and com.mycompany.calendar.Event
, and so you can't even compile..*
), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.com.mycompany.calendar.Event
, but when they later add one your previously valid code suddenly stops compiling.The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.
If you don't mind a third-party dependency, you could use a library which natively supports primitive collections like Eclipse Collections and avoid the boxing altogether. You can also use primitive collections to create boxed regular collections if you need to.
int[] ints = {1, 2, 3};
MutableIntList intList = IntLists.mutable.with(ints);
List<Integer> list = intList.collect(Integer::valueOf);
If you want the boxed collection in the end, this is what the code for collect
on IntArrayList
is doing under the covers:
public <V> MutableList<V> collect(IntToObjectFunction<? extends V> function)
{
return this.collect(function, FastList.newList(this.size));
}
public <V, R extends Collection<V>> R collect(IntToObjectFunction<? extends V> function,
R target)
{
for (int i = 0; i < this.size; i++)
{
target.add(function.valueOf(this.items[i]));
}
return target;
}
Since the question was specifically about performance, I wrote some JMH benchmarks using your solutions, the most voted answer and the primitive and boxed versions of Eclipse Collections.
import org.eclipse.collections.api.list.primitive.IntList;
import org.eclipse.collections.impl.factory.primitive.IntLists;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@State(Scope.Thread)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Fork(2)
public class IntegerArrayListFromIntArray
{
private int[] source = IntStream.range(0, 1000).toArray();
public static void main(String[] args) throws RunnerException
{
Options options = new OptionsBuilder().include(
".*" + IntegerArrayListFromIntArray.class.getSimpleName() + ".*")
.forks(2)
.mode(Mode.Throughput)
.timeUnit(TimeUnit.SECONDS)
.build();
new Runner(options).run();
}
@Benchmark
public List<Integer> jdkClassic()
{
List<Integer> list = new ArrayList<>(source.length);
for (int each : source)
{
list.add(each);
}
return list;
}
@Benchmark
public List<Integer> jdkStreams1()
{
List<Integer> list = new ArrayList<>(source.length);
Collections.addAll(list,
Arrays.stream(source).boxed().toArray(Integer[]::new));
return list;
}
@Benchmark
public List<Integer> jdkStreams2()
{
return Arrays.stream(source).boxed().collect(Collectors.toList());
}
@Benchmark
public IntList ecPrimitive()
{
return IntLists.immutable.with(source);
}
@Benchmark
public List<Integer> ecBoxed()
{
return IntLists.mutable.with(source).collect(Integer::valueOf);
}
}
These are the results from these tests on my Mac Book Pro. The units are operations per second, so the bigger the number, the better. I used an ImmutableIntList
for the ecPrimitive
benchmark, because the MutableIntList
in Eclipse Collections doesn't copy the array by default. It merely adapts the array you give it. This was reporting even larger numbers for ecPrimitive
, with a very large margin of error because it was essentially measuring the cost of a single object creation.
# Run complete. Total time: 00:06:52
Benchmark Mode Cnt Score Error Units
IntegerArrayListFromIntArray.ecBoxed thrpt 40 191671.859 ± 2107.723 ops/s
IntegerArrayListFromIntArray.ecPrimitive thrpt 40 2311575.358 ± 9194.262 ops/s
IntegerArrayListFromIntArray.jdkClassic thrpt 40 138231.703 ± 1817.613 ops/s
IntegerArrayListFromIntArray.jdkStreams1 thrpt 40 87421.892 ± 1425.735 ops/s
IntegerArrayListFromIntArray.jdkStreams2 thrpt 40 103034.520 ± 1669.947 ops/s
If anyone spots any issues with the benchmarks, I'll be happy to make corrections and run them again.
Note: I am a committer for Eclipse Collections.
Solution(s) for this, found in the official wampserver.com forums:
This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )
To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80"
. Note thatPID
on the right side. This is the process id of the software which currently usesport 80
. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID
you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).
left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80"
to 8080
. Restart. Done !
Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here
By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.
IMPORTANT: you have to use localhost
or 127.0.0.1
now with port 8080
, this means 127.0.0.1:8080
or localhost:8080
.
If you want very few info like a class in your html for common browsers for instance, you could use:
function get_browser()
{
$browser = '';
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];
return $browser;
}
which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.
I had the same problem and I solved by using the postcast server. You can install it locally and use it.
Yet another solution, assuming the number of items in the folder is not huge:
tar -czf workspace.tar.gz `ls -A`
(ls -A
prints normal and hidden files but not "." and ".." as ls -a
does.)