Here is a presentation on this topic that you might find interesting:
http://www.bytemining.com/2010/08/taking-r-to-the-limit-part-ii-large-datasets-in-r/
I haven't tried the discussed things myself, but the bigmemory
package seems very useful
Just add a "custom" stylesheet which is loaded after Bootstrap´s stylesheet. So the class definitions are overloaded.
In this stylesheet declare the alignment as follows:
.table .text-right {text-align: right}
.table .text-left {text-align: left}
.table .text-center {text-align: center}
Now you are able to use the "common" alignment conventions for td and th elements.
sudo perl -MCPAN -e 'install Foo'
You could assign the comparison of the property to "1"
obj["isChecked"] = (obj["isChecked"]==="1");
This only evaluates for a String value of "1"
though. Other variables evaulate to false like an actual typeof number
would be false. (i.e. obj["isChecked"]=1
)
If you wanted to be indiscrimate about "1"
or 1
, you could use:
obj["isChecked"] = (obj["isChecked"]=="1");
console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false
Same concept in PHP
$obj["isChecked"] = ($obj["isChecked"] == "1");
The same operator limitations as stated above for JavaScript apply.
The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:
!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false
echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false
create or replace procedure my_proc( v_number IN number,p_rc OUT SYS_REFCURSOR )
as
begin
open p_rc
for select 1 col1
from dual;
end;
/
and then write a function lie this which calls your stored procedure
create or replace function my_proc_test(v_number IN NUMBER) RETURN sys_refcursor
as
p_rc sys_refcursor;
begin
my_proc(v_number,p_rc);
return p_rc;
end
/
then you can run this SQL query in the SQLDeveloper editor.
SELECT my_proc_test(3) FROM DUAL;
you will see the result in the console right click on it and cilck on single record view and edit the result you can see the all the records that were returned by the ref cursor.
I was trying to compare A-B columns and highlight equal text, but usinng the obove fomrulas some text did not match at all. So I used form (VBA macro to compare two columns and color highlight cell differences) codes and I modified few things to adapt it to my application and find any desired column (just by clicking it). In my case, I use large and different numbers of rows on each column. Hope this helps:
Sub ABTextCompare()
Dim Report As Worksheet
Dim i, j, colNum, vMatch As Integer
Dim lastRowA, lastRowB, lastRow, lastColumn As Integer
Dim ColumnUsage As String
Dim colA, colB, colC As String
Dim A, B, C As Variant
Set Report = Excel.ActiveSheet
vMatch = 1
'Select A and B Columns to compare
On Error Resume Next
Set A = Application.InputBox(Prompt:="Select column to compare", Title:="Column A", Type:=8)
If A Is Nothing Then Exit Sub
colA = Split(A(1).Address(1, 0), "$")(0)
Set B = Application.InputBox(Prompt:="Select column being searched", Title:="Column B", Type:=8)
If A Is Nothing Then Exit Sub
colB = Split(B(1).Address(1, 0), "$")(0)
'Select Column to show results
Set C = Application.InputBox("Select column to show results", "Results", Type:=8)
If C Is Nothing Then Exit Sub
colC = Split(C(1).Address(1, 0), "$")(0)
'Get Last Row
lastRowA = Report.Cells.Find("", Range(colA & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column A
lastRowB = Report.Cells.Find("", Range(colB & 1), xlFormulas, xlByRows, xlPrevious).Row - 1 ' Last row in column B
Application.ScreenUpdating = False
'***************************************************
For i = 2 To lastRowA
For j = 2 To lastRowB
If Report.Cells(i, A.Column).Value <> "" Then
If InStr(1, Report.Cells(j, B.Column).Value, Report.Cells(i, A.Column).Value, vbTextCompare) > 0 Then
vMatch = vMatch + 1
Report.Cells(i, A.Column).Interior.ColorIndex = 35 'Light green background
Range(colC & 1).Value = "Items Found"
Report.Cells(i, A.Column).Copy Destination:=Range(colC & vMatch)
Exit For
Else
'Do Nothing
End If
End If
Next j
Next i
If vMatch = 1 Then
MsgBox Prompt:="No Itmes Found", Buttons:=vbInformation
End If
'***************************************************
Application.ScreenUpdating = True
End Sub
public class UrlContent{
public static void main(String[] args) {
URL url;
try {
// get URL content
String a="http://localhost:8080/TestWeb/index.jsp";
url = new URL(a);
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AES is the currently accepted standard algorithm to use (hence the name Advanced Encryption Standard).
The rest are not.
When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:
9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned
, then modular arithmetic takes place.
Now look at the following operations storing the result as an unsigned int
:
unsigned int five = 5, seven = 7;
unsigned int a = five - seven; // a = (-2 % 2^32) = 4294967294
int one = 1, six = 6;
unsigned int b = one - six; // b = (-5 % 2^32) = 4294967291
When you want to make sure that the result is signed
, then stored it into signed
variable or cast it to signed
. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs()
function defined in stdlib.h
:
int c = five - seven; // c = -2
int d = abs(five - seven); // d = 2
Be very careful, especially while writing conditions, because:
if (abs(five - seven) < seven) // = if (2 < 7)
// ...
if (five - seven < -1) // = if (-2 < -1)
// ...
if (one - six < 1) // = if (-5 < 1)
// ...
if ((int)(five - seven) < 1) // = if (-2 < 1)
// ...
but
if (five - seven < 1) // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
// ...
if (one - six < five) // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
// ...
If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:
<div class="text_div">
This div <span>contains</span> some text.
</div>
You can then easily change its contents with jQuery:
$('.text_div > span').text('hello everyone');
If you can't wrap it in a span tag, you could use regular expressions.
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
Just wanted to show that there is no performance difference between the 2 main ways of doing it:
df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))
def loc():
df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
def replace():
df2['A'].replace(
to_replace=2,
value=5,
inplace=True
)
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
The async is used with a function to makes it into an asynchronous function. The await keyword is used to invoke an asynchronous function synchronously. The await keyword holds the JS engine execution until promise is resolved.
We should use async & await only when we want the result immediately. Maybe the result is being returned from the function or getting used in the next line.
From Python 3.0 changelog;
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
From the Python 3 email documentation it can be seen that io.StringIO
should be used instead:
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
Reference: https://docs.python.org/3/library/io.html
In swift 4 you can write it smarter:
let d = [ 1 : "hello", 2 : "bye", -1 : "foo" ]
d = [Int : String](uniqueKeysWithValues: d.sorted{ $0.key < $1.key })
Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337
You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties
Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0
only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden
, you can eliminate this problem:
div {_x000D_
width:100px;_x000D_
height:20px;_x000D_
}_x000D_
.menu {_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
_x000D_
background:#eee;_x000D_
width:100px;_x000D_
margin:0;_x000D_
padding:5px;_x000D_
list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
visibility:visible;_x000D_
opacity:1;_x000D_
}
_x000D_
<div>_x000D_
<a href="#">Open Menu</a>_x000D_
<ul class="menu">_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
<li><a href="#">Item</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
For WampServer, click on its tray icon and then in the popup cascading menu select
MySQL | MySQL settings | datadir
----FirstActivity.java-----
package com.mindscripts.eid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FirstActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button orderButton = (Button) findViewById(R.id.order);
orderButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this,OrderScreen.class);
startActivity(intent);
}
});
}
}
---OrderScreen.java---
package com.mindscripts.eid;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class OrderScreen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_class);
Button orderButton = (Button) findViewById(R.id.end);
orderButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
---AndroidManifest.xml----
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mindscripts.eid"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OrderScreen"></activity>
</application>
it is solved in react-router-dom 4.4.0 see: Route's proptypes fail
now it is beta, or just wait for final release.
npm install [email protected] --save
Readonly textbox in Asp.net
<asp:TextBox ID="t" runat="server" Style="margin-left: 20px; margin-top: 24px;"
Width="335px" Height="41px" ReadOnly="true"></asp:TextBox>
Here's a reworking of your sample to get you started.
your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.
the sample below also uses the more standard naming OnXxx for the method that raises the event.
the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.
.
public enum MyEvents{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEventArgs(MyEvents myEvents)
{
MyEvents = myEvents;
}
public MyEvents MyEvents { get; private set; }
}
public static class MyClass
{
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents myEvents)
{
OnMyEvent(new MyEventArgs(myEvents));
}
protected static void OnMyEvent(MyEventArgs e)
{
if (EventTriggered != null)
{
// Normally the first argument (sender) is "this" - but your example
// uses a static event, so I'm passing null instead.
// EventTriggered(this, e);
EventTriggered(null, e);
}
}
}
Possible Variation to my other answer for random chars
In order to get random Char
s, you can define an extension function like this
fun ClosedRange<Char>.random(): Char =
(Random().nextInt(endInclusive.toInt() + 1 - start.toInt()) + start.toInt()).toChar()
// will return a `Char` between A and Z (incl.)
('A'..'Z').random()
If you're working with JDK > 1.6, use ThreadLocalRandom.current()
instead of Random()
.
For kotlinjs and other use cases which don't allow the usage of java.util.Random
, this answer will help.
As of 1.3, Kotlin comes with its own multiplatform Random generator. It is described in this KEEP. You can now directly use the extension as part of the Kotlin standard library without defining it:
('a'..'b').random()
You can either: Write a server-side script page like PHP, JSP, ASP.net etc to generate this HTML dynamically
or
Setup the web-server that you are using (e.g. Apache) to do exactly that automatically for directories that doesn't contain welcome-page (e.g. index.html)
Specifically in apache read more here: Edit the httpd.conf: http://justlinux.com/forum/showthread.php?s=&postid=502789#post502789 (updated link: https://forums.justlinux.com/showthread.php?94230-Make-apache-list-directory-contents&highlight=502789)
or add the autoindex mod: http://httpd.apache.org/docs/current/mod/mod_autoindex.html
Based on the number of views this question has, it looks like a lot of people are visiting this to see how to set up a job that executes a shell script.
These are the steps to execute a shell script in Jenkins:
In the textarea you can either paste a script or indicate how to run an existing script. So you can either say:
#!/bin/bash
echo "hello, today is $(date)" > /tmp/jenkins_test
or just
/path/to/your/script.sh
Click Save.
Now the newly created job should appear in the main page of Jenkins, together with the other ones. Open it and select Build now to see if it works. Once it has finished pick that specific build from the build history and read the Console output to see if everything happened as desired.
You can get more details in the document Create a Jenkins shell script job in GitHub.
Cameron MacFarland nailed it.
I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.
As a general rule, when on Debian or Ubuntu and you're missing a development file (or any other file for that matter), use apt-file
to figure out which package provides that file:
~ apt-file search openssl/bio.h
android-libboringssl-dev: /usr/include/android/openssl/bio.h
libssl-dev: /usr/include/openssl/bio.h
libwolfssl-dev: /usr/include/cyassl/openssl/bio.h
libwolfssl-dev: /usr/include/wolfssl/openssl/bio.h
A quick glance at each of the packages that are returned by the command, using apt show
will tell you which among the packages is the one you're looking for:
~ apt show libssl-dev
Package: libssl-dev
Version: 1.1.1d-2
Priority: optional
Section: libdevel
Source: openssl
Maintainer: Debian OpenSSL Team <[email protected]>
Installed-Size: 8,095 kB
Depends: libssl1.1 (= 1.1.1d-2)
Suggests: libssl-doc
Conflicts: libssl1.0-dev
Homepage: https://www.openssl.org/
Tag: devel::lang:c, devel::library, implemented-in::TODO, implemented-in::c,
protocol::ssl, role::devel-lib, security::cryptography
Download-Size: 1,797 kB
APT-Sources: http://ftp.fr.debian.org/debian unstable/main amd64 Packages
Description: Secure Sockets Layer toolkit - development files
This package is part of the OpenSSL project's implementation of the SSL
and TLS cryptographic protocols for secure communication over the
Internet.
.
It contains development libraries, header files, and manpages for libssl
and libcrypto.
N: There is 1 additional record. Please use the '-a' switch to see it
A very effective way to virtually eliminate spam is to have a text field that has text in it such as "Remove this text in order to submit the form!" and that text must be removed in order to submit the form.
Upon form validation, if the text field contains the original text, or any random text for that matter, do not submit the form. Bots can read form names and automatically fill in Name and Email fields but do not know if they have to actually remove text from a certain field in order to submit.
I implemented this method on our corporate website and it totally eliminated the spam we were getting on a daily basis. It really works!
xampp in ubuntu
cd /opt/lampp/etc
vim php.ini
Find:
post_max_size = 8M
upload_max_filesize = 2M
max_execution_time = 30
max_input_time = 60
memory_limit = 8M
Change to:
post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M
sudo /opt/lampp/lampp restart
The Zeus editor has support for C/C++ and it also has a form of intellisensing.
It does its intellisensing using the tags information produced by ctags:
Without a GROUP BY clause, any summation will roll all rows up into a single row, so your query will indeed not work. If you grouped by, say, name, and ordered by sum(c_counts+f_counts), then you might get some useful results. But you would have to group by something.
You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here
All this can be done in one simple line:
string jsonString = JsonConvert.SerializeObject(yourObject, Formatting.Indented);
You should be able to use jQuery.ajax
:
Load a remote page using an HTTP request.
And you can specify which method should be used, with the type
option :
The type of request to make ("
POST
" or "GET
"), default is "GET
".
Note: Other HTTP request methods, such asPUT
andDELETE
, can also be used here, but they are not supported by all browsers.
The best is QSpinBox
.
And for a double value use QDoubleSpinBox
.
QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));
If you use the Stopwatch class, you can use the .StartNew() method to reset the watch to 0. So you don't have to call .Reset() followed by .Start(). Might come in handy.
It turns out that you can set window.undefined to whatever you want, and so get object.x !== undefined
when object.x is the real undefined. In my case I inadvertently set undefined to null.
The easiest way to see this happen is:
window.undefined = null;
alert(window.xyzw === undefined); // shows false
Of course, this is not likely to happen. In my case the bug was a little more subtle, and was equivalent to the following scenario.
var n = window.someName; // someName expected to be set but is actually undefined
window[n]=null; // I thought I was clearing the old value but was actually changing window.undefined to null
alert(window.xyzw === undefined); // shows false
Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.
I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.
I looked at using KeychainItemWrapper (the ARC version) but I didn't find its Objective C wrapper as wholesome as desired.
I used this solution by Kishikawa Katsumi, which meant I wrote less code and didn't have to use casts to store NSString values.
Two examples of storing:
[UICKeyChainStore setString:@"kishikawakatsumi" forKey:@"username"];
[UICKeyChainStore setString:@"P455_w0rd$1$G$Z$" forKey:@"password"];
Two examples of retrieving
UICKeyChainStore *store = [UICKeyChainStore keyChainStore];
// or
UICKeyChainStore *store = [UICKeyChainStore keyChainStoreWithService:@"YOUR_SERVICE"];
NSString *username = [store stringForKey:@"username"];
NSString *password = [store stringForKey:@"password"];
If the variable table
contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.
Teaser:
public class SampleViewModel: BaseViewModelStub
{
public string Name { get; set; }
[UiCommand]
public void HelloWorld()
{
MessageBox.Show("Hello World!");
}
[UiCommand]
public void Print()
{
MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
}
public bool CanPrint()
{
return !String.IsNullOrEmpty(Name);
}
}
}
UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.
Unique at any time:
int uniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
this should work
update table_name
set column_b = case
when column_a = 1 then 'Y'
else null
end,
set column_c = case
when column_a = 2 then 'Y'
else null
end,
set column_d = case
when column_a = 3 then 'Y'
else null
end
where
conditions
the question is why would you want to do that...you may want to rethink the data model. you can replace null
with whatever you want.
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
You can't change your password through TortoiseSVN. Authentication to the SVN server has to be changed within the SVN server itself.
How you actually achieve this depends on which SVN Server is housing the repository and how the SVN Server was laid out on your computer.
n a Windows environment, credentials are typically stored in <yoursvnroot>\conf\passwd
.
In a Linux environment it could be as above, or a myriad of other ways depending on how it's hosted.
This is the code that i personally use in my sites. Works outside of the box.
<?php
function breadcrumbs($home = 'Home') {
global $page_title; //global varable that takes it's value from the page that breadcrubs will appear on. Can be deleted if you wish, but if you delete it, delete also the title tage inside the <li> tag inside the foreach loop.
$breadcrumb = '<div class="breadcrumb-container"><div class="container"><ol class="breadcrumb">';
$root_domain = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'].'/';
$breadcrumbs = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
$breadcrumb .= '<li><i class="fa fa-home"></i><a href="' . $root_domain . '" title="Home Page"><span>' . $home . '</span></a></li>';
foreach ($breadcrumbs as $crumb) {
$link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
$root_domain .= $crumb . '/';
$breadcrumb .= '<li><a href="'. $root_domain .'" title="'.$page_title.'"><span>' . $link . '</span></a></li>';
}
$breadcrumb .= '</ol>';
$breadcrumb .= '</div>';
$breadcrumb .= '</div>';
return $breadcrumb;
}
echo breadcrumbs();
?>
The css:
.breadcrumb-container {
width: 100%;
background-color: #f8f8f8;
border-bottom-color: 1px solid #f4f4f4;
list-style: none;
margin-top: 72px;
min-height: 25px;
box-shadow: 0 3px 0 rgba(60, 57, 57, .2)
}
.breadcrumb-container li {
display: inline
}
.breadcrumb {
font-size: 12px;
padding-top: 3px
}
.breadcrumb>li:last-child:after {
content: none
}
.breadcrumb>li:last-child {
font-weight: 700;
font-style: italic
}
.breadcrumb>li>i {
margin-right: 3px
}
.breadcrumb>li:after {
font-family: FontAwesome;
content: "\f101";
font-size: 11px;
margin-left: 3px;
margin-right: 3px
}
.breadcrumb>li+li:before {
font-size: 11px;
padding-left: 3px
}
Feel free to play around with the css padding and margins until you get it right for your own site.
These methods are in ObjectNode
: the division is such that most read operations are included in JsonNode
, but mutations in ObjectNode
and ArrayNode
.
Note that you can just change first line to be:
ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type
or
ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast
In Maven: The Definitive Guide, I wrote about the differences between Maven and Ant in the introduction the section title is "The Differences Between Ant and Maven". Here's an answer that is a combination of the info in that introduction with some additional notes.
A Simple Comparison
I'm only showing you this to illustrate the idea that, at the most basic level, Maven has built-in conventions. Here's a simple Ant build file:
<project name="my-project" default="dist" basedir=".">
<description>
simple example build file
</description>
<!-- set global properties for this build -->
<property name="src" location="src/main/java"/>
<property name="build" location="target/classes"/>
<property name="dist" location="target"/>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<target name="compile" depends="init"
description="compile the source " >
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}"/>
</target>
<target name="dist" depends="compile"
description="generate the distribution" >
<!-- Create the distribution directory -->
<mkdir dir="${dist}/lib"/>
<!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file
-->
<jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
</target>
<target name="clean"
description="clean up" >
<!-- Delete the ${build} and ${dist} directory trees -->
<delete dir="${build}"/>
<delete dir="${dist}"/>
</target>
</project>
In this simple Ant example, you can see how you have to tell Ant exactly what to do. There is a compile goal which includes the javac task that compiles the source in the src/main/java directory to the target/classes directory. You have to tell Ant exactly where your source is, where you want the resulting bytecode to be stored, and how to package this all into a JAR file. While there are some recent developments that help make Ant less procedural, a developer's experience with Ant is in coding a procedural language written in XML.
Contrast the previous Ant example with a Maven example. In Maven, to create a JAR file from some Java source, all you need to do is create a simple pom.xml, place your source code in ${basedir}/src/main/java and then run mvn install from the command line. The example Maven pom.xml that achieves the same results.
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.sonatype.mavenbook</groupId>
<artifactId>my-project</artifactId>
<version>1.0</version>
</project>
That's all you need in your pom.xml. Running mvn install from the command line will process resources, compile source, execute unit tests, create a JAR, and install the JAR in a local repository for reuse in other projects. Without modification, you can run mvn site and then find an index.html file in target/site that contains links to JavaDoc and a few reports about your source code.
Admittedly, this is the simplest possible example project. A project which only contains source code and which produces a JAR. A project which follows Maven conventions and doesn't require any dependencies or customization. If we wanted to start customizing the behavior, our pom.xml is going to grow in size, and in the largest of projects you can see collections of very complex Maven POMs which contain a great deal of plugin customization and dependency declarations. But, even when your project's POM files become more substantial, they hold an entirely different kind of information from the build file of a similarly sized project using Ant. Maven POMs contain declarations: "This is a JAR project", and "The source code is in src/main/java". Ant build files contain explicit instructions: "This is project", "The source is in src/main/java
", "Run javac
against this directory", "Put the results in target/classses
", "Create a JAR from the ....", etc. Where Ant had to be explicit about the process, there was something "built-in" to Maven that just knew where the source code was and how it should be processed.
High-level Comparison
The differences between Ant and Maven in this example? Ant...
Where Maven...
mvn install
. This command told Maven to execute a series of sequence steps until it reached the lifecycle. As a side-effect of this journey through the lifecycle, Maven executed a number of default plugin goals which did things like compile and create a JAR.What About Ivy?
Right, so someone like Steve Loughran is going to read that comparison and call foul. He's going to talk about how the answer completely ignores something called Ivy and the fact that Ant can reuse build logic in the more recent releases of Ant. This is true. If you have a bunch of smart people using Ant + antlibs + Ivy, you'll end up with a well designed build that works. Even though, I'm very much convinced that Maven makes sense, I'd happily use Ant + Ivy with a project team that had a very sharp build engineer. That being said, I do think you'll end up missing out on a number of valuable plugins such as the Jetty plugin and that you'll end up doing a whole bunch of work that you didn't need to do over time.
More Important than Maven vs. Ant
Both files define variable k
as an integer (int
).
As a result, the linker sees two variables with the same name, and is unsure which one it should use if you ever refer to k
.
To fix this, change one of the declarations to:
extern int k;
That means: "k is an integer, declared here, but defined externally (ie. the other file)."
Now there is only one variable k
, that can be properly referred to by two different files.
Are you using a shared hosting provider? It could be master settings overriding anything you're trying to change. Have you tried adding those into your .htaccess?
php_value upload_max_filesize 10M
php_value post_max_size 10M
We can check using ps command
# ps -aux | grep ssh
Will show all shh service running and we can find the tunnel service listed
If you are using PoolingHttpClientConnectionManager procedure above doesn't work, custom SSLContext is ignored. You have to pass socketFactoryRegistry in contructor when creating PoolingHttpClientConnectionManager.
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext, new X509HostnameVerifier() {
@Override
public void verify(String host, SSLSocket ssl)
throws IOException {
}
@Override
public void verify(String host, X509Certificate cert)
throws SSLException {
}
@Override
public void verify(String host, String[] cns,
String[] subjectAlts) throws SSLException {
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create().register("https", sslsf)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm).build();
For me, only catching the mouseenter event was a bit buggy, and the tooltip was not showing/hiding properly. I had to write this, and it is now working perfectly:
$(document).on('mouseenter','[rel=tooltip]', function(){
$(this).tooltip('show');
});
$(document).on('mouseleave','[rel=tooltip]', function(){
$(this).tooltip('hide');
});
Try adding parentheses around the row in table1
e.g.
DELETE
FROM table1
WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);
The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.
Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:
MERGE INTO table1 AS t1
USING table2 AS s1
ON t1.stn = s1.stn
AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;
You could rollback the last migration by
rake db:rollback STEP=1
or rollback this specific migration by
rake db:migrate:down VERSION=<YYYYMMDDHHMMSS>
and edit the file, then run rake db:mirgate
again.
What i came up with is :
1) Make a position:fixed
<div>
with width:100%
(id=zoomdiv)
2) when the page loads :
zoomlevel=$("#zoomdiv").width()*1.0 / screen.availWidth
And it worked for me for ctrl+
and ctrl-
zooms.
or i can add the line to a $(window).onresize()
event to get the active zoom level
Code:
<script>
var zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
$(window).resize(function(){
zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
alert(zoom);
});
</script>
<body>
<div id=zoomdiv style="width:100%;position:fixed;"></div>
</body>
P.S. : this is my first post, pardon any mistakes
If it's 7 days from now that you're looking for, just put:
$date = strtotime("+7 day", time());
echo date('M d, Y', $date);
You could just vectorize the function and then apply it directly to a Numpy array each time you need it:
import numpy as np
def f(x):
return x * x + 3 * x - 2 if x > 0 else x * 5 + 8
f = np.vectorize(f) # or use a different name if you want to keep the original f
result_array = f(A) # if A is your Numpy array
It's probably better to specify an explicit output type directly when vectorizing:
f = np.vectorize(f, otypes=[np.float])
As Edan Maor explained, the quick and dirty way to do it (for [utc-16] encoded .xml files), which you should not do for the resons Edam Maor explained, can done with the following python 2.7 code in case time constraints do not allow you to learn (propper) XML parses.
Assuming you want to:
It worked in python 2.7 modifying an .xml file named "b.xml" located in folder "a", where "a" was located in the "working folder" of python. It outputs the new modified file as "c.xml" in folder "a", without yielding encoding errors (for me) in further use outside of python 2.7.
pattern = '<Author>'
subst = ' <Author>' + domain + '\\' + user_name + '</Author>'
line_index =0 #set line count to 0 before starting
file = io.open('a/b.xml', 'r', encoding='utf-16')
lines = file.readlines()
outFile = open('a/c.xml', 'w')
for line in lines[0:len(lines)]:
line_index =line_index +1
if line_index == len(lines):
#1. & 2. delete last line and adding another line in its place not writing it
outFile.writelines("Write extra line here" + '\n')
# 4. Close root tag:
outFile.writelines("</phonebook>") # as in:
#http://tizag.com/xmlTutorial/xmldocument.php
else:
#3. Substitue a line if it finds the following substring in a line:
pattern = '<Author>'
subst = ' <Author>' + domain + '\\' + user_name + '</Author>'
if pattern in line:
line = subst
print line
outFile.writelines(line)#just writing/copying all the lines from the original xml except for the last.
There are several ways to assign the equal variables.
The easiest one:
grade_1 = grade_2 = grade_3 = average = 0.0
With unpacking:
grade_1, grade_2, grade_3, average = 0.0, 0.0, 0.0, 0.0
With list comprehension and unpacking:
>>> grade_1, grade_2, grade_3, average = [0.0 for _ in range(4)]
>>> print(grade_1, grade_2, grade_3, average)
0.0 0.0 0.0 0.0
Surprised a multiline re.sub has not been suggested (Oh, because you've already split your string... But why?):
>>> import re
>>> a = "Foo\n \nBar\nBaz\n\n Garply\n \n"
>>> print a
Foo
Bar
Baz
Garply
>>> print(re.sub(r'\n\s*\n','\n',a,re.MULTILINE))
Foo
Bar
Baz
Garply
>>>
This is a simple copy, just like you would do with memcpy()
(indeed, some compilers actually produce a call to memcpy()
for that code). There is no "string" in C, only pointers to a bunch a chars. If your source structure contains such a pointer, then the pointer gets copied, not the chars themselves.
Answer is NO. You might have seen an example where somebody would have set something like :
-DArguments=a=1,b=2,c=3,d=4,e=cow
Then the application would parse value of Arguments
property string to get individual values.
In your main
you can get the key values as(Assuming input format is guaranteed):
String line = System.getProperty("Arguments");
if(line != null) {
String str[] = line.split(",");
for(int i=1;i<str.length;i++){
String arr[] = str[i].split("=");
System.out.println("Key = " + arr[0]);
System.out.println("Value = " + arr[1]);
}
}
Also, the -D
should be before the main class or the jar
file in the java command line. Example : java -DArguments=a=1,b=2,c=3,d=4,e=cow MainClass
This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:
ps -o pid -C bash
EDIT: Dependening on the sort of output you expect, pgrep
would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:
pgrep bash
The constructor of unique_ptr<T>
accepts a raw pointer to an object of type T
(so, it accepts a T*
).
In the first example:
unique_ptr<int> uptr (new int(3));
The pointer is the result of a new
expression, while in the second example:
unique_ptr<double> uptr2 (pd);
The pointer is stored in the pd
variable.
Conceptually, nothing changes (you are constructing a unique_ptr
from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:
unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);
Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).
This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:
unique_ptr<int> p = make_unique<int>(42);
Which is both clearer and safer. Now concerning this doubt of yours:
What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.
Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.
This way you do not have to remember doing delete
on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:
{
unique_ptr<int> p = make_unique<int>(42);
// Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete
Now unique_ptr
is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr
is non-copyable.
As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.
I've changed the recursion to iteration.
def MovingTheBall(listOfBalls,position,numCell):
while 1:
stop=1
positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
for i in range(0,len(listOfBalls)):
if positionTmp==listOfBalls[i].pos:
stop=0
if stop==1:
if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
stop=0
else:
return positionTmp
Works good :D
To create a model that references another, use the Ruby on Rails model generator:
$ rails g model wheel car:references
That produces app/models/wheel.rb:
class Wheel < ActiveRecord::Base
belongs_to :car
end
And adds the following migration:
class CreateWheels < ActiveRecord::Migration
def self.up
create_table :wheels do |t|
t.references :car
t.timestamps
end
end
def self.down
drop_table :wheels
end
end
When you run the migration, the following will end up in your db/schema.rb:
$ rake db:migrate
create_table "wheels", :force => true do |t|
t.integer "car_id"
t.datetime "created_at"
t.datetime "updated_at"
end
As for documentation, a starting point for rails generators is Ruby on Rails: A Guide to The Rails Command Line which points you to API Documentation for more about available field types.
I got same exception due to there was no parameterless public contructor
Code was like this:
public class HomeController : Controller
{
private HomeController()
{
_repo = new Repository();
}
changed to
public class HomeController : Controller
{
public HomeController()
{
_repo = new Repository();
}
problem resolved to me.
Be sure to fully qualify your sheets with which workbook they are referencing!
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
I use
android:scaleX="0.70"
android:scaleY="0.70"
to ajust the size of checkbox
then I set margins like this
android:layout_marginLeft="-10dp"
to adjust ths location of the checkbox.
from tkinter import *
from PIL import ImageTk, Image
window = Tk()
window.geometry("1000x300")
path = "1.jpg"
image = PhotoImage(Image.open(path))
panel = Label(window, image = image)
panel.pack()
window.mainloop()
Since Java 8 you can call java.time.Instant.toEpochMilli()
.
For example the call
final long currentTimeJava8 = Instant.now().toEpochMilli();
gives you the same results as
final long currentTimeJava1 = System.currentTimeMillis();
Let's answer this by example:
class NonThreadSafe {
private int count = 0;
public boolean countTo10() {
count = count + 1;
return (count == 10);
}
The countTo10
method adds one to the counter and then returns true if the count has reached 10. It should only return true once.
This will work as long as only one thread is running the code. If two threads run the code at the same time various problems can occur.
For example, if count starts as 9, one thread could add 1 to count (making 10) but then a second thread could enter the method and add 1 again (making 11) before the first thread has a chance to execute the comparison with 10. Then both threads do the comparison and find that count is 11 and neither returns true.
So this code is not thread safe.
In essence, all multi-threading problems are caused by some variation of this kind of problem.
The solution is to ensure that the addition and the comparison cannot be separated (for example by surrounding the two statements by some kind of synchronization code) or by devising a solution that does not require two operations. Such code would be thread-safe.
If you want to know the location of you NPM packages, you should:
which npm // locate a program file in the user's path SEE man which
// OUTPUT SAMPLE
/usr/local/bin/npm
la /usr/local/bin/npm // la: aliased to ls -lAh SEE which la THEN man ls
lrwxr-xr-x 1 t04435 admin 46B 18 Sep 10:37 /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
So given that npm is a NODE package itself, it is installed in the same location as other packages(EUREKA). So to confirm you should cd into node_modules and list the directory.
cd /usr/local/lib/node_modules/
ls
#SAMPLE OUTPUT
@angular npm .... all global npm packages installed
npm root -g
As per @anthonygore 's comment
You have your ssh clone
statement wrong: git clone username [email protected]:root/test.git
That statement would try to clone a repository named username
into the location relative to your current path, [email protected]:root/test.git
.
You want to leave out username
:
git clone [email protected]:root/test.git
For linux ubuntu 18.04:
Go to terminal and command:$ sudo systemctl status tomcat
late answer, but use this package to to check. Package Name: data_connection_checker
in you pubspec.yuml file:
dependencies:
data_connection_checker: ^0.3.4
create a file called connection.dart or any name you want. import the package:
import 'package:data_connection_checker/data_connection_checker.dart';
check if there is internet connection or not:
print(await DataConnectionChecker().hasConnection);
Make sure that the Python dev files come with your OS.
You should not hard code the library and include paths. Instead, use pkg-config, which will output the correct options for your specific system:
$ pkg-config --cflags --libs python2
-I/usr/include/python2.7 -lpython2.7
You may add it to your gcc line:
gcc -Wall utilsmodule.c -o Utilc $(pkg-config --cflags --libs python2)
This will work as long as the image you want to rotate is already in your Properties resources folder.
In Partial Class:
Bitmap bmp2;
OnLoad:
bmp2 = new Bitmap(Tycoon.Properties.Resources.save2);
pictureBox6.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox6.Image = bmp2;
Button or Onclick
private void pictureBox6_Click(object sender, EventArgs e)
{
if (bmp2 != null)
{
bmp2.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox6.Image = bmp2;
}
}
You can use:
adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1
This will start the LAUNCHER Activity of the application using monkeyrunner test tool.
you can use -clean parameter while starting eclipse like
C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_24\bin" -clean
We can also try this solution
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml");
in this the spring automatically finds the class in the class path itself
Hi This can be solved by changing the prorperty of the project in the solution explorer then give false
to 64bit runtime
option
One solution I have used in the past - lets say your site is on mydomain.com, and you need to make an ajax request to foreigndomain.com
Configure an IIS rewrite from your domain to the foreign domain - e.g.
<rewrite>
<rules>
<rule name="ForeignRewrite" stopProcessing="true">
<match url="^api/v1/(.*)$" />
<action type="Rewrite" url="https://foreigndomain.com/{R:1}" />
</rule>
</rules>
</rewrite>
on your mydomain.com site - you can then make a same origin request, and there's no need for any options request :)
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
These are listed in RFC3986. See the Collected ABNF for URI to see what is allowed where and the regex for parsing/validation.
To retrieve your image from byte to base64 string....
Model property:
public byte[] NomineePhoto { get; set; }
public string NomineePhoneInBase64Str
{
get {
if (NomineePhoto == null)
return "";
return $"data:image/png;base64,{Convert.ToBase64String(NomineePhoto)}";
}
}
IN view:
<img style="height:50px;width:50px" src="@item.NomineePhoneInBase64Str" />
It is possible to do this all in pandas directly and is well-suited for a unique ability of the replace
method.
First, let's make a dictionary of dictionaries mapping the columns and their values to their new replacement values.
transform_dict = {}
for col in df.columns:
cats = pd.Categorical(df[col]).categories
d = {}
for i, cat in enumerate(cats):
d[cat] = i
transform_dict[col] = d
transform_dict
{'location': {'New_York': 0, 'San_Diego': 1},
'owner': {'Brick': 0, 'Champ': 1, 'Ron': 2, 'Veronica': 3},
'pets': {'cat': 0, 'dog': 1, 'monkey': 2}}
Since this will always be a one to one mapping, we can invert the inner dictionary to get a mapping of the new values back to the original.
inverse_transform_dict = {}
for col, d in transform_dict.items():
inverse_transform_dict[col] = {v:k for k, v in d.items()}
inverse_transform_dict
{'location': {0: 'New_York', 1: 'San_Diego'},
'owner': {0: 'Brick', 1: 'Champ', 2: 'Ron', 3: 'Veronica'},
'pets': {0: 'cat', 1: 'dog', 2: 'monkey'}}
Now, we can use the unique ability of the replace
method to take a nested list of dictionaries and use the outer keys as the columns, and the inner keys as the values we would like to replace.
df.replace(transform_dict)
location owner pets
0 1 1 0
1 0 2 1
2 0 0 0
3 1 1 2
4 1 3 1
5 0 2 1
We can easily go back to the original by again chaining the replace
method
df.replace(transform_dict).replace(inverse_transform_dict)
location owner pets
0 San_Diego Champ cat
1 New_York Ron dog
2 New_York Brick cat
3 San_Diego Champ monkey
4 San_Diego Veronica dog
5 New_York Ron dog
Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.
For simplicity, I'd suggest using GUI: gitk - The Git repository browser. It's pretty flexible
And you can navigate through the results using the up/down arrows.
I created the Path Length Checker tool for this purpose, which is a nice, free GUI app that you can use to see the path lengths of all files and directories in a given directory.
I've also written and blogged about a simple PowerShell script for getting file and directory lengths. It will output the length and path to a file, and optionally write it to the console as well. It doesn't limit to displaying files that are only over a certain length (an easy modification to make), but displays them descending by length, so it's still super easy to see which paths are over your threshold. Here it is:
$pathToScan = "C:\Some Folder" # The path to scan and the the lengths for (sub-directories will be scanned as well).
$outputFilePath = "C:\temp\PathLengths.txt" # This must be a file in a directory that exists and does not require admin rights to write to.
$writeToConsoleAsWell = $true # Writing to the console will be much slower.
# Open a new file stream (nice and fast) and write all the paths and their lengths to it.
$outputFileDirectory = Split-Path $outputFilePath -Parent
if (!(Test-Path $outputFileDirectory)) { New-Item $outputFileDirectory -ItemType Directory }
$stream = New-Object System.IO.StreamWriter($outputFilePath, $false)
Get-ChildItem -Path $pathToScan -Recurse -Force | Select-Object -Property FullName, @{Name="FullNameLength";Expression={($_.FullName.Length)}} | Sort-Object -Property FullNameLength -Descending | ForEach-Object {
$filePath = $_.FullName
$length = $_.FullNameLength
$string = "$length : $filePath"
# Write to the Console.
if ($writeToConsoleAsWell) { Write-Host $string }
#Write to the file.
$stream.WriteLine($string)
}
$stream.Close()
I got an error when I used
<git config --global http.proxy http://user:password@proxy_addr:port>
The error is that the config file cannot be identified as there is no such file. I changed the command to
<git config --system http.proxy http://user:password@proxy_addr:port>
I am running git on the Windows 7 command prompt.
The above command references the config file in GIT_HOME/etc/gitconfig
.
The --global
option does not.
You can get the TAIL utility from the Windows Server 2003 Resource Kit Tools.
Here are additional details -- Tail command for Windows (CMD).
Take a look at THREE.PointerLockControls
The parseInt solution is the best way to go as it is clear what is happening.
For completeness it is worth mentioning that this can also be done with the + operator
$('.load_more').live("click",function() { //When user clicks
var newcurrentpageTemp = +$(this).attr("id") + 1; //Get the id from the hyperlink
alert(newcurrentpageTemp);
dosomething();
});
take a look at Trim()
which returns a new string with whitespace removed from the beginning and end of the string it is called on.
This is the documentation that you want: http://msdn.microsoft.com/en-us/library/aa292114(VS.71).aspx
I guess the answer is, yes, there is an equivalent that will accomplish the same thing, integrated with Windows security.
Use the none
test (not to be confused with Python's None
object!):
{% if p is not none %}
{{ p.User['first_name'] }}
{% else %}
NONE
{% endif %}
or:
{{ p.User['first_name'] if p is not none else 'NONE' }}
or if you need an empty string:
{{ p.User['first_name'] if p is not none }}
I had the same problem. I used a trigger and in that trigger I called a procedure which computed some values into 2 OUT variables. When I tried to print the result in the trigger body, nothing showed on screen. But then I solved this problem by making 2 local variables in a function, computed what I need with them and finally, copied those variables in your OUT procedure variables. I hope it'll be useful and successful!
As of Node v10.10.0, it is possible to use the new withFileTypes
option for fs.readdir
and fs.readdirSync
in combination with the dirent.isDirectory()
function to filter for filenames in a directory. That looks like this:
fs.readdirSync('./dirpath', {withFileTypes: true})
.filter(item => !item.isDirectory())
.map(item => item.name)
The returned array is in the form:
['file1.txt', 'file2.txt', 'file3.txt']
You aren't being very clear about what you want here, since I think @DWin's is technically correct, given your example code. I think what you really want is this:
y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
# first plot
plot(x, y1,ylim = range(c(y1,y2)))
# Add points
points(x, y2)
DWin's solution was operating under the implicit assumption (based on your example code) that you wanted to plot the second set of points overlayed on the original scale. That's why his image looks like the points are plotted at 1, 101, etc. Calling plot
a second time isn't what you want, you want to add to the plot using points
. So the above code on my machine produces this:
But DWin's main point about using ylim
is correct.
You might want to look at the DecimalFormat
class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57
instead).
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
Code sample:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index
You really don't need jQuery for that:
var doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write('Test');
doc.close();
If you absolutely have to use jQuery, you should use contents()
:
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append('Test');
});
Please don't forget that if you're using jQuery, you'll need to hook into the DOMReady function as follows:
$(function() {
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append('Test');
});
});
here's an example for bash:
usage="$(basename "$0") [-h] [-s n] -- program to calculate the answer to life, the universe and everything
where:
-h show this help text
-s set the seed value (default: 42)"
seed=42
while getopts ':hs:' option; do
case "$option" in
h) echo "$usage"
exit
;;
s) seed=$OPTARG
;;
:) printf "missing argument for -%s\n" "$OPTARG" >&2
echo "$usage" >&2
exit 1
;;
\?) printf "illegal option: -%s\n" "$OPTARG" >&2
echo "$usage" >&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
To use this inside a function:
"$FUNCNAME"
instead of $(basename "$0")
local OPTIND OPTARG
before calling getopts
Quick fix! If you don't want to manually add a space, you can do this:
var a = "I want apple";_x000D_
var b = "an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
(edit: i see that this is actually answered above, sorry!)
You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.
To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white"))
to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL)
would set the background to null for the legend, but it did not. Perhaps worth another question.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
To get rid of the black background in the legend, you need to use the override.aes
argument to the guide_legend
. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
UPLOAD IMAGES WITH PROGRESS BAR
Thought I'd extend upon user3451783's answer and provide one with an HTML5 progress bar. I found that it was very annoying uploading photos without knowing if anything was happening at all.
HTML
<progress></progress>
<div id="summernote"></div>
JS
// initialise editor
$('#summernote').summernote({
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
// send the file
function sendFile(file, editor, welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
data: data,
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
return myXhr;
},
url: root + '/assets/scripts/php/app/uploadEditorImages.php',
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
// update progress bar
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded, max:e.total});
// reset progress on complete
if (e.loaded == e.total) {
$('progress').attr('value','0.0');
}
}
}
#!/usr/bin/perl -w
use strict;
my $url = $ARGV[0];
if($url =~ /([^:]*:\/\/)?([^\/]*\.)*([^\/\.]+)\.[^\/]+/g) {
print $3;
}
Create background drawable like this to show rounded shadow.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Drop Shadow Stack -->
<item>
<shape>
<corners android:radius="4dp" />
<padding android:bottom="1dp" android:left="1dp"
android:right="1dp" android:top="1dp" />
<solid android:color="#00CCCCCC" />
</shape>
</item>
<item>
<shape>
<corners android:radius="4dp" />
<padding android:bottom="1dp" android:left="1dp"
android:right="1dp" android:top="1dp" />
<solid android:color="#10CCCCCC" />
</shape>
</item>
<item>
<shape>
<corners android:radius="4dp" />
<padding android:bottom="1dp" android:left="1dp"
android:right="1dp" android:top="1dp" />
<solid android:color="#20d5d5d5" />
</shape>
</item>
<item>
<shape>
<corners android:radius="6dp" />
<padding android:bottom="1dp" android:left="1dp"
android:right="1dp" android:top="1dp" />
<solid android:color="#30cbcbcb" />
</shape>
</item>
<item>
<shape>
<corners android:radius="4dp" />
<padding android:bottom="1dp" android:left="1dp"
android:right="1dp" android:top="1dp" />
<solid android:color="#50bababa" />
</shape>
</item>
<!-- Background -->
<item>
<shape>
<solid android:color="@color/gray_100" />
<corners android:radius="4dp" />
</shape>
</item>
</layer-list>
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
I don't think you should ever provide the False
value in square brackets (ever), also the column values when they are more than one, then only they are provided as a list! Not like ['one']
.
test = df.sort_values(by='one', ascending = False)
Best css to fit space empty height:
@media print {
body * {
visibility: hidden;
height:0;
}
#section-to-print, #section-to-print * {
visibility: visible;
height:auto;
}
#section-to-print {
position: absolute;
left: 0;
top: 0;
}
}
Another option is to add it on the web.config directly:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
... I found this in here
I had to first choose the new default node version nvm use ***
or nvm install ***
and then remove all in node_modules in the project and npm i
again.
I ran Visual Studio in Administrator mode and it worked for me :) Also, ensure that the app.config file which you are using for writing WCF configuration must be in the project where "ServiceHost" class is used, and not in actual WCF service project.
@OptionsItem(android.R.id.home)
void homeSelected() {
onBackPressed();
}
I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:
Request.AddHeader "Content-Type", "application/json"
Here is the snippet of my code:
Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String
Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac
Set Response = Client.Execute(Request)
You might want to think about using dashes instead of periods.
In Pro ASP MVC 3 Framework they suggest this about making friendly URLs:
Avoid symbols, codes, and character sequences. If you want a word separator, use a dash (/my-great-article). Underscores are unfriendly, and URL-encoded spaces are bizarre (/my+great+article) or disgusting (/my%20great%20article).
It also mentions that URLs should be be easy to read and change for humans. Maybe a reason to think about using a dash instead of a dot also comes from the same book:
Don't use file name extensions for HTML pages (.aspx or .mvc), but do use them for specialized file types (.jpg, .pdf, .zip, etc). Web browsers don't care about file name extensions if you set the MIME type appropriately, but humans still expect PDF files to end with .pdf
So while a period is still readable to humans (though less readable than dashes, IMO), it might still be a bit confusing/misleading depending on what comes after the period. What if someone has a last name of zip? Then the URL will be /John.zip instead of /John-zip, something that can be misleading even to the developer that wrote the application.
Generally, as long as your log4j.properties file is on the classpath, Log4j should just automatically pick it up at JVM startup.
This might be an old question, but here's what I did:
In a .conf file loaded by apache:
<VirtualHost *:80>
ServerName something.com
ProxyPass / http://localhost:8080/
</VirtualHost>
Explanation: Listen on all requests to the local machine's port 80. If I requested "http://something.com/somethingorother
", forward that request to "http://localhost:8080/somethingorother
". This should work for an external visitor because, according to the docs, it maps the remote request to the local server's space.
I'm running Apache 2.4.6-2ubuntu2.2, so I'm not sure how the "-2ubuntu2.2" affects the wider applicability of this answer.
After you make these changes, add the needed modules and restart apache
sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart
A slightly other way of iterating through each column of each line of a CSV-file would be
$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path
foreach($line in $csv)
{
$properties = $line | Get-Member -MemberType Properties
for($i=0; $i -lt $properties.Count;$i++)
{
$column = $properties[$i]
$columnvalue = $line | Select -ExpandProperty $column.Name
# doSomething $column.Name $columnvalue
# doSomething $i $columnvalue
}
}
so you have the choice: you can use either $column.Name
to get the name of the column, or $i
to get the number of the column
Another way :
decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);
I'm using Anaconda on Windows 10, with a GTX 1660 Super. I first installed the CUDA environment following this step-by-step. However there is now a keras-gpu
metapackage available on Anaconda which apparently doesn't require installing CUDA and cuDNN libraries beforehand (mine were already installed anyway).
This is what worked for me to create a dedicated environment named keras_gpu
:
# need to downgrade from tensorflow 2.1 for my particular setup
conda create --name keras_gpu keras-gpu=2.3.1 tensorflow-gpu=2.0
To add on @johncasey 's answer but for TensorFlow 2.0, adding this block works for me:
import tensorflow as tf
from tensorflow.python.keras import backend as K
# adjust values to your needs
config = tf.compat.v1.ConfigProto( device_count = {'GPU': 1 , 'CPU': 8} )
sess = tf.compat.v1.Session(config=config)
K.set_session(sess)
This post solved the set_session
error I got: you need to use the keras backend from the tensorflow path instead of keras itself.
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
For .NET 2.0, here's a nice bit of code I wrote that does exactly what you want, and works for any property on a Control
:
private delegate void SetControlPropertyThreadSafeDelegate(
Control control,
string propertyName,
object propertyValue);
public static void SetControlPropertyThreadSafe(
Control control,
string propertyName,
object propertyValue)
{
if (control.InvokeRequired)
{
control.Invoke(new SetControlPropertyThreadSafeDelegate
(SetControlPropertyThreadSafe),
new object[] { control, propertyName, propertyValue });
}
else
{
control.GetType().InvokeMember(
propertyName,
BindingFlags.SetProperty,
null,
control,
new object[] { propertyValue });
}
}
Call it like this:
// thread-safe equivalent of
// myLabel.Text = status;
SetControlPropertyThreadSafe(myLabel, "Text", status);
If you're using .NET 3.0 or above, you could rewrite the above method as an extension method of the Control
class, which would then simplify the call to:
myLabel.SetPropertyThreadSafe("Text", status);
UPDATE 05/10/2010:
For .NET 3.0 you should use this code:
private delegate void SetPropertyThreadSafeDelegate<TResult>(
Control @this,
Expression<Func<TResult>> property,
TResult value);
public static void SetPropertyThreadSafe<TResult>(
this Control @this,
Expression<Func<TResult>> property,
TResult value)
{
var propertyInfo = (property.Body as MemberExpression).Member
as PropertyInfo;
if (propertyInfo == null ||
[email protected]().IsSubclassOf(propertyInfo.ReflectedType) ||
@this.GetType().GetProperty(
propertyInfo.Name,
propertyInfo.PropertyType) == null)
{
throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
}
if (@this.InvokeRequired)
{
@this.Invoke(new SetPropertyThreadSafeDelegate<TResult>
(SetPropertyThreadSafe),
new object[] { @this, property, value });
}
else
{
@this.GetType().InvokeMember(
propertyInfo.Name,
BindingFlags.SetProperty,
null,
@this,
new object[] { value });
}
}
which uses LINQ and lambda expressions to allow much cleaner, simpler and safer syntax:
myLabel.SetPropertyThreadSafe(() => myLabel.Text, status); // status has to be a string or this will fail to compile
Not only is the property name now checked at compile time, the property's type is as well, so it's impossible to (for example) assign a string value to a boolean property, and hence cause a runtime exception.
Unfortunately this doesn't stop anyone from doing stupid things such as passing in another Control
's property and value, so the following will happily compile:
myLabel.SetPropertyThreadSafe(() => aForm.ShowIcon, false);
Hence I added the runtime checks to ensure that the passed-in property does actually belong to the Control
that the method's being called on. Not perfect, but still a lot better than the .NET 2.0 version.
If anyone has any further suggestions on how to improve this code for compile-time safety, please comment!
I have used the using Newtonsoft.Json as below. Create an object:
public class WorklistSortColumn
{
[JsonProperty(PropertyName = "field")]
public string Field { get; set; }
[JsonProperty(PropertyName = "dir")]
public string Direction { get; set; }
[JsonIgnore]
public string SortOrder { get; set; }
}
Now Call the below method to serialize to Json object as shown below.
string sortColumn = JsonConvert.SerializeObject(worklistSortColumn);
My script:
echo "WARNINGS: $warningsFound WARNINGS FOUND:\n$warningStrings
Output:
WARNING : 2 WARNINGS FOUND:\nWarning, found the following local orphaned signature file:
On my bash script I was getting mad as you until I've just tried:
echo "WARNING : $warningsFound WARNINGS FOUND:
$warningStrings"
Just hit enter where you want to insert that jump. Output now is:
WARNING : 2 WARNINGS FOUND:
Warning, found the following local orphaned signature file:
$("#regTitle")[0].innerHTML = 'Hello World';
if(sessionStorage.reload) {
sessionStorage.reload = true;
// optionnal
setTimeout( () => { sessionStorage.setItem('reload', false) }, 2000);
} else {
sessionStorage.setItem('reload', false);
}
If the POM missing warning is of project's self module, the reason is that you are trying to mistakenly build from a sub-module directory. You need to run the build and install command from root directory of the project.
There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:
const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;
You can check at runtime if the value is valid and if not throw an error, i.e.:
function isToDoDto(obj: any): obj is IToDoDto {
return typeof obj.description === "string" && typeof obj.status === "boolean";
}
@Post()
addToDo(@Response() res, @Request() req) {
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
const toDo = req.body as IToDoDto;
this.toDoService.addToDo(toDo);
return res.status(HttpStatus.CREATED).end();
}
As @huyz pointed out, there's no need for the type assertion because isToDoDto
is a type guard, so this should be enough:
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
this.toDoService.addToDo(req.body);
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}
To sum it up, #pragma
tells the compiler to do stuff. Here are a couple of ways I use it:
#pragma
can be used to ignore compiler warnings. For example, to make GCC shut up about implicit function declarations, you can write:
#pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
An older version of libportable
does this portably.
#pragma once
, when written at the top of a header file, will cause said header file to be included once. libportable
checks for pragma once support.
jquery version of teshguru script for automatically detect input[file] and style
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<style>
#yourBtn{
position: relative;
top: 150px;
font-family: calibri;
width: 150px;
padding: 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px dashed #BBB;
text-align: center;
background-color: #DDD;
cursor:pointer;
}
</style>
<script type="text/javascript">
$(document).ready(function()
{
$('input[type=file]').each(function()
{
$(this).attr('onchange',"sub(this)");
$('<div id="yourBtn" onclick="getFile()">click to upload a file</div>').insertBefore(this);
$(this).wrapAll('<div style="height: 0px;width: 0px; overflow:hidden;"></div>');
});
});
function getFile(){
$('input[type=file]').click();
}
function sub(obj){
var file = obj.value;
var fileName = file.split("\\");
document.getElementById("yourBtn").innerHTML = fileName[fileName.length-1];
}
</script>
</head>
<body>
<?php
var_dump($_FILES);
?>
<center>
<form action="" method="post" enctype="multipart/form-data" name="myForm">
<input id="upfile" name="file" type="file" value="upload"/>
<input type="submit" value='submit' >
</form>
</center>
</body>
</html>
You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.
Rather than using plt.axis('off')
you should use ax.axis('off')
where ax
is a matplotlib.axes
object. To do this for your code you simple need to add axarr[0,0].axis('off')
and so on for each of your subplots.
The code below shows the result (I've removed the prune_matrix
part because I don't have access to that function, in the future please submit fully working code.)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread("stewie.jpg")
f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')
axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')
axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')
axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')
plt.show()
Note: To turn off only the x or y axis you can use set_visible()
e.g.:
axarr[0,0].xaxis.set_visible(False) # Hide only x axis
The classes which you are importing have to be on the classpath. So either the users of your Applet have to have the libraries in the right place or you simply provide those libraries by including them in your jar file. For example like this: Easiest way to merge a release into one JAR file
I would like share an example to understand the usage of stream().filter
Code Snippet: Sample program to identify even number.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public void fetchEvenNumber(){
List<Integer> numberList = new ArrayList<>();
numberList.add(10);
numberList.add(11);
numberList.add(12);
numberList.add(13);
numberList.add(14);
numberList.add(15);
List<Integer> evenNumberListObj = numberList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());
System.out.println(evenNumberListObj);
}
Output will be : [10, 12, 14]
List evenNumberListObj = numberList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());
numberList: it is an ArrayList object contains list of numbers.
java.util.Collection.stream() : stream() will get the stream of collection, which will return the Stream of Integer.
filter: Returns a stream that match the given predicate. i.e based on given condition (i -> i%2 != 0) returns the matching stream.
collect: whatever the stream of Integer filter based in the filter condition, those integer will be put in a list.
I found that the answer by cballou was no longer working in Firefox as of Jan. 2014. Specifically, if (self.pageYOffset)
didn't trigger if the client had scrolled right, but not down - because 0
is a falsey number. This went undetected for a while because Firefox supported document.body.scrollLeft
/Top
, but this is no longer working for me (on Firefox 26.0).
Here's my modified solution:
var getPageScroll = function(document_el, window_el) {
var xScroll = 0, yScroll = 0;
if (window_el.pageYOffset !== undefined) {
yScroll = window_el.pageYOffset;
xScroll = window_el.pageXOffset;
} else if (document_el.documentElement !== undefined && document_el.documentElement.scrollTop) {
yScroll = document_el.documentElement.scrollTop;
xScroll = document_el.documentElement.scrollLeft;
} else if (document_el.body !== undefined) {// all other Explorers
yScroll = document_el.body.scrollTop;
xScroll = document_el.body.scrollLeft;
}
return [xScroll,yScroll];
};
Tested and working in FF26, Chrome 31, IE11. Almost certainly works on older versions of all of them.
static int binaryToInt (String binary){
char []cA = binary.toCharArray();
int result = 0;
for (int i = cA.length-1;i>=0;i--){
//111 , length = 3, i = 2, 2^(3-3) + 2^(3-2)
// 0 1
if(cA[i]=='1') result+=Math.pow(2, cA.length-i-1);
}
return result;
}
Well I encountered a similar problem. The problem for me is that the JS file get loaded before the DOM render happens. So move your <script>
to the end of <body>
tag.
or use defer.
<script defer src="">
so rest assured e.preventDefault()
should work.
Im not a java developer but was using a java app to test a RESTful API. In order for me to fix the error I had to install the intermediate certificates in the webserver in order to make the error go away. I was using lighttpd, the original certificate was installed on an IIS server. Hope it helps. These were the certificates I had missing on the server.
Why are you grouping by? Do you mean order by?
SELECT player_name, player_salary, player_salary * 1.1 AS NewSalary
FROM players
ORDER BY player_salary, player_name;
If you compile multiple files in the same line, ensure that you use javac only once and not for every class file.
Simply,
SELECT TIME(column_name), DATE(column_name)
I use this simple code:
fun getConnectionInfo(): ConnectionInfo {
val cm = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (cm.activeNetwork == null) {
ConnectionInfo.NO_CONNECTION
} else {
if (cm.isActiveNetworkMetered) {
ConnectionInfo.MOBILE
} else {
ConnectionInfo.WI_FI
}
}
}
Reinstalling the software fixes the issue, just make sure not to delete the htdocs folder in the process.
You cannot use items
instead iteritems
in all places in Python. For example, the following code:
class C:
def __init__(self, a):
self.a = a
def __iter__(self):
return self.a.iteritems()
>>> c = C(dict(a=1, b=2, c=3))
>>> [v for v in c]
[('a', 1), ('c', 3), ('b', 2)]
will break if you use items
:
class D:
def __init__(self, a):
self.a = a
def __iter__(self):
return self.a.items()
>>> d = D(dict(a=1, b=2, c=3))
>>> [v for v in d]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __iter__ returned non-iterator of type 'list'
The same is true for viewitems, which is available in Python 3.
Also, since items returns a copy of the dictionary’s list of (key, value)
pairs, it is less efficient, unless you want to create a copy anyway.
In Python 2, it is best to use iteritems
for iteration. The 2to3
tool can replace it with items
if you ever decide to upgrade to Python 3.
There are many ways of solving this problem, and the ones listed above are the most commonly used ways of achieving the solution. I want to add two more ways, just in case someone is looking for an alternative.
index_list = [1,3]
df.take(pos)
#or
df.query('index in @index_list')
check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
main
System.out.println("date : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));
method
public String getMyDate(String myDate, String returnFormat, String myFormat)
{
DateFormat dateFormat = new SimpleDateFormat(returnFormat);
Date date=null;
String returnValue="";
try {
date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
returnValue = dateFormat.format(date);
} catch (ParseException e) {
returnValue= myDate;
System.out.println("failed");
e.printStackTrace();
}
return returnValue;
}
I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.
https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js
If you have 2 routes that perform the same action you can do the following to keep it DRY.
var express = require("express"),
app = express.createServer();
function fooRoute(req, res, next) {
res.end("Foo Route\n");
}
app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);
app.listen(3000);
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class HashTreeSetCompare {
//It is generally faster to add elements to the HashSet and then
//convert the collection to a TreeSet for a duplicate-free sorted
//Traversal.
//really?
O(Hash + tree set) > O(tree set) ??
Really???? Why?
public static void main(String args[]) {
int size = 80000;
useHashThenTreeSet(size);
useTreeSetOnly(size);
}
private static void useTreeSetOnly(int size) {
System.out.println("useTreeSetOnly: ");
long start = System.currentTimeMillis();
Set<String> sortedSet = new TreeSet<String>();
for (int i = 0; i < size; i++) {
sortedSet.add(i + "");
}
//System.out.println(sortedSet);
long end = System.currentTimeMillis();
System.out.println("useTreeSetOnly: " + (end - start));
}
private static void useHashThenTreeSet(int size) {
System.out.println("useHashThenTreeSet: ");
long start = System.currentTimeMillis();
Set<String> set = new HashSet<String>();
for (int i = 0; i < size; i++) {
set.add(i + "");
}
Set<String> sortedSet = new TreeSet<String>(set);
//System.out.println(sortedSet);
long end = System.currentTimeMillis();
System.out.println("useHashThenTreeSet: " + (end - start));
}
}
To get the occurrences of the object from the list directly:
int noOfOccurs = Collections.frequency(animals, "bat");
To get the occurrence of the Object collection inside list, override the equals method in the Object class as:
@Override
public boolean equals(Object o){
Animals e;
if(!(o instanceof Animals)){
return false;
}else{
e=(Animals)o;
if(this.type==e.type()){
return true;
}
}
return false;
}
Animals(int type){
this.type = type;
}
Call the Collections.frequency as:
int noOfOccurs = Collections.frequency(animals, new Animals(1));
Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml
<mvc:view-controller path="/" view-name="index"/>
After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml
file.
change index
with your jsp name.
You can create GitHub repositories via the command line using their Repositories API (http://develop.github.com/p/repo.html)
Check Creating github repositories with command line | Do it yourself Android for example usage.
Take a look at the PropertyPlaceholderConfigurer, I find it clearer to use than annotation.
e.g.
@Configuration
public class PropertiesConfiguration {
@Bean
public PropertyPlaceholderConfigurer properties() {
final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
// ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.setIgnoreResourceNotFound(true);
final List<Resource> resourceLst = new ArrayList<Resource>();
resourceLst.add(new ClassPathResource("myapp_base.properties"));
resourceLst.add(new FileSystemResource("/etc/myapp/overriding.propertie"));
resourceLst.add(new ClassPathResource("myapp_test.properties"));
resourceLst.add(new ClassPathResource("myapp_developer_overrides.properties")); // for Developer debugging.
ppc.setLocations(resourceLst.toArray(new Resource[]{}));
return ppc;
}
This works for me under Excel and a big JSON files using JSON query translated in to native form. https://github.com/VBA-tools/VBA-JSON I am able parse node like "item.something" and get value using simple command:
MsgBox Json("item")("something")
What's nice.
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
It seems that Luiggi Mendoza
and joey rohan
both already answered this, but I think it can be clarified a little.
You can write it as a single if
statement:
if (inventory.contains("bread") && !inventory.contains("water")) {
// do something
}
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
var inp = $("#txt").val();
if(jQuery.trim(inp).length > 0)
{
//do something
}
Removes white space before checking. If the user entered only spaces then this will still work.
Using the jquery data store you can define a 'loaded' state.
<img id="myimage" onload="$(this).data('loaded', 'loaded');" src="lolcats.jpg" />
Then elsewhere you can do:
if ($('#myimage').data('loaded')) {
// loaded, so do stuff
}
Below solution works from API level 14+
Backgrounding ComponentCallbacks2 — Looking at the documentation is not 100% clear on how you would use this. However, take a closer look and you will noticed the onTrimMemory method passes in a flag. These flags are typically to do with the memory availability but the one we care about is TRIM_MEMORY_UI_HIDDEN. By checking if the UI is hidden we can potentially make an assumption that the app is now in the background. Not exactly obvious but it should work.
Foregrounding ActivityLifecycleCallbacks — We can use this to detect foreground by overriding onActivityResumed and keeping track of the current application state (Foreground/Background).
Create our interface that will be implemented by a custom Application class
interface LifecycleDelegate {
fun onAppBackgrounded()
fun onAppForegrounded()
}
Create a class that is going to implement the ActivityLifecycleCallbacks and ComponentCallbacks2 and override onActivityResumed and onTrimMemory methods
// Take an instance of our lifecycleHandler as a constructor parameter
class AppLifecycleHandler(private val lifecycleDelegate: LifecycleDelegate)
: Application.ActivityLifecycleCallbacks, ComponentCallbacks2 // <-- Implement these
{
private var appInForeground = false
// Override from Application.ActivityLifecycleCallbacks
override fun onActivityResumed(p0: Activity?) {
if (!appInForeground) {
appInForeground = true
lifecycleDelegate.onAppForegrounded()
}
}
// Override from ComponentCallbacks2
override fun onTrimMemory(level: Int) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
// lifecycleDelegate instance was passed in on the constructor
lifecycleDelegate.onAppBackgrounded()
}
}
}
Now all we need to do is have our custom Application class implement our LifecycleDelegate interface and register.
class App : Application(), LifeCycleDelegate {
override fun onCreate() {
super.onCreate()
val lifeCycleHandler = AppLifecycleHandler(this)
registerLifecycleHandler(lifeCycleHandler)
}
override fun onAppBackgrounded() {
Log.d("Awww", "App in background")
}
override fun onAppForegrounded() {
Log.d("Yeeey", "App in foreground")
}
private fun registerLifecycleHandler(lifeCycleHandler: AppLifecycleHandler) {
registerActivityLifecycleCallbacks(lifeCycleHandler)
registerComponentCallbacks(lifeCycleHandler)
}
}
In Manifest set the CustomApplicationClass
<application
android:name=".App"
I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:
select * from sales where datediff(dd, salesDate, '20101111') = 0
I actually use it more to find things within the last day or two, so my version looks like this:
select * from sales where datediff(dd, salesDate, getdate()) = 0
And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:
select * from sales where datediff(dd, salesDate, getdate()) <= 7
$suborder['payment_date'] = Carbon::parse($item['created_at'])->format('M d Y');
Also make sure id set in index.html is same as the one you referring to in index.js
index.html:
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
index.js:
ReactDOM.render(<App/>,document.getElementById('root'));
The object can be used as a parameter in Exception.with_traceback()
function:
except Exception as e:
tb = sys.exc_info()
print(e.with_traceback(tb[2]))
My understanding of PhoneGap is that they provide Javascript APIs to much of the iPhone APIs.
Titanium seems easier for a web developer background. It is a simple XML file to create a basic TabView application and then everything in the content area is controlled by HTML / JS. I also know that Titanium does provide some javascript access to some of the frameworks (particularly access to location information, the phone ID, etc).
UPDATE: Titanium added Maps API in version 0.8 of their framework.
If you want a custom equals function to match your elements, you can use this function in ES2015:
function unionEquals(left, right, equals){
return left.concat(right).reduce( (acc,element) => {
return acc.some(elt => equals(elt, element))? acc : acc.concat(element)
}, []);
}
It traverses the left+right array. Then for each element, will fill the accumulator if it does not find that element in the accumulator. At the end, there are no duplicate as specified by the equals
function.
Pretty, but probably not very efficient with thousands of objects.
I've found it in O(n * log n) time by the following method.
Take A[1] and find its position in sorted array B via a binary search. The number of inversions for this element will be one less than the index number of its position in B since every lower number that appears after the first element of A will be an inversion.
2a. accumulate the number of inversions to counter variable num_inversions.
2b. remove A[1] from array A and also from its corresponding position in array B
Here’s an example run of this algorithm. Original array A = (6, 9, 1, 14, 8, 12, 3, 2)
1: Merge sort and copy to array B
B = (1, 2, 3, 6, 8, 9, 12, 14)
2: Take A[1] and binary search to find it in array B
A[1] = 6
B = (1, 2, 3, 6, 8, 9, 12, 14)
6 is in the 4th position of array B, thus there are 3 inversions. We know this because 6 was in the first position in array A, thus any lower value element that subsequently appears in array A would have an index of j > i (since i in this case is 1).
2.b: Remove A[1] from array A and also from its corresponding position in array B (bold elements are removed).
A = (6, 9, 1, 14, 8, 12, 3, 2) = (9, 1, 14, 8, 12, 3, 2)
B = (1, 2, 3, 6, 8, 9, 12, 14) = (1, 2, 3, 8, 9, 12, 14)
3: Rerun from step 2 on the new A and B arrays.
A[1] = 9
B = (1, 2, 3, 8, 9, 12, 14)
9 is now in the 5th position of array B, thus there are 4 inversions. We know this because 9 was in the first position in array A, thus any lower value element that subsequently appears would have an index of j > i (since i in this case is again 1). Remove A[1] from array A and also from its corresponding position in array B (bold elements are removed)
A = (9, 1, 14, 8, 12, 3, 2) = (1, 14, 8, 12, 3, 2)
B = (1, 2, 3, 8, 9, 12, 14) = (1, 2, 3, 8, 12, 14)
Continuing in this vein will give us the total number of inversions for array A once the loop is complete.
Step 1 (merge sort) would take O(n * log n) to execute. Step 2 would execute n times and at each execution would perform a binary search that takes O(log n) to run for a total of O(n * log n). Total running time would thus be O(n * log n) + O(n * log n) = O(n * log n).
Thanks for your help. Writing out the sample arrays on a piece of paper really helped to visualize the problem.
What's this "other information"? An IP address?
In PHP, you use $_SERVER['REMOTE_ADDR']
to get the IP address of the remote client, then you can use gethostbyaddr()
to try and conver that IP into a hostname - but not all IPs have a reverse mapping configured.
If you do not have the pandas and sqlalchemy libraries, import using pip
pip install pandas
pip install sqlalchemy
We can use pandas and sqlalchemy to directly insert into the database
import csv
import pandas as pd
from sqlalchemy import create_engine, types
engine = create_engine('mysql://root:*Enter password here*@localhost/*Enter Databse name here*') # enter your password and database names here
df = pd.read_csv("Excel_file_name.csv",sep=',',quotechar='\'',encoding='utf8') # Replace Excel_file_name with your excel sheet name
df.to_sql('Table_name',con=engine,index=False,if_exists='append') # Replace Table_name with your sql table name
In case of .css method in jQuery for !important rule will not apply.
In this case we should use .attr function.
For Example:
If you want to add style as below:
<div id='voltaic_holder' style='position:absolute;top:-75px !important'>
You should use:
$("#voltaic_holder").attr("style", "position:absolute;top:-75px !important");
Hope it helps some one.
sudo service mysql stop;
sudo service mysql start;
If the above process will not work let's check one the given code above you can stop Mysql server and again start server
If you're having this issue, and try to run bundle exec jekyll serve
per this Jekyll documentation, it'll ask you to run bundle install
, which should prompt you to install any missing gems, which in this case will be rake
. This should resolve your issue.
You may also need to run bundle update
to ensure Gemfile.lock
is referencing the most up-to-date gems.
For what it's worth, it appears your intent is to use the incoming HTTP request to form another HTTP request. Sort of like a gateway. There is an excellent module django-revproxy that accomplishes exactly this.
The source is a pretty good reference on how to accomplish what you are trying to do.
When calling java use the -Xmx Flag for example -Xmx512m for 512 megs for the heap size. You may also want to consider the -xms flag to start the heap larger if you are going to have it grow right from the start. The default size is 128megs.
It depends what you mean by empty.
To check if there is no text (this allows child elements that are empty themselves):
if ($('#leftmenu').text() == '')
To check if there are no child elements or text:
if ($('#leftmenu').contents().length == 0)
Or,
if ($('#leftmenu').html() == '')
Solution #1
Since the original question only wants a simplified solution (and not a faster one), here is a one-line solution:
public boolean contains(int[] array, int key) {
return Arrays.toString(array).matches(".*[\\[ ]" + key + "[\\],].*");
}
Explanation: Javadoc of Arrays.toString()
states the result is enclosed in square brackets and adjacent elements are separated by the characters ", " (a comma followed by a space). So we can count on this. First we convert array
to a string, and then we check if key
is contained in this string. Of course we cannot accept "sub-numbers" (e.g. "1234" contains "23"), so we have to look for patterns where the key
is preceded with an opening bracket or a space, and followed by a closing bracket or a comma.
Note: The used regexp pattern also handles negative numbers properly (whose string representation starts with a minus sign).
Solution #2
This solution is already posted but it contains mistakes, so I post the correct solution:
public boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
Also this solution has a side effect: it modifies the array
(sorts it).
Accept attribute was introduced in the RFC 1867, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).
Other solutions for advanced file uploading require Flash movies like SWFUpload or Java Applets like JUpload.
By using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner
We need the assurance from the IoC container that, before using any bean, the injection of necessary beans must be done.
In setter injection strategy, we trust the IoC container that it will first create the bean first but will do the injection right before using the bean using the setter methods. And the injection is done according to your configuration. If you somehow misses to specify any beans to inject in the configuration, the injection will not be done for those beans and your dependent bean will not function accordingly when it will be in use!
But in constructor injection strategy, container imposes (or must impose) to provide the dependencies properly while constructing the bean. This was addressed as " container-agnostic manner", as we are required to provide dependencies while creating the bean, thus making the visibility of dependency, independent of any IoC container.
Edit:
Q1: And how to prevent container from creating bean by constructor with null
values instead of missing beans?
You have no option to really miss any <constructor-arg>
(in case of Spring), because you are imposed by IoC container to provide all the constructor arguments needed to match a provided constructor for creating the bean. If you provide null
in your <constructor-arg>
intentionally. Then there is nothing IoC container can do or need to do with it!
\n
is a line feed (LF) character, character code 10. \r
is a carriage return (CR) character, character code 13. What they do differs from system to system. On Windows, for instance, lines in text files are terminated using CR followed immediately by LF (e.g., CRLF). On Unix systems and their derivatives, only LF is used. (Macs prior to Mac OS X used CR, but Mac OS X is a *nix derivative and so uses LF.)
In the old days, LF literally did just a line feed on printers (moving down one line without moving where you are horizonally on the page), and CR similarly moved back to the beginning of the line without moving the paper up, hence some systems (like Windows) sending CR (return to the left-hand side) and LF (and feed the paper up).
Because of all this confusion, some output targets will accept multiple line break sequences, so you could see the same effect from either character depending on what you're outputting to.
Your problem is that String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";
is not JSON
.
What you want to do is open an HTTP
connection to "http://www.json-generator.com/j/cglqaRcMSW?indent=4" and parse the JSON response.
String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";
JSONObject jsonObject = new JSONObject(JSON); // <-- Problem here!
Will not open a connection to the site and retrieve the content.
I tested below code and worked ok
Also I'm using library: org.apache.commons.lang.ArrayUtils
public void testConcatArrayString(){
String[] a = null;
String[] b = null;
String[] c = null;
a = new String[] {"1","2","3","4","5"};
b = new String[] {"A","B","C","D","E"};
c = (String[]) ArrayUtils.addAll(a, b);
if(c!=null){
for(int i=0; i<c.length; i++){
System.out.println("c[" + (i+1) + "] = " + c[i]);
}
}
}
Regards
AFAIK you will need at least a little bit of JavaScript...
I would suggest to use jQuery.
You can include this library in one line. And then you can access your div with
$('div').click(function(){
// do stuff here
});
and respond to the click event.
Here is the Swift 3 answer for anyone looking since Swift 3 does not accept "Make".
aView.center = CGPoint(x: 200, Y: 200)
The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>
. The let keyword declares a template input variable that you reference within the template.
Have you looked into ControlsFx Popover control.
import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;
private PopOver item;
final Scene scene = addItemButton.getScene();
final Point2D windowCoord = new Point2D(scene.getWindow()
.getX(), scene.getWindow().getY());
final Point2D sceneCoord = new Point2D(scene.getX(), scene.
getY());
final Point2D nodeCoord = addItemButton.localToScene(0.0,
0.0);
final double clickX = Math.round(windowCoord.getX()
+ sceneCoord.getY() + nodeCoord.getX());
final double clickY = Math.round(windowCoord.getY()
+ sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);
This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.
Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.
You can use query
, i.e.:
b = df.query('a > 1 & a < 5')
This works for me:
var tP = $("img").css("padding").split(" ");
var Padding = {
Top: tP[0] != null ? parseInt(tP[0]) : 0,
Right: tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0),
Bottom: tP[2] != null ? parseInt(tP[2]) : (tP[0] != null ? parseInt(tP[0]) : 0),
Left: tP[3] != null ? parseInt(tP[3]) : (tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0))
};
Result example:
Object {Top: 5, Right: 8, Bottom: 5, Left: 8}
To make a total:
var TotalPadding = Padding.Top + Padding.Right + Padding.Bottom + Padding.Left;
After finding this StackOverflow question/answer
Complex type is getting null in a ApiController parameter
the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.
you can use env variables to setup username and password for mongo
MONGO_INITDB_ROOT_USERNAME
MONGO_INITDB_ROOT_PASSWORD
using simple docker command
docker run -e MONGO_INITDB_ROOT_USERNAME=my-user MONGO_INITDB_ROOT_PASSWORD=my-password mongo
using docker-compose
version: '3.1'
services:
mongo:
image: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: my-user
MONGO_INITDB_ROOT_PASSWORD: my-password
and the last option is to manually access the container and set the user and password inside the mongo docker container
docker exec -it mongo-container bash
now you can use mongo shell command to configure everything that you want
I just installed Drony, is not shareware and it does no require root on cellphone with Android 3.x or above
https://play.google.com/store/apps/details?id=org.sandroproxy.drony
It intercepts the requests and are shown on a LOG
I tried most of these, but they give false positives, all for the same reason.. It is not enough to test the directory for an available permission, you have to check that the logged in user is a member of a group that has that permission. To do this you get the users identity, and check if it is a member of a group that contains the FileSystemAccessRule IdentityReference. I have tested this, works flawlessly..
/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full path to directory </param>
/// <param name="AccessRight">File System right tested</param>
/// <returns>State [bool]</returns>
public static bool DirectoryHasPermission(string DirectoryPath, FileSystemRights AccessRight)
{
if (string.IsNullOrEmpty(DirectoryPath)) return false;
try
{
AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
foreach (FileSystemAccessRule rule in rules)
{
if (identity.Groups.Contains(rule.IdentityReference))
{
if ((AccessRight & rule.FileSystemRights) == AccessRight)
{
if (rule.AccessControlType == AccessControlType.Allow)
return true;
}
}
}
}
catch { }
return false;
}
First, check that whatever you are returning via unicode is a String.
If it is not a string you can change it to a string like this (where self.id is an integer)
def __unicode__(self):
return '%s' % self.id
following which, if it still doesn't work, restart your ./manage.py shell for the changes to take effect and try again. It should work.
Best Regards
I´ve had experienced this problem, the intent
is not null but the information sent via this intent
is not received in onActionActivit()
This is a better solution using getContentResolver() :
private Uri imageUri;
private ImageView myImageView;
private Bitmap thumbnail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
...
...
myImageview = (ImageView) findViewById(R.id.pic);
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "MyPicture");
values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
}
the onActivityResult()
get a bitmap stored by getContentResolver() :
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
myImageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Check my example in github:
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
The best way is to use the category.
You can check the following function. Which has all the conditions to check.
-(BOOL)isNullString:(NSString *)aStr{
if([(NSNull *)aStr isKindOfClass:[NSNull class]]){
return YES;
}
if ((NSNull *)aStr == [NSNull null]) {
return YES;
}
if ([aStr isKindOfClass:[NSNull class]]){
return YES;
}
if(![[aStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]){
return YES;
}
return NO;
}
Emulation is the process of mimicking the outwardly observable behavior to match an existing target. The internal state of the emulation mechanism does not have to accurately reflect the internal state of the target which it is emulating.
Simulation, on the other hand, involves modeling the underlying state of the target. The end result of a good simulation is that the simulation model will emulate the target which it is simulating.
Ideally, you should be able to look into the simulation and observe properties that you would also see if you looked into the original target. In practice, there may some shortcuts to the simulation for performance reasons -- that is, some internal aspects of the simulation may actually be an emulation.
MAME is an arcade game emulator; Hyperterm is a (not very good) terminal emulator. There's no need to model the arcade machine or a terminal in detail to get the desired emulated behavior.
Flight Simulator is a simulator; SPICE is an electronics simulator. They model as much as possible every detail of the target to represent what the target does in reality.
EDIT: Other responses have pointed out that the goal of an emulation is to able to substitute for the object it is emulating. That's an important point. A simulation's focus is more on the modelling of the internal state of the target -- and the simulation does not necessarily lead to emulation. In particular, a simulation may run far slower than real time. SPICE, for example, cannot substitue for an actual electronics circuit (even if assuming there was some kind of magical device that perfectly interfaces electrical circuits to a SPICE simulation.) A simulation Simulation does not always lead to emulation --
Integer
refers to the reference, that is, when comparing references you're comparing if they point to the same object, not value. Hence, the issue you're seeing. The reason it works so well with plain int
types is that it unboxes the value contained by the Integer
.
May I add that if you're doing what you're doing, why have the if
statement to begin with?
mismatch = ( cdiCt != null && cdsCt != null && !cdiCt.equals( cdsCt ) );
From SQL Server 2016 you can just use
DROP TABLE IF EXISTS ##CLIENTS_KEYWORD
On previous versions you can use
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You could also consider truncating the table instead rather than dropping and recreating.
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
Why not:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render
:
onItemClick: function (event) {
this.setState({ selectedItem: event.currentTarget.dataset.id });
//where 'id' = whatever suffix you give the data-* li attribute
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
</ul>
</div>
);
},
You'd want to put those <li>
s into a loop, and you need to make the li.on
and li.off
styles set your background-color
.