Depending on what you want to accomplish, you might want to try out KeyValuePair.
The fact that you cannot change the key of an entry can of course be rectified by simply replacing the entire entry by a new instance of KeyValuePair.
Judging from your output it looks like you have defined START_DATE as a timestamp. If it were a regular date Oracle would be able to handle the implicit conversion. But as it isn't you need to explicitly cast those strings to be dates.
SQL> alter session set nls_date_format = 'dd-mon-yyyy hh24:mi:ss'
2 /
Session altered.
SQL>
SQL> select * from t23
2 where start_date between '15-JAN-10' and '17-JAN-10'
3 /
no rows selected
SQL> select * from t23
2 where start_date between to_date('15-JAN-10') and to_date('17-JAN-10')
3 /
WIDGET START_DATE
------------------------------ ----------------------
Small Widget 15-JAN-10 04.25.32.000
SQL>
But we still only get one row. This is because START_DATE has a time element. If we don't specify the time component Oracle defaults it to midnight. That is fine for the from side of the BETWEEN
but not for the until side:
SQL> select * from t23
2 where start_date between to_date('15-JAN-10')
3 and to_date('17-JAN-10 23:59:59')
4 /
WIDGET START_DATE
------------------------------ ----------------------
Small Widget 15-JAN-10 04.25.32.000
Product 1 17-JAN-10 04.31.32.000
SQL>
edit
If you cannot pass in the time component there are a couple of choices. One is to change the WHERE clause to remove the time element from the criteria:
where trunc(start_date) between to_date('15-JAN-10')
and to_date('17-JAN-10')
This might have an impact on performance, because it disqualifies any b-tree index on START_DATE. You would need to build a function-based index instead.
Alternatively you could add the time element to the date in your code:
where start_date between to_date('15-JAN-10')
and to_date('17-JAN-10') + (86399/86400)
Because of these problems many people prefer to avoid the use of between
by checking for date boundaries like this:
where start_date >= to_date('15-JAN-10')
and start_date < to_date('18-JAN-10')
n=int(input())
pair = dict()
for i in range(0,n):
word = input().split()
key = word[0]
value = word[1]
pair[key]=value
print(pair)
I already did it using Lotus Notus
and PHP
.
This solution works if you have access to the mail server or you can request something to the mail server
Administrator:
1) Create a group in the mail server
: Sales Department
2) Assign to the group
the accounts you need to be in the group
3) Assign an internet address to the group: [email protected]
4) Create your PHP script using the mail function:
$to = "[email protected]";
mail($to, $subject, $message, $headers);
It worked for me and all the accounts included in the group receive the mail.
The best of the lucks.
for large numbers that display with scientific notation set format to just '#'
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
https://developer.mozilla.org/en/CSS/vertical-align
<table style="height: 275px; width: 188px">
<tr>
<td style="width: 259px; vertical-align:top">
main page
</td>
</tr>
</table>
?
There are a lot of correct/same answers, but for future references:
Same stands for Tomcat 7. Be aware that updating only your used frameworks' versions (as proposed in other similar questions) isn't enough.
You also have to update Tomcat plugin's version. What worked for me, using Java 7, was upgrading to version 2.2 of tomcat7-maven-plugin (= Tomcat 7.0.47).
Here is how you get the execution path of the application:
var path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
MSDN has a full reference on how to determine the Executing Application's Path.
Note that the value in path
will be in the form of file:\c:\path\to\bin\folder
, so before using the path you may need to strip the file:\
off the front. E.g.:
path = path.Substring(6);
For those using force directed graphs in D3 v4/v5, the size
method doesn't exist any more. Something like the following worked for me (based on this github issue):
simulation
.force("center", d3.forceCenter(width / 2, height / 2))
.force("x", d3.forceX(width / 2))
.force("y", d3.forceY(height / 2))
.alpha(0.1).restart();
Set the theme in your android manifest file.
<activity android:name=".LoginActivity"
android:theme="@android:style/Theme.Dialog"/>
And set the dialog state on touch to finish.
this.setFinishOnTouchOutside(false);
The easiest way to find a midnight:
Long time = new Date().getTime();
Date date = new Date(time - time % (24 * 60 * 60 * 1000));
Next day:
Date date = new Date(date.getTime() + 24 * 60 * 60 * 1000);
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
In mi and vivo - Using the above solution is not enough. You must also tell the user to add permission manually. You can help them by opening the right location inside phone settings. Varies for different phone models.
//by importing Decimal format we can do...
import java.util.Scanner;
import java.text.DecimalFormat;
public class Average
{
public static void main(String[] args)
{
int sub1,sub2,sub3,total;
Scanner in = new Scanner(System.in);
System.out.print("Enter Subject 1 Marks : ");
sub1 = in.nextInt();
System.out.print("Enter Subject 2 Marks : ");
sub2 = in.nextInt();
System.out.print("Enter Subject 3 Marks : ");
sub3 = in.nextInt();
total = sub1 + sub2 + sub3;
System.out.println("Total Marks of Subjects = " + total);
res = (float)total;
average = res/3;
System.out.println("Before Rounding Decimal.. Average = " +average +"%");
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("After Rounding Decimal.. Average = " +df.format(average)+"%");
}
}
/* Output
Enter Subject 1 Marks : 72
Enter Subject 2 Marks : 42
Enter Subject 3 Marks : 52
Total Marks of Subjects = 166
Before Rounding Decimal.. Average = 55.333332%
After Rounding Decimal.. Average = 55.33%
*/
/* Output
Enter Subject 1 Marks : 98
Enter Subject 2 Marks : 88
Enter Subject 3 Marks : 78
Total Marks of Subjects = 264
Before Rounding Decimal.. Average = 88.0%
After Rounding Decimal.. Average = 88%
*/
/* You can Find Avrerage values in two ouputs before rounding average
And After rounding Average..*/
Here are the standard punctuation characters for US-ASCII: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
For Unicode punctuation (such as curly quotes, em-dashes, etc), you can easily match on specific block ranges. The General Punctuation block is \u2000-\u206F
, and the Supplemental Punctuation block is \u2E00-\u2E7F
.
Put together, and properly escaped, you get the following RegExp:
/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/
That should match pretty much any punctuation you encounter. So, to answer the original question:
var punctRE = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/g;
var spaceRE = /\s+/g;
var str = "This, -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
str.replace(punctRE, '').replace(spaceRE, ' ');
>> "This is an example of a string with punctuation"
US-ASCII source: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#posix
Unicode source: http://kourge.net/projects/regexp-unicode-block
You can create variable like this:
x = 10
print(x)
Or this:
globals()['y'] = 100
print(y)
Lets create a new class:
class Foo(object):
def __init__(self):
self.name = 'John'
You can create class instance this way:
instance_name_1 = Foo()
Or this way:
globals()['instance_name_2'] = Foo()
Lets create a function:
def create_new_instance(class_name,instance_name):
globals()[instance_name] = class_name()
print('Class instance '{}' created!'.format(instance_name))
Call a function:
create_new_instance(Foo,'new_instance') #Class instance 'new_instance' created!
print(new_instance.name) #John
Also we can write generator function:
def create_instance(class_name,instance_name):
count = 0
while True:
name = instance_name + str(count)
globals()[name] = class_name()
count += 1
print('Class instance: {}'.format(name))
yield True
generator_instance = create_instance(Foo,'instance_')
for i in range(5):
next(generator_instance)
#out
#Class instance: instance_0
#Class instance: instance_1
#Class instance: instance_2
#Class instance: instance_3
#Class instance: instance_4
print(instance_0.name) #john
print(instance_1.name) #john
print(instance_2.name) #john
print(instance_3.name) #john
print(instance_4.name) #john
#print(instance_5.name) #error.. we only created 5 instances..
next(generator_instance) #Class instance: instance_5
print(instance_5.name) #John Now it works..
Another option to stream images from a webcam to a browser is via mjpeg. This is just a series of jpeg images that most modern browsers support as part of the tag. Here's a sample server written in c#:
https://www.codeproject.com/articles/371955/motion-jpeg-streaming-server
This works well over a LAN, but not as well over the internet as mjpeg is not as effcient as other video codecs (h264, VP8 etc..)
For installing standard toolboxes: Just insert your CD/DVD of MATLAB and start installing, when you see typical/Custom, choose custom and check the toolboxes you want to install and uncheck the others which are installed already.
Not certain what the HTML looks like (that would help with answers). If it's
<div class="testimonials content">stuff</div>
then simply remove the space in your css. A la...
.testimonials.content { css here }
UPDATE:
Okay, after seeing HTML see if this works...
.testimonials .wrapper .content { css here }
or just
.testimonials .wrapper { css here }
or
.desc-container .wrapper { css here }
all 3 should work.
i think i hve some joined like this from 7 Tables
SELECT a.no_surat ,
a.nm_anggota ,
a.nrp_nip_anggota ,
a.tmpt_lahir ,
a.tgl_lahir ,
a.bln_lahir ,
a.thn_lahir ,
a.alamat ,
a.keperluan ,
a.nm_jabatan ,
b.id_polsek ,b.nm_polsek,
c.id_polres ,c.nm_polres ,
d.id_pangkat , d.nm_pangkat,
e.id_pejabat , e.nm_pejabat ,
f.id_ket , f.nm_ket,
g.id_pejabat,g.nm_pejabat
FROM tbl_skhp AS a
LEFT JOIN tbl_polsek AS b ON a.id_polsek=b.id_polsek
LEFT JOIN tbl_polres AS c ON a.id_polres=c.id_polres
LEFT JOIN tbl_pangkat AS d ON a.id_pangkat=d.id_pangkat
LEFT JOIN tbl_pejabat AS e ON a.id_pejabat=e.id_pejabat
LEFT JOIN tbl_ket AS f ON a.id_ket=f.id_ket
LEFT JOIN tbl_pejabat AS g ON a.id_pejabat=g.id_pejabat
i hope u understand.... i am just sharing worked code for me.... i am use it to fetch data to my readonly form just for priview...
Many users fall in this thread expecting to find a solution for blank pages being displayed while using nginx+php-fpm, me being one of them. This is a recap of what I ended up doing after reading many of the answers here plus my own investigations (updated to php7.2):
1) Open /etc/php/7.2/fpm/pool.d/www.conf
and check the value of parameter listen
.
listen = /var/run/php/php7.2-fpm.sock
2) Parameter listen
should match fastcgi_pass
parameter in your site configuration file (i,e: /etc/nginx/sites-enabled/default
).
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
3) Check the file actually exists:
$ file /var/run/php/php7.2-fpm.sock
/var/run/php/php7.2-fpm.sock: socket
4) If it doesn't exist that means php7.2-fpm is not running, so you need to restart it:
$ sudo /etc/init.d/php7.2-fpm restart
[ ok ] Restarting php7.2-fpm (via systemctl): php7.2-fpm.service.
With regard to the location
section in /etc/nginx/sites-enabled/default
:
# pass PHP scripts to FastCGI server
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php-fpm (or other unix sockets):
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}
Check the file snippets/fastcgi-php.conf
exists at location /etc/nginx/
:
$ file /etc/nginx/snippets/fastcgi-php.conf
/etc/nginx/snippets/fastcgi-php.conf: ASCII text
This file contains a list of variable definitions required by php7.2-fpm. The variables are defined directly or through an include of a separated file.
include fastcgi.conf;
This file is located at /etc/nginx/fastcgi.conf
and it looks like:
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
...
fastcgi_param REDIRECT_STATUS 200;
nginx includes two possible parameter files: fastcgi_params and fastcgi.conf. The difference between both is the definition of variable SCRIPT_FILENAME
:
$ diff fastcgi_params fastcgi.conf
1a2
> fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
To make a long story short, fastcgi.conf should always work. If for some reason you're set up is using fastcgi_params, you should define SCRIPT_FILENAME
:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php-fpm (or other unix sockets):
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
Now reload nginx configuration:
$ sudo nginx -s reload
And check a php file is displayed correctly. For instance:
/var/www/html/test.php
<pre><?php var_export($_SERVER)?></pre>
Where /var/www/html
is the path to the document root.
If despite all that, you're still seeing a blank file, make sure your php.ini
has short_open_tag
enabled (if you're testing a PHP page with short tags).
Maybe this is going a bit too far back but…
Also, I’d like to suggest that multiline text fields have a different type (e.g. “textarea") than single-line fields ("text"), as they really are different types of things, and imply different issues (semantics) for client-side handling.
Cheap and insecure answer:
Add
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
in code, before calling https.request()
A more secure way (the solution above makes the whole node process insecure) is answered in this question
You can either use the css property Fixed, or if you need something more fine-tuned then you need to use javascript and track the scrollTop property which defines where the user agent's scrollbar location is (0 being at the top ... and x being at the bottom)
.Fixed
{
position: fixed;
top: 20px;
}
or with jQuery:
$('#ParentContainer').scroll(function() {
$('#FixedDiv').css('top', $(this).scrollTop());
});
It works pretty well with 00xx
and +xx
:
^(?:00|\+)(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$
To properly answer this qustion you need to consider PHP internals or the target that PHP is built for.
To answer this from a typical Linux perspective on x86...
Sizes of types in C: https://usrmisc.wordpress.com/2012/12/27/integer-sizes-in-c-on-32-bit-and-64-bit-linux/
Types used in PHP for variables: http://php.net/manual/en/internals2.variables.intro.php
Strings are always 2GB as the length is always 32bits and a bit is wasted because it uses int rather than uint. int is impractical for lengths over 2GB as it requires a cast to avoid breaking arithmetic or "than" comparisons. The extra bit is likely being used for overflow checks.
Strangely, hash keys might internally support 4GB as uint is used although I have never put this to the test. PHP hash keys have a +1 to the length for a trailing null byte which to my knowledge gets ignored so it may need to be unsigned for that edge case rather than to allow longer keys.
A 32bit system may impose more external limits.
you can use the new HTML 5 file api to read file contents
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
but this won't work on every browser so you probably need a server side fallback.
file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo
Alternatively, if you're stuck with fopen()
you can use the w
or w+
modes:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
If you happen to have a shell opened inside Emacs, you can also do:
. ~/.emacs
May save a few key strokes.
It's been many functions, macros and objects since I posted this question. The way I handled it, which is mentioned in one of the answers here, is by creating a string function that handles the errors that get generate by the vlookup function, and returns either nothing or the vlookup result if any.
Function fsVlookup(ByVal pSearch As Range, ByVal pMatrix As Range, ByVal pMatColNum As Integer) As String
Dim s As String
On Error Resume Next
s = Application.WorksheetFunction.VLookup(pSearch, pMatrix, pMatColNum, False)
If IsError(s) Then
fsVlookup = ""
Else
fsVlookup = s
End If
End Function
One could argue about the position of the error handling or by shortening this code, but it works in all cases for me, and as they say, "if it ain't broke, don't try and fix it".
Not very clear what your issue is, but it sounds like you want something like this:
List<string> printer = new List<string>( new [] { "jupiter", "neptune", "pangea", "mercury", "sonic" } );
if( printer.Exists( p => p.Equals( "jupiter" ) ) )
{
...
}
import java.util.concurrent.atomic.AtomicInteger;
public class PrintEvenOddTester {
public static void main(String ... args){
Printer print = new Printer(false);
Thread t1 = new Thread(new TaskEvenOdd(print, "Thread1", new AtomicInteger(1)));
Thread t2 = new Thread(new TaskEvenOdd(print,"Thread2" , new AtomicInteger(2)));
t1.start();
t2.start();
}
}
class TaskEvenOdd implements Runnable {
Printer print;
String name;
AtomicInteger number;
TaskEvenOdd(Printer print, String name, AtomicInteger number){
this.print = print;
this.name = name;
this.number = number;
}
@Override
public void run() {
System.out.println("Run method");
while(number.get()<10){
if(number.get()%2 == 0){
print.printEven(number.get(),name);
}
else {
print.printOdd(number.get(),name);
}
number.addAndGet(2);
}
}
}
class Printer {
boolean isEven;
public Printer() { }
public Printer(boolean isEven) {
this.isEven = isEven;
}
synchronized void printEven(int number, String name) {
while (!isEven) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+": Even:" + number);
isEven = false;
notifyAll();
}
synchronized void printOdd(int number, String name) {
while (isEven) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+": Odd:" + number);
isEven = true;
notifyAll();
}
}
If you have an array like this
data = array
(
[0] => array
(
[subject] => a
[object] => c
),
[1] => array
(
[subject] => b
[object] => d
),
[2] => array
(
[subject] => d
[object] => b
),
[3] => array
(
[subject] => d
[object] => c
),
[4] => array
(
[subject] => c
[object] => a
),
[5] => array
(
[subject] => c
[object] => d
)
)
and you want to get arrays like this:
data = array
(
[0] => array
(
[subject] => a
[object] => c
),
[1] => array
(
[subject] => b
[object] => d
),
[2] => array
(
[subject] => d
[object] => c
)
)
or
data = array
(
[0] => array
(
[subject] => d
[object] => b
),
[1] => array
(
[subject] => c
[object] => a
),
[2] => array
(
[subject] => c
[object] => d
)
)
a following code can help
$data1 = array();
$data1 = $data;
for($q=0;$q<count($data);$q++)
{
for($p=0;$p<count($data1);$p++)
{
if (($data[$q]["subject"] == $data1[$p]["object"]) && ($data[$q]["object"] == $data1[$p]["subject"]))
{
$data1[$p]["subject"] = $data[$q]["subject"];
$data1[$p]["object"] = $data[$q]["object"];
}
}
}
$data1 = array_values(array_map("unserialize", array_unique(array_map("serialize", $data1))));
$data = $data1;
For those who are still facing this issue try adding:
libxml_use_internal_errors(true);
before the loadHtml
call and add
libxml_use_internal_errors(false);
after the call.
This solved it for me.
Alright, before I go into the solution, lets be on the same line about this one fact: Javascript is Event Based. So you'll usually have to setup callbacks to be able to do procedures.
Based on your comment I assumed you have a trigger that will do the logic that launched the function depending if the element is clicked; for sake of demonstration I made it a "submit button"; but this can be a timer or something else.
var the_action = function(type) {
switch(type) {
case 'a':
console.log('Case A');
break;
case 'b':
console.log('Case B');
break;
}
};
$('.clickme').click(function() {
console.log('Clicked');
$(this).data('clicked', true);
});
$('.submit').click(function() {
// All your logic can go here if you want.
if($('.clickme').data('clicked') == true) {
the_action('a');
} else {
the_action('b');
}
});
Live Example: http://jsfiddle.net/kuroir/6MCVJ/
I always considered the .hpp
header to be a sort of portmanteau of .h
and .cpp
files...a header which contains implementation details as well.
Typically when I've seen (and use) .hpp
as an extension, there is no corresponding .cpp
file. As others have said, this isn't a hard and fast rule, just how I tend to use .hpp
files.
You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:
fun_mean <- function(x){
return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}
ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)
I fixed a few bugs in the answer provided by Reigel (the accepted answer):
There are some remaining issues concerning spaces. I don't see a solution for double spaces, they are displayed as single spaces in the shadow (html rendering). This cannot be soved by using , because the spaces should break. Also, the textarea breaks a line after a space, if there is no room for that space it will break the line at an earlier point. Suggestions are welcome.
Corrected code:
(function ($) {
$.fn.autogrow = function (options) {
var $this, minHeight, lineHeight, shadow, update;
this.filter('textarea').each(function () {
$this = $(this);
minHeight = $this.height();
lineHeight = $this.css('lineHeight');
$this.css('overflow','hidden');
shadow = $('<div></div>').css({
position: 'absolute',
'word-wrap': 'break-word',
top: -10000,
left: -10000,
width: $this.width(),
fontSize: $this.css('fontSize'),
fontFamily: $this.css('fontFamily'),
lineHeight: $this.css('lineHeight'),
resize: 'none'
}).appendTo(document.body);
update = function () {
shadow.css('width', $(this).width());
var val = this.value.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n/g, '<br/>')
.replace(/\s/g,' ');
if (val.indexOf('<br/>', val.length - 5) !== -1) { val += '#'; }
shadow.html(val);
$(this).css('height', Math.max(shadow.height(), minHeight));
};
$this.change(update).keyup(update).keydown(update);
update.apply(this);
});
return this;
};
}(jQuery));
I needed to do something similar, here is my implementation. To recap the purpose, it is to have 2 elements take up the width of a given parent container, and the height to only be as high as it needs to be. Essentially height equaling max height of largest amount of content, but the other container being flush.
html
<div id="ven">
<section>some content</section>
<section>some content</section>
</div>
css
#ven {
height: 100%;
}
#ven section {
width: 50%;
float: left;
height: 100%;
}
As long as the object is actually a SkyfilterClient
, then a cast should work. Here is a contrived example to prove this:
using System;
class Program
{
static void Main()
{
NetworkClient net = new SkyfilterClient();
var sky = (SkyfilterClient)net;
}
}
public class NetworkClient{}
public class SkyfilterClient : NetworkClient{}
However, if it is actually a NetworkClient
, then you cannot magically make it become the subclass. Here is an example of that:
using System;
class Program
{
static void Main()
{
NetworkClient net = new NetworkClient();
var sky = (SkyfilterClient)net;
}
}
public class NetworkClient{}
public class SkyfilterClient : NetworkClient{}
HOWEVER, you could create a converter class. Here is an example of that, also:
using System;
class Program
{
static void Main()
{
NetworkClient net = new NetworkClient();
var sky = SkyFilterClient.CopyToSkyfilterClient(net);
}
}
public class NetworkClient
{
public int SomeVal {get;set;}
}
public class SkyfilterClient : NetworkClient
{
public int NewSomeVal {get;set;}
public static SkyfilterClient CopyToSkyfilterClient(NetworkClient networkClient)
{
return new SkyfilterClient{NewSomeVal = networkClient.SomeVal};
}
}
But, keep in mind that there is a reason you cannot convert this way. You may be missing key information that the subclass needs.
Finally, if you just want to see if the attempted cast will work, then you can use is
:
if(client is SkyfilterClient)
cast
If you are using Java 8, use the code below.
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);
import sys
def class_meta(frame):
class_context = '__module__' in frame.f_locals
assert class_context, 'Frame is not a class context'
module_name = frame.f_locals['__module__']
class_name = frame.f_code.co_name
return module_name, class_name
def print_class_path():
print('%s.%s' % class_meta(sys._getframe(1)))
class MyClass(object):
print_class_path()
In my case it should be:
from multiprocessing import JoinableQueue
Since in python2, Queue has methods like .task_done()
, but in python3 multiprocessing.Queue
doesn't have this method, and multiprocessing.JoinableQueue
does.
Here is a easy method.
First parse the JSON from url -
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
Then place a task and then read the desired value from JSON -
private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
JSONObject json;
try {
json = new JSONObject(result);
////CREATE A JSON OBJECT////
JSONObject data = json.getJSONObject("JSON OBJECT NAME");
////GET A STRING////
String title = data.getString("");
//Similarly you can get other types of data
//Replace String to the desired data type like int or boolean etc.
} catch (JSONException e1) {
e1.printStackTrace();
}
//GETTINGS DATA FROM JSON ARRAY//
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray postalCodesItems = new JSONArray(
jsonObject.getString("postalCodes"));
JSONObject postalCodesItem = postalCodesItems
.getJSONObject(1);
} catch (Exception e) {
Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
}
}
}
You can then place a task like this -
new ReadPlacesFeedTask()
.execute("JSON URL");
I like to give my input field a border, remove the outline on focus, and "outline" the border instead:
input {
border: 1px solid grey;
&:focus {
outline: none;
border-left: 1px solid violet;
}
}
You can also do it with a transparent border:
input {
border: 1px solid transparent;
&:focus {
outline: none;
border-left: 1px solid violet;
}
}
This below configuration working in my case
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<argLine>-XX:MaxPermSize=500M</argLine>
</configuration>
</plugin>
Try to use -XX:MaxPermSize instead of -XX:MaxPermGen
If you already have a struct.
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
)
// .....
type Student struct {
Name string `json:"name"`
Address string `json:"address"`
}
// .....
body := &Student{
Name: "abc",
Address: "xyz",
}
payloadBuf := new(bytes.Buffer)
json.NewEncoder(payloadBuf).Encode(body)
req, _ := http.NewRequest("POST", url, payloadBuf)
client := &http.Client{}
res, e := client.Do(req)
if e != nil {
return e
}
defer res.Body.Close()
fmt.Println("response Status:", res.Status)
// Print the body to the stdout
io.Copy(os.Stdout, res.Body)
Full gist.
One other significant point if you're using C# 6:
'=>' can be used instead of 'get' and is only for 'get only' methods - it can't be used with a 'set'.
For C# 7, see the comment from @avenmore below - it can now be used in more places. Here's a good reference - https://csharp.christiannagel.com/2017/01/25/expressionbodiedmembers/
Just create a symlink in your src folder for the namespace pointing to the folder containing your classes...
ln -s ../src/AppName ./src/AppName
Your autoload in composer will look the same...
"autoload": {
"psr-0": {"AppName": "src/"}
}
And your AppName namespaced classes will start a directory up from your current working directory in a src
folder now... that should work.
Use form-inline
.
It only works on screen resolutions greater than 768px though. To test the snippet below make sure to click the "Expand snippet" link to get a wider viewing area.
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
<form class="form-inline">_x000D_
<input type="text" class="form-control"/>-<input type="text" class="form-control"/>_x000D_
</form>
_x000D_
Reference: https://getbootstrap.com/docs/3.3/css/#forms-inline
You can also use,
parent.jQuery("#testdiv").attr("style", content from form);
Mostly READABILITY. When reading others code, it is much more intuitive to read as NOT CONTAINS KEY !values.containsKey(NoteColumns.CREATED_DATE)
instead of reading CONTAINS KEY IS FALSE (values.containsKey(NoteColumns.CREATED_DATE) == false)
.
Great answers from a couple of years ago. Now Bitbucket has made it easier.
Tag the Commit you want to download (as mentioned in answer by Rudy Matela).
Then head over to Downloads and click the "Tags" tab and you'll get multiple options for download.
Tensorflow upgrade -Python3
>> pip3 install --upgrade tensorflow --user
if you got this
"ERROR: tensorboard 2.0.2 has requirement grpcio>=1.24.3, but you'll have grpcio 1.22.0 which is incompatible."
Upgrade grpcio
>> pip3 install --upgrade grpcio --user
With support for C++11 initializer lists it is very easy:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using Strings = vector<string>;
void foo( Strings const& strings )
{
for( string const& s : strings ) { cout << s << endl; }
}
auto main() -> int
{
foo( Strings{ "hi", "there" } );
}
Lacking that (e.g. for Visual C++ 10.0) you can do things like this:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> Strings;
void foo( Strings const& strings )
{
for( auto it = begin( strings ); it != end( strings ); ++it )
{
cout << *it << endl;
}
}
template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }
template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
v.push_back( a );
return v;
}
int main()
{
foo( r( Strings() ) << "hi" << "there" );
}
The 'Access-Control-Allow-Origin' header contains multiple values
when i received this error i spent tons of hours searching solution for this but nothing works, finally i found solution to this problem which is very simple. when ''Access-Control-Allow-Origin' header added more than one time to your response this error occur, check your apache.conf or httpd.conf (Apache server), server side script, and remove unwanted entry header from these files.
You should use style instead of background color. Try searching holoeverywhere then I think this one will help you solve your problem
just change some of the 9patch resources to customize the edittext look and feel.
It's quite possible that someone will provide a truly detailed answer here, but I've always found this post from Robert Sosinski to be a great explanation of the subtleties between blocks, procs & lambdas.
I should add that I believe the post I'm linking to is specific to ruby 1.8. Some things have changed in ruby 1.9, such as block variables being local to the block. In 1.8, you'd get something like the following:
>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Goodbye"
Whereas 1.9 would give you:
>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Hello"
I don't have 1.9 on this machine so the above might have an error in it.
Instant.now()
The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
An Instant
represents a moment on the timeline in UTC with a resolution of up to nanoseconds.
Instant instant = Instant.now();
The toString
method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.
String output = instant.toString();
2016-06-27T19:15:25.864Z
The Instant
class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.
OffsetDateTime
But Instant
has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant
to OffsetDateTime
. Specify an offset-from-UTC. In java.time that means a ZoneOffset
object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC
.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
2016-06-27T19:15:25.864Z
Or skip the Instant
class.
OffsetDateTime.now( ZoneOffset.UTC )
Now with an OffsetDateTime
object in hand, you can use DateTimeFormatter
to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter
.
ZonedDateTime
When you want to display wall-clock time for some particular time zone, apply a ZoneId
to get a ZonedDateTime
.
In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00
. So note how the time-of-day is four hours earlier in the output, 15
instead of 19
hours. Instant
and the ZonedDateTime
both represent the very same simultaneous moment, just viewed through two different lenses.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
2016-06-27T15:15:25.864-04:00[America/Montreal]
While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant )
and java.util.Date::toInstant
.
java.util.Date utilDate = java.util.Date.from( instant );
And going the other direction.
Instant instant= utilDate.toInstant();
Similarly, look for new methods added to GregorianCalendar
(subclass of Calendar
) to convert to and from java.time.ZonedDateTime
.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
You may be able to use the JAVA_TOOL_OPTIONS
environment variable to set options. It worked for me with Rasbian. See Environment Variables and System Properties which has this to say:
In many environments, the command line is not readily accessible to start the application with the necessary command-line options.
This often happens with applications that use embedded VMs (meaning they use the Java Native Interface (JNI) Invocation API to start the VM), or where the startup is deeply nested in scripts. In these environments the JAVA_TOOL_OPTIONS environment variable can be useful to augment a command line.
When this environment variable is set, the JNI_CreateJavaVM function (in the JNI Invocation API), the JNI_CreateJavaVM function adds the value of the environment variable to the options supplied in its JavaVMInitArgs argument.
However this environment variable use may be disabled for security reasons.
In some cases, this option is disabled for security reasons. For example, on the Oracle Solaris operating system, this option is disabled when the effective user or group ID differs from the real ID.
See this example showing the difference between specifying on the command line versus using the JAVA_TOOL_OPTIONS
environment variable.
You could call editText.invalidate()
after you reset the hint color. That could resolve your issue. Actually the SDK update the color in the same way.
Reference link: http://www.programering.com/a/MTNyUDMwATA.html
Steps I followed
1) Execute the command adb nodaemon server
in command prompt
Output at command prompt will be: The following error occurred cannot bind 'tcp:5037'
The original ADB server port binding failed
2) Enter the following command query which using port 5037
netstat -ano | findstr "5037"
The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288
3) View the task manager, close all adb.exe
4) Restart eclipse or other IDE
The above steps worked for me.
If you are using Table.query
property:
from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()
If you are using session.query()
method (as stated in miniwark's answer):
from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()
Somebody wrote a blog post about this a few years back. There are examples in several languages, using both WebKit and Mozilla. There's also an example in Ruby.
It boils down to this: decide how wide you want your window to be; put a browser component in the window; wait until the page loads; capture the pixel buffer contents.
For my case was encountering this issue with Laravel 6.x and managed to sort it out by installing an SSL Certificate. Tried playing around with .htaccess but never worked. I'm using the default Laravel 6.x .htaccess file which has the following contents
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media
can be used for hiding elements in the screen width basis. See some example:
<div id="my-content"></div>
...and:
@media screen and (min-width: 0px) and (max-width: 400px) {
#my-content { display: block; } /* show it on small screens */
}
@media screen and (min-width: 401px) and (max-width: 1024px) {
#my-content { display: none; } /* hide it elsewhere */
}
Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.
GO isn't a keyword in SQL Server; it's a batch separator. GO ends a batch of statements. This is especially useful when you are using something like SQLCMD. Imagine you are entering in SQL statements on the command line. You don't necessarily want the thing to execute every time you end a statement, so SQL Server does nothing until you enter "GO".
Likewise, before your batch starts, you often need to have some objects visible. For example, let's say you are creating a database and then querying it. You can't write:
CREATE DATABASE foo;
USE foo;
CREATE TABLE bar;
because foo does not exist for the batch which does the CREATE TABLE. You'd need to do this:
CREATE DATABASE foo;
GO
USE foo;
CREATE TABLE bar;
That's a problem with your version of jquery. Look here https://code.jquery.com/ and add this script
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous">
</script>
Edit:
Android 5.0 (API level 21) and higher uses ART which supports multidexing. Therefore, if your minSdkVersion
is 21 or higher, the multidex support library is not needed.
Modify your build.gradle
:
android {
compileSdkVersion 22
buildToolsVersion "23.0.0"
defaultConfig {
minSdkVersion 14 //lower than 14 doesn't support multidex
targetSdkVersion 22
// Enabling multidex support.
multiDexEnabled true
}
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
If you are running unit tests, you will want to include this in your Application
class:
public class YouApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
Or just make your application
class extend MultiDexApplication
public class Application extends MultiDexApplication {
}
For more info, this is a good guide.
To get ride of all Unnamed columns, you can also use regex such as df.drop(df.filter(regex="Unname"),axis=1, inplace=True)
Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.
In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").
Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).
Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.
HTH.
On Mac OS X sudo port install ImageMagick
turned out to work fine to fix the gem install rmagick
problem . I just didn't know that it worked fine because rvm during installation blew away my .bash_profile contents which included MacPort's addition of /opt/local/bin
to PATH. I put back /opt/local/bin into PATH in my .bash_profile and then my gem install rmagick
then succeeded.
As per macOS 10.14.5, below are the details:
Go to
system preferences > sharing > remote login.
A way of producing a data.frame
and being able to do this in one line is to coerce all matrices/data frames passed to cbind
into a data.frame while setting the column names attribute using setNames
:
a = matrix(rnorm(10), ncol = 2)
b = matrix(runif(10), ncol = 2)
cbind(setNames(data.frame(a), c('n1', 'n2')),
setNames(data.frame(b), c('u1', 'u2')))
which produces:
n1 n2 u1 u2
1 -0.2731750 0.5030773 0.01538194 0.3775269
2 0.5177542 0.6550924 0.04871646 0.4683186
3 -1.1419802 1.0896945 0.57212043 0.9317578
4 0.6965895 1.6973815 0.36124709 0.2882133
5 0.9062591 1.0625280 0.28034347 0.7517128
Unfortunately, there is no for data frames that returns the matrix after the column names, however, there is nothing to stop you from adapting the code of setColNames
function analogous to setNames
setNames
to produce one:
setColNames <- function (object = nm, nm) {
colnames(object) <- nm
object
}
See this answer, the magrittr
package contains functions for this.
col_Names=["Sequence", "Start", "End", "Coverage"]
my_CSV_File= pd.read_csv("yourCSVFile.csv",names=col_Names)
having done this, just check it with[well obviously I know, u know that. But still...
my_CSV_File.head()
Hope it helps ... Cheers
As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them
You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built
If I have understood your question correctly you want to display one particular cell of your populated datatable? This what I used to display the given cell in my DataGrid.
var s = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();
Hope this helps
If checked:
$( "SELECTOR" ).attr( "checked" ) // Returns ‘true’ if present on the element, returns undefined if not present
$( "SELECTOR" ).prop( "checked" ) // Returns true if checked, false if unchecked.
$( "SELECTOR" ).is( ":checked" ) // Returns true if checked, false if unchecked.
Get the checked val:
$( "SELECTOR:checked" ).val()
Get the checked val numbers:
$( "SELECTOR:checked" ).length
Check or uncheck checkbox
$( "SELECTOR" ).prop( "disabled", false );
$( "SELECTOR" ).prop( "checked", true );
Here is a method that returns the image dimensions:
from PIL import Image
import os
def get_image_dimensions(imagefile):
"""
Helper function that returns the image dimentions
:param: imagefile str (path to image)
:return dict (of the form: {width:<int>, height=<int>, size_bytes=<size_bytes>)
"""
# Inline import for PIL because it is not a common library
with Image.open(imagefile) as img:
# Calculate the width and hight of an image
width, height = img.size
# calculat ethe size in bytes
size_bytes = os.path.getsize(imagefile)
return dict(width=width, height=height, size_bytes=size_bytes)
var_dump(json_decode('{"0":0}')); // output: object(0=>0)
var_dump(json_decode('[0]')); //output: [0]
var_dump(json_decode('{"0":0}', true));//output: [0]
var_dump(json_decode('[0]', true)); //output: [0]
If you decode the json into array, information will be lost in this situation.
Also, notice that by default Jersey will override the response body in case of an http code 400 or more.
In order to get your specified entity as the response body, try to add the following init-param to your Jersey in your web.xml configuration file :
<init-param>
<!-- used to overwrite default 4xx state pages -->
<param-name>jersey.config.server.response.setStatusOverSendError</param-name>
<param-value>true</param-value>
</init-param>
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array
, then it becomes a generic object.
If you want to get full screen without actionBar and Title.
Add it in style.xml
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
and use the style at activity of manifest.xml.
<activity ....
android:theme="@style/AppTheme.NoActionBar" > ......
</activity>
Sounds like what you want is multi-channel sounds. Let's suppose you have 4 channels (like on really old 16-bit games), I haven't got round to playing with the HTML5 audio feature yet, but don't you just need 4 <audio> elements, and cycle which is used to play the next sound effect? Have you tried that? What happens? If it works: To play more sounds simultaneously, just add more <audio> elements.
I have done this before without the HTML5 <audio> element, using a little Flash object from http://flash-mp3-player.net/ - I wrote a music quiz (http://webdeavour.appspot.com/) and used it to play clips of music when the user clicked the button for the question. Initially I had one player per question, and it was possible to play them over the top of each other, so I changed it so there was only one player, which I pointed at different music clips.
I know it's an old question and Path.GetFileNameWithoutExtension
is a better and maybe cleaner option. But personally I've added this two methods to my project and wanted to share them. This requires C# 8.0 due to it using ranges and indices.
public static string RemoveExtension(this string file) => ReplaceExtension(file, null);
public static string ReplaceExtension(this string file, string extension)
{
var split = file.Split('.');
if (string.IsNullOrEmpty(extension))
return string.Join(".", split[..^1]);
split[^1] = extension;
return string.Join(".", split);
}
//
is unconditionally "flooring division", e.g:
>>> 4.0//1.5
2.0
As you see, even though both operands are float
s, //
still floors -- so you always know securely what it's going to do.
Single /
may or may not floor depending on Python release, future imports, and even flags on which Python's run, e.g.:
$ python2.6 -Qold -c 'print 2/3'
0
$ python2.6 -Qnew -c 'print 2/3'
0.666666666667
As you see, single /
may floor, or it may return a float, based on completely non-local issues, up to and including the value of the -Q
flag...;-).
So, if and when you know you want flooring, always use //
, which guarantees it. If and when you know you don't want flooring, slap a float()
around other operand and use /
. Any other combination, and you're at the mercy of version, imports, and flags!-)
Below code for black:-
<color name="black">#000000</color>
Now if i want to use opacity than you can use below code :-
<color name="black">#99000000</color>
and below for opacity code:-
Hex Opacity Values
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00
If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".
First, checkout temp branch and start standard merge
git checkout -b temp
git merge origin/master
You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.
git commit -m "Merge branch 'origin/master' into 'temp'"
Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.
git checkout alpha
git rebase origin/master -X theirs
Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.
git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)
And delete temporary branch
git branch -D temp
That's all. We did a rebase via hidden merge.
Also I wrote a script, so that can be done in a dialog manner, you can find it here.
ListView is actually already capable of measuring itself to be tall enough to display all items, but it doesn't do this when you simply specify wrap_content (MeasureSpec.UNSPECIFIED). It will do this when given a height with MeasureSpec.AT_MOST. With this knowledge, you can create a very simple subclass to solve this problem which works far better than any of the solutions posted above. You should still use wrap_content with this subclass.
public class ListViewForEmbeddingInScrollView extends ListView {
public ListViewForEmbeddingInScrollView(Context context) {
super(context);
}
public ListViewForEmbeddingInScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ListViewForEmbeddingInScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 4, MeasureSpec.AT_MOST));
}
}
Manipulating the heightMeasureSpec to be AT_MOST with a very large size (Integer.MAX_VALUE >> 4) causes the ListView to measure all of its children up to the given (very large) height and set its height accordingly.
This works better than the other solutions for a few reasons:
On the downside, you could argue that doing this is relying on undocumented behavior in the SDK which could change. On the other hand, you could argue that this is how wrap_content should really work with ListView and that the current wrap_content behavior is just broken.
If you're worried that the behavior could change in the future, you should simply copy the onMeasure function and related functions out of ListView.java and into your own subclass, then make the AT_MOST path through onMeasure run for UNSPECIFIED as well.
By the way, I believe that this is a perfectly valid approach when you are working with small numbers of list items. It may be inefficient when compared to LinearLayout, but when the number of items is small, using LinearLayout is unnecessary optimization and therefore unnecessary complexity.
You can configure multiple remote repositories with the git remote
command:
git remote add alt alt-machine:/path/to/repo
To fetch from all the configured remotes and update tracking branches, but not merge into HEAD
, do:
git remote update
If it's not currently connected to one of the remotes, it will take time out or throw an error, and go on to the next. You'll have to manually merge from the fetched repositories, or cherry-pick
, depending on how you want to organize collecting changes.
To fetch the master branch from alt and pull it into your current head, do:
git pull alt master
So in fact git pull
is almost shorthand for git pull origin HEAD
(actually it looks in the config file to determine this, but you get the idea).
For pushing updates, you have to do that to each repo manually.
A push was, I think, designed with the central-repository workflow in mind.
A Hamiltonian path visits every node (or vertex) exactly once, and a Eulerian path traverses every edge exactly once.
Just use the result from the FOR
command. For example (inside a batch file):
for /F "delims=" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)
You can use the %%I
as the value you want. Just like this: %%I
.
And in advance the %%I
does not have any spaces or CR characters and can be used for comparisons!!
I think the best thing to do, if you're really concerned about the efficiency of concatenating all of these files, is to copy them all into the same bytes buffer.
buf := bytes.NewBuffer(nil)
for _, filename := range filenames {
f, _ := os.Open(filename) // Error handling elided for brevity.
io.Copy(buf, f) // Error handling elided for brevity.
f.Close()
}
s := string(buf.Bytes())
This opens each file, copies its contents into buf, then closes the file. Depending on your situation you may not actually need to convert it, the last line is just to show that buf.Bytes() has the data you're looking for.
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
Another option is to apply flex styling at the table row, and add the col-classes
to the table header / table data elements:
<table>
<thead>
<tr class="d-flex">
<th class="col-3">3 columns wide header</th>
<th class="col-sm-5">5 columns wide header</th>
<th class="col-sm-4">4 columns wide header</th>
</tr>
</thead>
<tbody>
<tr class="d-flex">
<td class="col-3">3 columns wide content</th>
<td class="col-sm-5">5 columns wide content</th>
<td class="col-sm-4">4 columns wide content</th>
</tr>
</tbody>
</table>
var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();
See the google.maps.LatLng docs and google.maps.Marker getPosition()
.
Here is a tweak of McDowell's algorithm that doesn't pad the result:
function toHex(str) {
var result = '';
for (var i=0; i<str.length; i++) {
result += str.charCodeAt(i).toString(16);
}
return result;
}
I used ☐
(☐) for [ ]
and ☑
(☑) for [x]
and it works for marked.js which says it is compatible with Github markdown. I based my solution on answers for this question. See also this informative answer.
Update: I should have mentioned that when you do it this way, you do not need the <ul>
, e.g:
| Unchecked | Checked |
| --------- | ------- |
| ☐ | ☑ |
I use something like this
>>> import datetime
>>> regex = datetime.datetime.strptime
>>>
>>> # TEST
>>> assert regex('2020-08-03', '%Y-%m-%d')
>>>
>>> assert regex('2020-08', '%Y-%m-%d')
ValueError: time data '2020-08' does not match format '%Y-%m-%d'
>>> assert regex('08/03/20', '%m/%d/%y')
>>>
>>> assert regex('08-03-2020', '%m/%d/%y')
ValueError: time data '08-03-2020' does not match format '%m/%d/%y'
It seems that Microsoft themselves prefer <>
to !=
as evidenced in their table constraints. I personally prefer using !=
because I clearly read that as "not equal", but if you enter [field1 != field2]
and save it as a constrait, the next time you query it, it will show up as [field1 <> field2]
. This says to me that the correct way to do it is <>
.
.bashrc
is not meant to be executed but sourced. Try this instead:
. ~/.bashrc
Cheers!
As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.
Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)
This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.
The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html
https://developer.android.com/reference/android/content/BroadcastReceiver.html
https://developer.android.com/guide/components/bound-services.html
In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:
https://developer.android.com/guide/components/aidl.html
Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip
This project will start an Activity which binds to a service; implementing the AIDL.
This project is also useful to re-factor for the purpose of IPC across different apps.
This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)
When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.
This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.
This project is developed in accordance to the above docs and is subsequently a clean solution.
There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.
You can begin by installing Node.js from terminal or cmd:
apt-get install nodejs-legacy npm
Then install the dependencies:
npm install
Then, start the server:
npm start
In asp.net core, If your api controller doesn't have annotation called [AllowAnonymous]
, add it to above your controller name like
[ApiController]
[Route("api/")]
[AllowAnonymous]
public class TestController : ControllerBase
For your current structure, you could also try the following:
select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country
I think I prefer a union between the two tables, and a group by on the country name as mentioned above.
But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)
Encountered similar error. resetting chrome://net-internals/#hsts did not work for me. The issue was that my vm's clock was skewed by days. resetting the time did work out to resolve this issue. https://support.google.com/chrome/answer/4454607?hl=en
The correct solution seems to be:
string text = ((ListBoxItem)ListBox1.SelectedItem).Content.ToString();
Please be sure to use .Content and not .Name.
TL;DR: The trick is to modify os.environment
before you import settings/base.py
in any settings/<purpose>.py
, this will greatly simplify things.
Just thinking about all these intertwining files gives me a headache.
Combining, importing (sometimes conditionally), overriding, patching of what was already set in case DEBUG
setting changed later on.
What a nightmare!
Through the years I went through all different solutions. They all somewhat work, but are so painful to manage.
WTF! Do we really need all that hassle? We started with just one settings.py
file.
Now we need a documentation just to correctly combine all these together in a correct order!
I hope I finally hit the (my) sweet spot with the solution below.
Keep secrets a secret — don't store them in a repo!
Set/read keys and secrets through environment settings, 12 factor style.
Have sensible fallback defaults. Ideally for local development you don't need anything more beside defaults.
…but try to keep defaults production safe. It's better to miss a setting override locally, than having to remember to adjust default settings safe for production.
Have the ability to switch DEBUG
on/off in a way that can have an effect on other settings (eg. using javascript compressed or not).
Switching between purpose settings, like local/testing/staging/production, should be based only on DJANGO_SETTINGS_MODULE
, nothing more.
…but allow further parameterization through environment settings like DATABASE_URL
.
…also allow them to use different purpose settings and run them locally side by side, eg. production setup on local developer machine, to access production database or smoke test compressed style sheets.
Fail if an environment variable is not explicitly set (requiring an empty value at minimum), especially in production, eg. EMAIL_HOST_PASSWORD
.
Respond to default DJANGO_SETTINGS_MODULE
set in manage.py during django-admin startproject
Keep conditionals to a minimum, if the condition is the purposed environment type (eg. for production set log file and it's rotation), override settings in associated purposed settings file.
Do not let django read DJANGO_SETTINGS_MODULE setting form a file.
Ugh! Think of how meta this is. If you need to have a file (like docker
env) read that into the environment before staring up a django process.
Do not override DJANGO_SETTINGS_MODULE in your project/app code, eg. based on hostname or process name.
If you are lazy to set environment variable (like for setup.py test
) do it in tooling just before you run your project code.
Avoid magic and patching of how django reads it's settings, preprocess the settings but do not interfere afterwards.
No complicated logic based nonsense. Configuration should be fixed and materialized not computed on the fly.
Providing a fallback defaults is just enough logic here.
Do you really want to debug, why locally you have correct set of settings but in production on a remote server,
on one of hundred machines, something computed differently? Oh! Unit tests? For settings? Seriously?
My strategy consists of excellent django-environ used with ini
style files,
providing os.environment
defaults for local development, some minimal and short settings/<purpose>.py
files that have an
import settings/base.py
AFTER the os.environment
was set from an INI
file. This effectively give us a kind of settings injection.
The trick here is to modify os.environment
before you import settings/base.py
.
To see the full example go do the repo: https://github.com/wooyek/django-settings-strategy
.
¦ manage.py
+---data
+---website
+---settings
¦ ¦ __init__.py <-- imports local for compatibility
¦ ¦ base.py <-- almost all the settings, reads from proces environment
¦ ¦ local.py <-- a few modifications for local development
¦ ¦ production.py <-- ideally is empty and everything is in base
¦ ¦ testing.py <-- mimics production with a reasonable exeptions
¦ ¦ .env <-- for local use, not kept in repo
¦ __init__.py
¦ urls.py
¦ wsgi.py
A defaults for local development. A secret file, to mostly set required environment variables.
Set them to empty values if they are not required in local development.
We provide defaults here and not in settings/base.py
to fail on any other machine if the're missing from the environment.
What happens in here, is loading environment from settings/.env
, then importing common settings
from settings/base.py
. After that we can override a few to ease local development.
import logging
import environ
logging.debug("Settings loading: %s" % __file__)
# This will read missing environment variables from a file
# We wan to do this before loading a base settings as they may depend on environment
environ.Env.read_env(DEBUG='True')
from .base import *
ALLOWED_HOSTS += [
'127.0.0.1',
'localhost',
'.example.com',
'vagrant',
]
# https://docs.djangoproject.com/en/1.6/topics/email/#console-backend
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
LOGGING['handlers']['mail_admins']['email_backend'] = 'django.core.mail.backends.dummy.EmailBackend'
# Sync task testing
# http://docs.celeryproject.org/en/2.5/configuration.html?highlight=celery_always_eager#celery-always-eager
CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
For production we should not expect an environment file, but it's easier to have one if we're testing something.
But anyway, lest's provide few defaults inline, so settings/base.py
can respond accordingly.
environ.Env.read_env(Path(__file__) / "production.env", DEBUG='False', ASSETS_DEBUG='False')
from .base import *
The main point of interest here are DEBUG
and ASSETS_DEBUG
overrides,
they will be applied to the python os.environ
ONLY if they are MISSING from the environment and the file.
These will be our production defaults, no need to put them in the environment or file, but they can be overridden if needed. Neat!
These are your mostly vanilla django settings, with a few conditionals and lot's of reading them from the environment. Almost everything is in here, keeping all the purposed environments consistent and as similar as possible.
The main differences are below (I hope these are self explanatory):
import environ
# https://github.com/joke2k/django-environ
env = environ.Env()
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Where BASE_DIR is a django source root, ROOT_DIR is a whole project root
# It may differ BASE_DIR for eg. when your django project code is in `src` folder
# This may help to separate python modules and *django apps* from other stuff
# like documentation, fixtures, docker settings
ROOT_DIR = BASE_DIR
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG', default=False)
INTERNAL_IPS = [
'127.0.0.1',
]
ALLOWED_HOSTS = []
if 'ALLOWED_HOSTS' in os.environ:
hosts = os.environ['ALLOWED_HOSTS'].split(" ")
BASE_URL = "https://" + hosts[0]
for host in hosts:
host = host.strip()
if host:
ALLOWED_HOSTS.append(host)
SECURE_SSL_REDIRECT = env.bool('SECURE_SSL_REDIRECT', default=False)
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
if "DATABASE_URL" in os.environ: # pragma: no cover
# Enable database config through environment
DATABASES = {
# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
'default': env.db(),
}
# Make sure we use have all settings we need
# DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis'
DATABASES['default']['TEST'] = {'NAME': os.environ.get("DATABASE_TEST_NAME", None)}
DATABASES['default']['OPTIONS'] = {
'options': '-c search_path=gis,public,pg_catalog',
'sslmode': 'require',
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# 'ENGINE': 'django.contrib.gis.db.backends.spatialite',
'NAME': os.path.join(ROOT_DIR, 'data', 'db.dev.sqlite3'),
'TEST': {
'NAME': os.path.join(ROOT_DIR, 'data', 'db.test.sqlite3'),
}
}
}
STATIC_ROOT = os.path.join(ROOT_DIR, 'static')
# django-assets
# http://django-assets.readthedocs.org/en/latest/settings.html
ASSETS_LOAD_PATH = STATIC_ROOT
ASSETS_ROOT = os.path.join(ROOT_DIR, 'assets', "compressed")
ASSETS_DEBUG = env('ASSETS_DEBUG', default=DEBUG) # Disable when testing compressed file in DEBUG mode
if ASSETS_DEBUG:
ASSETS_URL = STATIC_URL
ASSETS_MANIFEST = "json:{}".format(os.path.join(ASSETS_ROOT, "manifest.json"))
else:
ASSETS_URL = STATIC_URL + "assets/compressed/"
ASSETS_MANIFEST = "json:{}".format(os.path.join(STATIC_ROOT, 'assets', "compressed", "manifest.json"))
ASSETS_AUTO_BUILD = ASSETS_DEBUG
ASSETS_MODULES = ('website.assets',)
The last bit shows the power here. ASSETS_DEBUG
has a sensible default,
which can be overridden in settings/production.py
and even that that can be overridden by an environment setting! Yay!
In effect we have a mixed hierarchy of importance:
$parts = preg_split('/\s+/', $str);
You can use this simple plugin to add scrollUp
and scrollDown
to your jQuery
You could use php to echo the browser name as a body
class, e.g.
<body class="mozilla">
Then, your conditional CSS would look like
.ie #container { top: 5px;}
.mozilla #container { top: 5px;}
.chrome #container { top: 5px;}
<form action="myController/myAction" method="POST">
<input type="text" name="valueINeed" />
<input type="submit" value="View Report" />
</form>
controller:
[HttpPost]
public ActionResult myAction(string valueINeed)
{
//....
}
Inspired from this post and that post, I use this code to generate and verify hashed salted passwords. It only uses JDK provided classes, no external dependency.
The process is:
getNextSalt
hash
method to generate a salted and hashed password. The method returns a byte[]
which you can save as is in a database with the saltisExpectedPassword
method to check that the details match/**
* A utility class to hash passwords and check passwords vs hashed values. It uses a combination of hashing and unique
* salt. The algorithm used is PBKDF2WithHmacSHA1 which, although not the best for hashing password (vs. bcrypt) is
* still considered robust and <a href="https://security.stackexchange.com/a/6415/12614"> recommended by NIST </a>.
* The hashed value has 256 bits.
*/
public class Passwords {
private static final Random RANDOM = new SecureRandom();
private static final int ITERATIONS = 10000;
private static final int KEY_LENGTH = 256;
/**
* static utility class
*/
private Passwords() { }
/**
* Returns a random salt to be used to hash a password.
*
* @return a 16 bytes random salt
*/
public static byte[] getNextSalt() {
byte[] salt = new byte[16];
RANDOM.nextBytes(salt);
return salt;
}
/**
* Returns a salted and hashed password using the provided hash.<br>
* Note - side effect: the password is destroyed (the char[] is filled with zeros)
*
* @param password the password to be hashed
* @param salt a 16 bytes salt, ideally obtained with the getNextSalt method
*
* @return the hashed password with a pinch of salt
*/
public static byte[] hash(char[] password, byte[] salt) {
PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH);
Arrays.fill(password, Character.MIN_VALUE);
try {
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
return skf.generateSecret(spec).getEncoded();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new AssertionError("Error while hashing a password: " + e.getMessage(), e);
} finally {
spec.clearPassword();
}
}
/**
* Returns true if the given password and salt match the hashed value, false otherwise.<br>
* Note - side effect: the password is destroyed (the char[] is filled with zeros)
*
* @param password the password to check
* @param salt the salt used to hash the password
* @param expectedHash the expected hashed value of the password
*
* @return true if the given password and salt match the hashed value, false otherwise
*/
public static boolean isExpectedPassword(char[] password, byte[] salt, byte[] expectedHash) {
byte[] pwdHash = hash(password, salt);
Arrays.fill(password, Character.MIN_VALUE);
if (pwdHash.length != expectedHash.length) return false;
for (int i = 0; i < pwdHash.length; i++) {
if (pwdHash[i] != expectedHash[i]) return false;
}
return true;
}
/**
* Generates a random password of a given length, using letters and digits.
*
* @param length the length of the password
*
* @return a random password
*/
public static String generateRandomPassword(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int c = RANDOM.nextInt(62);
if (c <= 9) {
sb.append(String.valueOf(c));
} else if (c < 36) {
sb.append((char) ('a' + c - 10));
} else {
sb.append((char) ('A' + c - 36));
}
}
return sb.toString();
}
}
As of Typescript 2.9, one can simply add:
"compilerOptions": {
"resolveJsonModule": true
}
to the tsconfig.json
. Thereafter, it's easy to use a json file (and there will be nice type inference in VSCode, too):
data.json
:
{
"cases": [
{
"foo": "bar"
}
]
}
In your Typescript file:
import { cases } from './data.json';
& is used in PHP to pass an object to a method / assign a new object to a variable by reference. It is deprecated in PHP 5 because PHP 5 passes all objects by reference by default.
You can access the Python console via “View/Show console” or Ctrl+`.
If we want to bind to a dictionary ie
<ComboBox SelectedValue="{Binding Pathology, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{x:Static RnxGlobal:CLocalizedEnums.PathologiesValues}" DisplayMemberPath="Value" SelectedValuePath="Key"
Margin="{StaticResource SmallMarginLeftBottom}"/>
then SelectedItem will not work whilist SelectedValue will
Trailing whitespace:
It is extra spaces (and tabs) at the end of line
^^^^^ here
Strip them:
#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""
import sys
if len(sys.argv[1:]) != 1:
sys.exit(__doc__)
content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
content = infile.read()
with open(outp, 'wb') as output:
for line in content.splitlines():
newline = line.rstrip(" \t")
outsize += len(newline) + 1
output.write(newline + '\n')
print("Done. Stripped %s bytes." % (len(content)-outsize))
The Python Documentation provides this snippet to get single characters from the keyboard:
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
if c:
print("Got character", repr(c))
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
You can also use the PyHook module to get your job done.
Directly from ngStyle
docs:
Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys.
<div ng-style="{'width': '20px', 'height': '20px', ...}"></div>
So you could do this:
<div ng-style="{'background-color': data.backgroundCol}"></div>
Hope this helps!
The following worked for me:
Select
Count(Distinct user_id) As countUsers
, Count(site_id) As countVisits
, site_id As site
From cp_visits
Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Group By site_id
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.
Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.
string myMessage="helloworld";
int len;
int slength = (int)myMessage.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len);
std::wstring r(buf);
std::wstring stemp = r.C_str();
LPCWSTR result = stemp.c_str();
display html form values in same page after clicking on submit button using JS & html codes. After opening it up again it should give that comments in that page.
I had similar situation:
$foo = array();
$foo[] = 'test'; // error
$foo[] = "test"; // working fine
From Python you can do directly using below code
import subprocess
proc = subprocess.check_output('C:\Windows\System32\cmd.exe /k %windir%\System32\\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f' ,stderr=subprocess.STDOUT,shell=True)
print(str(proc))
in first parameter just executed User Account setting you may customize with yours.
You can use map
, which is a functional programming technique that's also available in other languages like Python and Haskell.
[1,2,3,4].map( function(item) {
alert(item);
})
The general syntax is:
array.map(func)
In general func
would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.
The return value of array.map
is another array, so you can use it like this:
var x = [1,2,3,4].map( function(item) {return item * 10;});
And now x is [10,20,30,40]
.
You don't have to write the function inline. It could be a separate function.
var item_processor = function(item) {
// Do something complicated to an item
}
new_list = my_list.map(item_processor);
which would be sort-of equivalent to:
for (item in my_list) {item_processor(item);}
Except you don't get the new_list
.
You just need to enter this command:
sudo apt-get install gcc
I know that the question is old but still relevant.
The only solution that I've found that works is using @media query like this:
@media (hover) { my-class:hover {
//properties
}
}
My reference: https://www.jonathanfielding.com/an-introduction-to-interaction-media-features/
Font myFont = new Font ("Courier New", 1, 17);
The 17 represents the font size. Once you have that, you can put:
g.setFont (myFont);
g.drawString ("Hello World", 10, 10);
Fixed it by setting the class name to the property "classesToBeBound" of the JAXB marshaller:
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>myclass</value>
</list>
</property>
</bean>
You don't need to use display:inline
to achieve this:
.inline {
border: 1px solid red;
margin:10px;
float:left;/*Add float left*/
margin :10px;
}
You can use float-left
.
Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.
Using the Excel Text import wizard to import it if it is a text file, like a CSV file, is another option and can be done based on which row number to which row numbers you specify. See: This link
You can try git difftool
, it is designed to do this stuff.
First, you need to config diff tool to vimdiff
git config diff.tool vimdiff
Then, when you want to diff, just use git difftool
instead of git diff
. It will work as you expect.
Just define your variables in global.js outside a function scope:
// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";
// other js-file
function testGlobal () {
alert(global1);
}
To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:
<html>
<head>
<!-- Include global.js first -->
<script src="/YOUR_PATH/global.js" type="text/javascript"></script>
<!-- Now we can reference variables, objects, functions etc.
defined in global.js -->
<script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
</head>
[...]
</html>
You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.
Using autoview
image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
A good method which is a favorite of mine and for many I'm sure, is to make use of foreach
which will output each color you chose, and appear on screen one underneath each other.
When it comes to using checkboxes, you kind of do not have a choice but to use foreach
, and that's why you only get one value returned from your array.
Here is an example using $_GET
. You can however use $_POST
and would need to make both directives match in both files in order to work properly.
###HTML FORM
<form action="third.php" method="get">
Red<input type="checkbox" name="color[]" value="red">
Green<input type="checkbox" name="color[]" value="green">
Blue<input type="checkbox" name="color[]" value="blue">
Cyan<input type="checkbox" name="color[]" value="cyan">
Magenta<input type="checkbox" name="color[]" value="Magenta">
Yellow<input type="checkbox" name="color[]" value="yellow">
Black<input type="checkbox" name="color[]" value="black">
<input type="submit" value="submit">
</form>
###PHP (using $_GET) using third.php
as your handler
<?php
$name = $_GET['color'];
// optional
// echo "You chose the following color(s): <br>";
foreach ($name as $color){
echo $color."<br />";
}
?>
Assuming having chosen red, green, blue and cyan as colors, will appear like this:
red
green
blue
cyan
##OPTION #2
You can also check if a color was chosen. If none are chosen, then a seperate message will appear.
<?php
$name = $_GET['color'];
if (isset($_GET['color'])) {
echo "You chose the following color(s): <br>";
foreach ($name as $color){
echo $color."<br />";
}
} else {
echo "You did not choose a color.";
}
?>
##Additional options:
To appear as a list: (<ul></ul>
can be replaced by <ol></ol>
)
<?php
$name = $_GET['color'];
if (isset($_GET['color'])) {
echo "You chose the following color(s): <br>";
echo "<ul>";
foreach ($name as $color){
echo "<li>" .$color."</li>";
}
echo "</ul>";
} else {
echo "You did not choose a color.";
}
?>
Want to format it automatically when you save the file???
then Goto Window > Preferences > Java > Editor > Save Actions
and configure your save actions.
Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc
You can't use a LinearLayout for this, but you can use a FrameLayout
. In a FrameLayout
, the z-index is defined by the order in which the items are added, for example:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_drawable"
android:scaleType="fitCenter"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:padding="5dp"
android:text="My Label"
/>
</FrameLayout>
In this instance, the TextView would be drawn on top of the ImageView, along the bottom center of the image.
The answers here, as usual, expect a level of interactivity.
The problem is when something is listening through HTTP.sys; then, the PID is always 4 and, as most people find, you need some tool to find the real owner.
Here's how to identify the offending process programmatically. No TcpView, etc (as good as those tools are). Does rely on netsh; but then, the problem is usually related to HTTP.sys.
$Uri = "http://127.0.0.1:8989" # for example
# Shows processes that have registered URLs with HTTP.sys
$QueueText = netsh http show servicestate view=requestq verbose=yes | Out-String
# Break into text chunks; discard the header
$Queues = $QueueText -split '(?<=\n)(?=Request queue name)' | Select-Object -Skip 1
# Find the chunk for the request queue listening on your URI
$Queue = @($Queues) -match [regex]::Escape($Uri -replace '/$')
if ($Queue.Count -eq 1)
{
# Will be null if could not pick out exactly one PID
$ProcessId = [string]$Queue -replace '(?s).*Process IDs:\s+' -replace '(?s)\s.*' -as [int]
if ($ProcessId)
{
Write-Verbose "Identified process $ProcessId as the HTTP listener. Killing..."
Stop-Process -Id $ProcessId -Confirm
}
}
Originally posted here: https://stackoverflow.com/a/65852847/6274530
Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:
gcc -O2 -S foo.c
will leave the generated assembly code on the file foo.s.
Ripped straight from http://www.delorie.com/djgpp/v2faq/faq8_20.html (but removing erroneous -c
)
There is no definitive reason why unreachable statements must be not be allowed; other languages allow them without problems. For your specific need, this is the usual trick:
if (true) return;
It looks nonsensical, anyone who reads the code will guess that it must have been done deliberately, not a careless mistake of leaving the rest of statements unreachable.
Java has a little bit support for "conditional compilation"
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.21
if (false) { x=3; }
does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.
The rationale for this differing treatment is to allow programmers to define "flag variables" such as:
static final boolean DEBUG = false;
and then write code such as:
if (DEBUG) { x=3; }
The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.
Foreground needs a Brush, so you can use
textBlock.Foreground = Brushes.Navy;
If you want to use the color from RGB or ARGB then
textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35));
or
textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy);
To get the Color from Hex
textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991"));
See What is the maximum length of a URL in different browsers?
The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.
in case your project use dagger, and then this error show up you can add this at android manifest
<application
...
android: name = ".BaseApplication"
...> ...
Created an overall rehauled and fail-safe implementation from all comments and suggestions:
# collect stats about the dir
- name: check directory exists
stat:
path: '{{ directory_path }}'
register: dir_to_delete
# delete directory if condition is true
- name: purge {{directory_path}}
file:
state: absent
path: '{{ directory_path }}'
when: dir_to_delete.stat.exists and dir_to_delete.stat.isdir
# create directory if deleted (or if it didn't exist at all)
- name: create directory again
file:
state: directory
path: '{{ directory_path }}'
when: dir_to_delete is defined or dir_to_delete.stat.exist == False
You can use RequestDispatcher
as you usually use it in Servlet
:
<%@ page contentType="text/html"%>
<%@ page import = "javax.servlet.RequestDispatcher" %>
<%
RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
request.setAttribute("msg","HI Welcome");
rd.forward(request, response);
%>
Always be aware that don't commit any response before you use forward
, as it will lead to IllegalStateException
.
Here's an efficient way of achieving the result with two caveats.
See sample test cases here.
123.12345678 ==> 123.123
1.230000 ==> 1.23
1.1 ==> 1.1
1 ==> 1.0
0.000 ==> 0.0
0.00 ==> 0.0
0.4 ==> 0.4
0 ==> 0.0
1.4999 ==> 1.499
1.4995 ==> 1.499
1.4994 ==> 1.499
Here's the code. The two caveats I mentioned above can be addressed pretty easily, however, speed mattered more to me than accuracy, so i left it here.
String manipulations like System.out.printf("%.2f",123.234);
are computationally costly compared to mathematical operations. In my tests, the below code (without the sysout) took 1/30th the time compared to String manipulations.
public double limitPrecision(String dblAsString, int maxDigitsAfterDecimal) {
int multiplier = (int) Math.pow(10, maxDigitsAfterDecimal);
double truncated = (double) ((long) ((Double.parseDouble(dblAsString)) * multiplier)) / multiplier;
System.out.println(dblAsString + " ==> " + truncated);
return truncated;
}
One more important difference: typedef
s cannot be forward declared. So for the typedef
option you must #include
the file containing the typedef
, meaning everything that #include
s your .h
also includes that file whether it directly needs it or not, and so on. It can definitely impact your build times on larger projects.
Without the typedef
, in some cases you can just add a forward declaration of struct Foo;
at the top of your .h
file, and only #include
the struct definition in your .cpp
file.
Try > workdirectory/filename.txt
This would:
You can consider it equivalent to:
rm -f workdirectory/filename.txt; touch workdirectory/filename.txt
dayStart.bat
start "startOfficialSoftwares" /min cmd /k call startOfficialSoftwares.bat
start "initCodingEnvironment" /min cmd /k call initCodingEnvironment.bat
start "updateProjectSource" /min cmd /k call updateProjectSource.bat
start "runCoffeeMachine" /min cmd /k call runCoffeeMachine.bat
release.bat
call updateDevelVersion.bat
call mergeDevelIntoMaster.bat
call publishProject.bat
plot
has a plot.function
method
plot(eq, 1, 1000)
Or
curve(eq, 1, 1000)
If you want to do 1 file at a time you can go to the History view for the file assuming you have an Eclipse SVN plugin installed. "Team->Show History"
In the History view, find the last good version of that file, right click and choose "Get Contents". This will replace your current version with that version's contents. Then you can commit the changes when you've fixed it all up.
If true -> 1
and false -> 0
mapping is what you want, you can do:
boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.
Using Object Catalog Views:
SELECT T.NAME AS [TABLE NAME], C.NAME AS [COLUMN NAME], P.NAME AS [DATA TYPE], P.MAX_LENGTH AS[SIZE], CAST(P.PRECISION AS VARCHAR) +‘/’+ CAST(P.SCALE AS VARCHAR) AS [PRECISION/SCALE]
FROM ADVENTUREWORKS.SYS.OBJECTS AS T
JOIN ADVENTUREWORKS.SYS.COLUMNS AS C
ON T.OBJECT_ID=C.OBJECT_ID
JOIN ADVENTUREWORKS.SYS.TYPES AS P
ON C.SYSTEM_TYPE_ID=P.SYSTEM_TYPE_ID
WHERE T.TYPE_DESC=‘USER_TABLE’;
Using Information Schema Views
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION,
COLUMN_DEFAULT, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, NUMERIC_SCALE,
DATETIME_PRECISION
FROM ADVENTUREWORKS.INFORMATION_SCHEMA.COLUMNS
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;
}
}
Try this:
yAxis: {min: 0, max: 100}
See this jsfiddle example
This is my solution with stack
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
final themeColor = new Color(0xfff5a623);
final primaryColor = new Color(0xff203152);
final greyColor = new Color(0xffaeaeae);
final greyColor2 = new Color(0xffE8E8E8);
class LoadindScreen extends StatefulWidget {
LoadindScreen({Key key, this.title}) : super(key: key);
final String title;
@override
LoginScreenState createState() => new LoginScreenState();
}
class LoginScreenState extends State<LoadindScreen> {
SharedPreferences prefs;
bool isLoading = false;
Future<Null> handleSignIn() async {
setState(() {
isLoading = true;
});
prefs = await SharedPreferences.getInstance();
var isLoadingFuture = Future.delayed(const Duration(seconds: 3), () {
return false;
});
isLoadingFuture.then((response) {
setState(() {
isLoading = response;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: Stack(
children: <Widget>[
Center(
child: FlatButton(
onPressed: handleSignIn,
child: Text(
'SIGN IN WITH GOOGLE',
style: TextStyle(fontSize: 16.0),
),
color: Color(0xffdd4b39),
highlightColor: Color(0xffff7f7f),
splashColor: Colors.transparent,
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0)),
),
// Loading
Positioned(
child: isLoading
? Container(
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
),
color: Colors.white.withOpacity(0.8),
)
: Container(),
),
],
));
}
}
Use a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){
public int compare(DataNode o1, DataNode o2){
if(o1.degree == o2.degree)
return 0;
return o1.degree < o2.degree ? -1 : 1;
}
});
In the controller, you need to add the login object as an attribute of the model:
model.addAttribute("login", new Login());
Like this:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String displayLogin(Model model) {
model.addAttribute("login", new Login());
return "login";
}
Are methods using FOR XML PATH like below really that slow? Itzik Ben-Gan writes that this method has good performance in his T-SQL Querying book (Mr. Ben-Gan is a trustworthy source, in my view).
create table #t (id int, name varchar(20))
insert into #t
values (1, 'Matt'), (1, 'Rocks'), (2, 'Stylus')
select id
,Names = stuff((select ', ' + name as [text()]
from #t xt
where xt.id = t.id
for xml path('')), 1, 2, '')
from #t t
group by id
One simple way to get rid of the overwriting issue is to use File.AppendText
to append line at the end of the file as
void Main()
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText("file.txt"))
{
string first = reader[0].ToString();
string second=image.ToString();
string csv = string.Format("{0},{1}\n", first, second);
sw.WriteLine(csv);
}
}
To clone a branch without fetching other branches:
mkdir $BRANCH
cd $BRANCH
git init
git remote add -t $BRANCH -f origin $REMOTE_REPO
git checkout $BRANCH
It might be, because your span element sets is side as width as its content. if you have a div with 500px width and text-align center, and you enter a span tag it should be aligned in the center. So your problem might be a CSS one. Install Firebug at Firefox and check the style attributes your span or div object has.
as @Aurand to said, tomcat is not running. you can use the
ps -ef |grep java | grep tomcat
command to ignore the ps
programs.
worked for me in the shell scripte files.
Note that in Swift, you can just do
let testBool: Bool = true
NSLog("testBool = %@", testBool.description)
This will log testBool = true
use myString.c_str()
if you want a c-like string (const char*
) to use with printf
thanks
If you want just the summary of the exception use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to see the whole stack trace (usually better for debugging) use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Another method I sometime use is:
private DoSomthing(int arg1, int arg2, out string errorMessage)
{
int result ;
errorMessage = String.Empty;
try
{
//do stuff
int result = 42;
}
catch (Exception ex)
{
errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
result = -1;
}
return result;
}
And In your form you will have something like:
string ErrorMessage;
int result = DoSomthing(1, 2, out ErrorMessage);
if (!String.IsNullOrEmpty(ErrorMessage))
{
MessageBox.Show(ErrorMessage);
}
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
In my case I tried to remove file on github after few commits but save on computer
git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch file_name_with_path' HEAD
git push --force -u origin master
and later this file was ignored
I was also getting exact same error and using AsyncTask :
`java.lang.IllegalStateException:` The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131296334, class android.widget.ListView) with Adapter... etc
I solved it by puttingadapter.notifyDataSetChanged();
at the bottom of my UI thread, that is my AsyncTask onPostExecute method. Like this :
protected void onPostExecute(Void aVoid) {
all my other stuff etc...
all my other stuff etc...
adapter.notifyDataSetChanged();
}
});
}
Now my app works.
EDIT : In fact, my app still crashed about every 1 in 10 times, giving the same error.
Eventually I came across runOnUiThread
on a previous post, which I thought could be useful. So I put it in my doInBackground method, like this :
@Override
protected Void doInBackground(Void... voids) {
runOnUiThread(new Runnable() {
public void run() { etc... etc...
And I removed the adapter.notifyDataSetChanged();
method. Now, my app never crashes.
Here are slightly different options to accomplish the task at hand.
using toMap
:
list.stream()
.collect(Collectors.toMap(Function.identity(), e -> 1, Math::addExact));
using Map::merge
:
Map<String, Integer> accumulator = new HashMap<>();
list.forEach(s -> accumulator.merge(s, 1, Math::addExact));
You can define you own object prototype, just before its usage or at the beginning of your code.
The definition should look like this:
Object.prototype.hasOwnProperties = function()_x000D_
{ _x000D_
for (var k in this)_x000D_
{ _x000D_
if ( this.hasOwnProperty(k) )_x000D_
{ _x000D_
return true;_x000D_
} _x000D_
}_x000D_
return false;_x000D_
}
_x000D_
Here is a usage example:
var a = {};_x000D_
_x000D_
while ( a.status !== "finished" )_x000D_
{ _x000D_
if ( status === "processing" )_x000D_
{_x000D_
a.status = "finished"; _x000D_
}_x000D_
_x000D_
if ( status === "starting" )_x000D_
{_x000D_
a.status = "processing"; _x000D_
}_x000D_
_x000D_
if ( !a.hasOwnProperties() )_x000D_
{_x000D_
a.status = "starting";_x000D_
}_x000D_
}
_x000D_
Enjoy! :-)
In App.js
add the below code and try
window.location.pathname
var UTF8ToBin=function(f){for(var a,c=0,d=(f=unescape(encodeURIComponent(f))).length,b="";c<d;c++){for(a=f.charCodeAt(c).toString(2);a.length%8!=0;){a="0"+a}b+=a}return b},binToUTF8=function(f){for(var a,c=0,d=f.length,b="";c<d;c+=8){b+="%"+((a=parseInt(f.substr(c,8),2).toString(16)).length%2==0?a:"0"+a)}return decodeURIComponent(b)};
This is a small minified JavaScript Code to convert UTF8 to Binary and Vice versa.
Here is a working example:
@echo off
:ask
@echo echo Would you like to use developer mode?(Y/N)
set INPUT=
set /P INPUT=Type input: %=%
If /I "%INPUT%"=="y" goto yes
If /I "%INPUT%"=="n" goto no
goto ask
:yes
@echo you select yes
goto exit
:no
@echo you select no
goto exit
:exit
@pause
You have to reimplement it using <xsl:choose>
tag:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2> mooooooooooooo </h2>
</xsl:when>
<xsl:otherwise>
<h2> dooooooooooooo </h2>
</xsl:otherwise>
</xsl:choose>
Angular4
Instead of
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
use
this.fileInput.nativeElement.dispatchEvent(event);
because invokeElementMethod
won't be part of the renderer anymore.
Angular2
Use ViewChild with a template variable to get a reference to the file input, then use the Renderer to invoke dispatchEvent
to fire the event:
import { Component, Renderer, ElementRef, ViewChild } from '@angular/core';
@Component({
...
template: `
...
<input #fileInput type="file" id="imgFile" (click)="onChange($event)" >
...`
})
class MyComponent {
@ViewChild('fileInput') fileInput:ElementRef;
constructor(private renderer:Renderer) {}
showImageBrowseDlg() {
// from http://stackoverflow.com/a/32010791/217408
let event = new MouseEvent('click', {bubbles: true});
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
}
}
Update
Since direct DOM access isn't discouraged anymore by the Angular team this simpler code can be used as well
this.fileInput.nativeElement.click()
See also https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
String u = request.getParameter("username");
String p = request.getParameter("password");
try {
st = con.createStatement();
String sql;
sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
+ p + "'";
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/home.jsp");
requestDispatcher.forward(request, response);
} else {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/invalidLogin.jsp");
requestDispatcher.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
rs.close();
ps.close();
con.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have just wasted 1/2 a day trying to get either a 0
, null
, false
to return from strops
!
Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding:
Concept take a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done.
Anyway here was the basis of the cosing:
if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ())
{
do this
} else {
or that
}
{
echo strpos(mydomain.co.uk, mydomain);
if ( strpos(mydomain, xmas) == null )
{
echo "\n1 is null";
}
if ( (strpos(mydomain.co.uk, mydomain)) == 0 )
{
echo "\n2 is 0";
} else {
echo "\n2 Something is WRONG";
}
if ( (mydomain.co.uk, mydomain)) != 0 )
{
echo "\n3 is 0";
} else {
echo "\n3 it is not 0";
}
if ( (mydomain.co.uk, mydomain)) == null )
{
echo "\n4 is null";
} else {
echo "\n4 Something is WRONG";
}
}
FINALLY after reading this Topic, I found that this worked!!!
{
if ((mydomain.co.uk, mydomain)) !== false )
{
echo "\n5 is True";
} else {
echo "\n5 is False";
}
}
Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as false
, as its also can be a NULL
day!
After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as False
, NULL
and 0
are not all the same as True or False or NULL
?
You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.
int main()
{
int array[11];
printf("Write down your ID number!\n");
for(int i=0;i<id_length;i++)
scanf("%d", &array[i]);
if (array[0]==1)
{
printf("\nThis person is a male.");
}
else if (array[0]==2)
{
printf("\nThis person is a female.");
}
return 0;
}
Try this:
[(i, j) for i, j in enumerate(mylist)]
You need to put i,j
inside a tuple for the list comprehension to work. Alternatively, given that enumerate()
already returns a tuple, you can return it directly without unpacking it first:
[pair for pair in enumerate(mylist)]
Either way, the result that gets returned is as expected:
> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
A few
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask
Here's some concise code for Euclidean distance in Python given two points represented as lists in Python.
def distance(v1,v2):
return sum([(x-y)**2 for (x,y) in zip(v1,v2)])**(0.5)
A singular intelligent thought occurred to me after a long day of repair/rebuild/upgrades of the SDK/NDK & JDK. The environment vars need examined, as the fix for my AVD 'GalaxyS3' missing kernel file was to expand the system-images reference to absolute.
image.sysdir.1=C:\Android\sdk\system-images\android-19\armeabi-v7a\
Adding the "C:....sdk\" to the 'image.sysdir.1=' entry in the 'workspace'.android\avd\GalaxyS3.avd\config.ini file solved the problem (for now).
The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.
Adding to Mike McAllister's pretty-thorough answer...
Materialized views can only be set to refresh automatically through the database detecting changes when the view query is considered simple by the compiler. If it's considered too complex, it won't be able to set up what are essentially internal triggers to track changes in the source tables to only update the changed rows in the mview table.
When you create a materialized view, you'll find that Oracle creates both the mview and as a table with the same name, which can make things confusing.
Why can't operator<<
function for streaming objects to std::cout
or to a file be a member function?
Let's say you have:
struct Foo
{
int a;
double b;
std::ostream& operator<<(std::ostream& out) const
{
return out << a << " " << b;
}
};
Given that, you cannot use:
Foo f = {10, 20.0};
std::cout << f;
Since operator<<
is overloaded as a member function of Foo
, the LHS of the operator must be a Foo
object. Which means, you will be required to use:
Foo f = {10, 20.0};
f << std::cout
which is very non-intuitive.
If you define it as a non-member function,
struct Foo
{
int a;
double b;
};
std::ostream& operator<<(std::ostream& out, Foo const& f)
{
return out << f.a << " " << f.b;
}
You will be able to use:
Foo f = {10, 20.0};
std::cout << f;
which is very intuitive.
You can use jquery's load function here.
$("#your_element_id").load("file_name.html");
If you need more info, here is the link.
Why don't you use the MySQL built in password hasher:
http://dev.mysql.com/doc/refman/5.1/en/password-hashing.html
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
for comparison you could something like this:
select id from PassworTable where Userid='<userid>' and Password=PASSWORD('<password>')
and if it returns a value then the user is correct.
Posix is more as an OS, it is an "OS standard". You can imagine it as an imaginary OS, which actually doesn't exist, but it has a documentation. These papers are the "posix standard", defined by the IEEE, which is the big standard organization of the USA. The OSes implementing this specification are "Posix-compliant".
Government regulations prefer Posix-compliant solutions in their investments, thus being Posix-compliant has a significant financial advantage, particularly for the big IT companies of the USA.
The reward for an OS being fully posix compliant, that it is a guarantee that it will compile and run all Posix-compliant applications seamlessly.
Linux is the most well-known one. OSX, Solaris, NetBSD and Windows NT play here as well. Free- and OpenBSD are only "nearly" Posix-compliant. The posix-compliance of the WinNT is only a pseudo-solution to avoid this government regulation above.
Why not just: z/
That will highlight the current word under cursor and any other occurrences. And you don't have to give a separate command for each item you're searching for. Perhaps that's not available in the unholy gvim? It's in vim by default.
* is only good if you want the cursor to move to the next occurrence. When comparing two things visually you often don't want the cursor to move, and it's annoying to hit the * key every time.
I had the same issue as the poster. Basically I'm running a dashboard, and I have a bunch of named ranges that are populated with return values from some UDFs. On the dashboard, there are some pie charts with data series tied to cells which contain these named ranges (the problem also occurs if the data series target cells contain the UDFs directly, bypassing the named ranges).
I change a cell value which contains, for example, the date range to base the dashboard on, and the named ranges and UDFs are forced to calculate. However, the pie charts do not update--for some reason, other types of charts do. And by the way, these are chart objects, not chart sheets. Anyway, let's cut to the solution:
I didn't want to visibly change the chart title or some other aspect of it, and anyway I noticed this wasn't updating my charts consistently. Sometimes the first time I triggered the calculation the pies would update, but with subsequent calculations the pies would not. I did notice, however, that every time I made a change in the code my dashboard worked. Thus:
Solution:
With ActiveWorkbook.VBProject.VBComponents("ThisWorkbook").CodeModule
.AddFromString "'test"
.DeleteLines 1
End With
If you're using the Workbook module (I wasn't in this case), just create a new module and reference that instead.