You can use Guava's Streams
.
concat(Stream<? extends T>... streams)
method, which will be very short with static imports:
Stream stream = concat(stream1, stream2, of(element));
Xamarin is now owned by Microsoft So it completely free to use on Windows and mac as well.
If you want to remove all whitespace:
$str = preg_replace('/\s+/', '', $str);
See the 5th example on the preg_replace documentation. (Note I originally copied that here.)
Edit: commenters pointed out, and are correct, that str_replace
is better than preg_replace
if you really just want to remove the space character. The reason to use preg_replace
would be to remove all whitespace (including tabs, etc.).
I tried to give a simple explanation in my blogpost.
requires 32 bits (4 bytes) to encode any character. For example, in order to represent the "A" character code-point using this scheme, you'll need to write 65 in 32-bit binary number:
00000000 00000000 00000000 01000001 (Big Endian)
If you take a closer look, you'll note that the most-right seven bits are actually the same bits when using the ASCII scheme. But since UTF-32 is fixed width scheme, we must attach three additional bytes. Meaning that if we have two files that only contain the "A" character, one is ASCII-encoded and the other is UTF-32 encoded, their size will be 1 byte and 4 bytes correspondingly.
Many people think that as UTF-32 uses fixed width 32 bit to represent a code-point, UTF-16 is fixed width 16 bits. WRONG!
In UTF-16 the code point maybe represented either in 16 bits, OR 32 bits. So this scheme is variable length encoding system. What is the advantage over the UTF-32? At least for ASCII, the size of files won't be 4 times the original (but still twice), so we're still not ASCII backward compatible.
Since 7-bits are enough to represent the "A" character, we can now use 2 bytes instead of 4 like the UTF-32. It'll look like:
00000000 01000001
You guessed right.. In UTF-8 the code point maybe represented using either 32, 16, 24 or 8 bits, and as the UTF-16 system, this one is also variable length encoding system.
Finally we can represent "A" in the same way we represent it using ASCII encoding system:
01001101
Consider the Chinese letter "?" - its UTF-8 encoding is:
11101000 10101010 10011110
While its UTF-16 encoding is shorter:
10001010 10011110
In order to understand the representation and how it's interpreted, visit the original post.
XmlWriterSettings settings = new XmlWriterSettings
{
OmitXmlDeclaration = true
};
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
StringBuilder sb = new StringBuilder();
XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));
using (XmlWriter xw = XmlWriter.Create(sb, settings))
{
xs.Serialize(xw, model, ns);
xw.Flush();
return sb.ToString();
}
Can you provide your layout xml? Doing so would allow people to recreate the issue with minimal effort.
You might have to set
android:layout_weight="1"
for the item that you want expanded
Well, instead of passing Application.Current.MainWindow
, just pass a reference to whichever window it is you want: new WindowInteropHelper(this).Handle
and so on.
The problem is
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
Thus scan.close()
closes System.in
.
To fix it you can make
Scanner scan
static
and do not close it in PromptCustomerQty. Code below works.
public static void main (String[] args) {
// Create a customer
// Future proofing the possabiltiies of multiple customers
Customer customer = new Customer("Will");
// Create object for each Product
// (Name,Code,Description,Price)
// Initalize Qty at 0
Product Computer = new Product("Computer","PC1003","Basic Computer",399.99);
Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);
// Define internal variables
// ## DONT CHANGE
ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output
// Add objects to list
ProductList.add(Computer);
ProductList.add(Monitor);
ProductList.add(Printer);
// Ask users for quantities
PromptCustomerQty(customer, ProductList);
// Ask user for payment method
PromptCustomerPayment(customer);
// Create the header
PrintHeader(customer, formatString);
// Create Body
PrintBody(ProductList, formatString);
}
static Scanner scan;
public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList) {
// Initiate a Scanner
scan = new Scanner(System.in);
// **** VARIABLES ****
int qty = 0;
// Greet Customer
System.out.println("Hello " + customer.getName());
// Loop through each item and ask for qty desired
for (Product p : ProductList) {
do {
// Ask user for qty
System.out.println("How many would you like for product: " + p.name);
System.out.print("> ");
// Get input and set qty for the object
qty = scan.nextInt();
}
while (qty < 0); // Validation
p.setQty(qty); // Set qty for object
qty = 0; // Reset count
}
// Cleanup
}
public static void PromptCustomerPayment (Customer customer) {
// Variables
String payment = "";
// Prompt User
do {
System.out.println("Would you like to pay in full? [Yes/No]");
System.out.print("> ");
payment = scan.next();
} while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));
// Check/set result
if (payment.toLowerCase() == "yes") {
customer.setPaidInFull(true);
}
else {
customer.setPaidInFull(false);
}
}
On a side note, you shouldn't use ==
for String comparision, use .equals
instead.
In Alpine linux you should do:
apk add curl-dev python3-dev libressl-dev
I think it'd be okay if you commented it, e.g. // ^ == XOR
.
The javascript library sugar.js (http://sugarjs.com/) has functions to format dates
Example:
Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')
When you have a lot of variables that don't need escaping, you can use an autoescape
block:
{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}
Is there any efficient algorithm other than brute force search to find the three integers?
Yep; we can solve this in O(n2) time! First, consider that your problem P
can be phrased equivalently in a slightly different way that eliminates the need for a "target value":
original problem
P
: Given an arrayA
ofn
integers and a target valueS
, does there exist a 3-tuple fromA
that sums toS
?modified problem
P'
: Given an arrayA
ofn
integers, does there exist a 3-tuple fromA
that sums to zero?
Notice that you can go from this version of the problem P'
from P
by subtracting your S/3 from each element in A
, but now you don't need the target value anymore.
Clearly, if we simply test all possible 3-tuples, we'd solve the problem in O(n3) -- that's the brute-force baseline. Is it possible to do better? What if we pick the tuples in a somewhat smarter way?
First, we invest some time to sort the array, which costs us an initial penalty of O(n log n). Now we execute this algorithm:
for (i in 1..n-2) {
j = i+1 // Start right after i.
k = n // Start at the end of the array.
while (k >= j) {
// We got a match! All done.
if (A[i] + A[j] + A[k] == 0) return (A[i], A[j], A[k])
// We didn't match. Let's try to get a little closer:
// If the sum was too big, decrement k.
// If the sum was too small, increment j.
(A[i] + A[j] + A[k] > 0) ? k-- : j++
}
// When the while-loop finishes, j and k have passed each other and there's
// no more useful combinations that we can try with this i.
}
This algorithm works by placing three pointers, i
, j
, and k
at various points in the array. i
starts off at the beginning and slowly works its way to the end. k
points to the very last element. j
points to where i
has started at. We iteratively try to sum the elements at their respective indices, and each time one of the following happens:
j
closer to the end to select the next biggest number.k
closer to the beginning to select the next smallest number.For each i
, the pointers of j
and k
will gradually get closer to each other. Eventually they will pass each other, and at that point we don't need to try anything else for that i
, since we'd be summing the same elements, just in a different order. After that point, we try the next i
and repeat.
Eventually, we'll either exhaust the useful possibilities, or we'll find the solution. You can see that this is O(n2) since we execute the outer loop O(n) times and we execute the inner loop O(n) times. It's possible to do this sub-quadratically if you get really fancy, by representing each integer as a bit vector and performing a fast Fourier transform, but that's beyond the scope of this answer.
Note: Because this is an interview question, I've cheated a little bit here: this algorithm allows the selection of the same element multiple times. That is, (-1, -1, 2) would be a valid solution, as would (0, 0, 0). It also finds only the exact answers, not the closest answer, as the title mentions. As an exercise to the reader, I'll let you figure out how to make it work with distinct elements only (but it's a very simple change) and exact answers (which is also a simple change).
It causes by that your local branch doesn't track remote branch. As ssasi said,you need use these commands:
git remote update
git fetch
git checkout -b branch_nameA origin/branch_nameB
I solved my problem just now....
Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!
<span class="menu">Menu</span>
.menu {
position: relative;
text-decoration: none;
font-weight: 400;
color: blue;
transition: all .35s ease;
&::before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: yellow;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all 0.3s ease-in-out 0s;
transition: all 0.3s ease-in-out 0s;
}
&:hover {
color: yellow;
&::before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
}
}
You demonstrate a fundamental misunderstanding.
You never created an instance of SimpleClass at all, because you didn't call it.
for count in xrange(4):
x = SimpleClass()
x.attr = count
simplelist.append(x)
Or, if you let the class take parameters, instead, you can use a list comprehension.
simplelist = [SimpleClass(count) for count in xrange(4)]
My installer copied a log.txt file which had been generated on an XP computer. I was looking at that log file thinking it was generated on Vista. Once I fixed my log4net configuration to be "Vista Compatible". Environment.GetFolderPath was returning the expected results. Therefore, I'm closing this post.
The following SpecialFolder path reference might be useful:
Output On Windows Server 2003:
SpecialFolder.ApplicationData: C:\Documents and Settings\blake\Application Data SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Documents and Settings\blake\Desktop SpecialFolder.LocalApplicationData: C:\Documents and Settings\blake\Local Settings\Application Data SpecialFolder.MyDocuments: C:\Documents and Settings\blake\My Documents SpecialFolder.System: C:\WINDOWS\system32`
Output on Vista:
SpecialFolder.ApplicationData: C:\Users\blake\AppData\Roaming SpecialFolder.CommonApplicationData: C:\ProgramData SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Users\blake\Desktop SpecialFolder.LocalApplicationData: C:\Users\blake\AppData\Local SpecialFolder.MyDocuments: C:\Users\blake\Documents SpecialFolder.System: C:\Windows\system32
You could use reduce:
const arr = ["q", "w", "w", "e", "i", "u", "r"]
arr.reduce((acc, cur) => {
if(acc[cur]) {
acc.duplicates.push(cur)
} else {
acc[cur] = true //anything could go here
}
}, { duplicates: [] })
Result would look like this:
{ ...Non Duplicate Values, duplicates: ["w"] }
That way you can do whatever you want with the duplicate values!
You need to use a ServerSocket
. You can find an explanation here.
Expanding on @Benav's answer, my preferred approach is to:
$(SolutionDir)
to the Additional Include DirectoriesNow you can include headers from your referenced projects like so:
#include "OtherProject/Header.h"
Notes:
#include
s, but it sets the correct build dependencies, which you probably want.xampp\phpMyAdmin/config.inc
Find-
$cfg['Servers'][$i]['auth_type'] = 'config'
and change the 'config' to 'http' and that will allow you to type the user name and password when you go to your phpMyAdmin page using your browser.
There are two methods you can use. Both require creating a user and a database.
Using createuser and createdb,
$ sudo -u postgres createuser --superuser $USER
$ createdb mydatabase
$ psql -d mydatabase
Using the SQL administration commands, and connecting with a password over TCP
$ sudo -u postgres psql postgres
And, then in the psql shell
CREATE ROLE myuser LOGIN PASSWORD 'mypass';
CREATE DATABASE mydatabase WITH OWNER = myuser;
Then you can login,
$ psql -h localhost -d mydatabase -U myuser -p <port>
If you don't know the port, you can always get it by running the following, as the postgres
user,
SHOW port;
Or,
$ grep "port =" /etc/postgresql/*/main/postgresql.conf
postgres
userI suggest NOT modifying the postgres
user.
postgres
. You're supposed to have root to get to authenticate as postgres
.postgres
which is the PostgreSQL equivalent of SQL Server's SA
, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.Your problem is that you're not closing your HEREDOC correctly. The line containing END;
must not contain any whitespace afterwards.
In some cases the whole need for declaring a variable can be avoided by using With
statement.
For example,
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogSaveAs)
If fd.Show Then
'use fd.SelectedItems(1)
End If
this can be rewritten as
With Application.FileDialog(msoFileDialogSaveAs)
If .Show Then
'use .SelectedItems(1)
End If
End With
You should use something like this pg_dump --schema=your_schema_name db1
, for details take a look here
Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.
Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.
As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.
Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.
You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.
You need to use max-width
instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.
Here is how to use telnet in bash shell/expect
#!/usr/bin/expect
# just do a chmod 755 one the script
# ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
# if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed
set ip [lindex $argv 0]
set port [lindex $argv 1]
set timeout 5
spawn telnet $ip $port
expect "'^]'."
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
var Data=[{"id": "name2", "label": "Quantity"}]
Pass the string variable into Json parse :
Objdata= Json.parse(Data);
For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using Ad Hoc Helper available from the App Store. For further details on this method, see Craig Hockenberry's Beta testing on iPhone 2.0 article
For jailbroken iPhones, you can use the following method which I have personally tested using the AccelerometerGraph sample app on iPhone OS 3.0.
First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate:
Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate.
Name: iPhone Developer
Certificate Type: Code Signing
Let me override defaults: Yes
Click Continue
Validity: 3650 days
Click Continue
Blank out the Email address field.
Click Continue until complete.
You should see "This root certificate is not trusted". This is expected.
Set the iPhone SDK to allow the self-signed certificate to be used:
sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist
If you have Xcode open, restart it for this change to take effect.
The following steps require openssh
, and uikittools
to be installed first. Replace jasoniphone.local
with the hostname of the target device. Be sure to set your own password on both the mobile
and root
users after installing SSH.
To manually compile and install your application on the phone as a system app (bypassing Apple's installation system):
Project, Set Active SDK, Device and Set Active Build Configuration, Release.
Compile your project normally (using Build, not Build & Go).
In the build/Release-iphoneos
directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device.
scp -r AccelerometerGraph.app root@jasoniphone:/Applications/
Let SpringBoard know the new application has been installed:
ssh [email protected] uicache
This only has to be done when you add or remove applications. Updated applications just need to be relaunched.
To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project.
Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard:
ssh [email protected] rm -r /Applications/AccelerometerGraph.app &&
ssh [email protected] uicache
Use data type LONGBLOB
instead of BLOB
in your database table.
The ^<n>
format allows you to select the nth parent of the commit (relevant in merges). The ~<n>
format allows you to select the nth ancestor commit, always following the first parent. See git-rev-parse's documentation for some examples.
If all login services use PAM, and all login services have session required pam_env.so
in their respective /etc/pam.d/*
configuration files, then all login sessions will have some environment variables set as specified in pam_env
's configuration file.
On most modern Linux distributions, this is all there by default -- just add your desired global environment variables to /etc/security/pam_env.conf
.
This works regardless of the user's shell, and works for graphical logins too (if xdm/kdm/gdm/entrance/… is set up like this).
You can try using open-cv to save the file since it helps with image type conversions internally. The sample code:
import cv2
import numpy as np
def save(encoded_data, filename):
nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
return cv2.imwrite(filename, img)
Then somewhere in your code you can use it like this:
save(base_64_string, 'testfile.png');
save(base_64_string, 'testfile.jpg');
save(base_64_string, 'testfile.bmp');
When dealing with dates in SQL Server, the ISO-8601 format is probably the best way to go, since it just works regardless of your language and culture settings.
In order to INSERT data into a SQL Server table, you don't need any conversion codes or anything at all - just specify your dates as literal strings
INSERT INTO MyTable(DateColumn) VALUES('20090430 12:34:56.790')
and you're done.
If you need to convert a date column to ISO-8601 format on SELECT, you can use conversion code 126 or 127 (with timezone information) to achieve the ISO format.
SELECT CONVERT(VARCHAR(33), DateColumn, 126) FROM MyTable
should give you:
2009-04-30T12:34:56.790
I'm a little late to the party but for future readers.
From what i can tell, you're just wanting to toggle the visibility state right? Why not just use the !
operator?
jxPanel6.setVisible(!jxPanel6.isVisible);
It's not an if statement but I prefer this method for code related to your example.
Better solution
You can check item type in ItemCreated event:
protected void rptSummary_ItemCreated(Object sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Footer) {
e.Item.FindControl(ctrl);
}
if (e.Item.ItemType == ListItemType.Header) {
e.Item.FindControl(ctrl);
}
}
Please check with this documentation.
http://php.net/manual/en/function.error-log.php
Example:
<?php
// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon($username, $password)) {
error_log("Oracle database not available!", 0);
}
// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo())) {
error_log("Big trouble, we're all out of FOOs!", 1,
"[email protected]");
}
// another way to call error_log():
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>
Since it's just false and json object, why don't you check whether it's false, otherwise it must be json.
if(ret == false || ret == "false") {
// json
}
A CASE
statement is an expression, just like a boolean comparison. That means the 'AND' needs to go before the 'CASE' statement, not within it.:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND -- Added the "AND" here
CASE WHEN @day = 'Monday' THEN (Monday = 1) -- Removed "AND"
WHEN @day = 'Tuesday' THEN (Tuesday = 1) -- Removed "AND"
ELSE AND (Wednesday = 1)
END
One use case is to make an ajax
call before the user closes the window or leaves the page. This would be like deleting some temporary records in the database before the user can navigate to another site or closes the browser.
$(window).unload(
function(){
$.ajax({
url: 'your url',
global: false,
type: 'POST',
data: {},
async: false, //blocks window close
success: function() {}
});
});
From react documentation : https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
Erasing state when props change is an Anti Pattern
Since React 16, componentWillReceiveProps is deprecated. From react documentation, the recommended approach in this case is use
ParentComponent
of the ModalBody
will own the start_time
state. This is not my prefer approach in this case since i think the modal should own this state. start_time
state from your ModalBody
and use getInitialState
just like you have already done. To reset the start_time
state, you simply change the key from the ParentComponent
Remove the TO_DATE in the WHERE clause
TO_DATE (alarm_datetime,'DD.MM.YYYY HH24:MI:SS')
and change the code to
alarm_datetime
The error comes from to_date conversion of a date column.
Added Explanation: Oracle converts your alarm_datetime into a string using its nls depended date format. After this it calls to_date with your provided date mask. This throws the exception.
<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">
Add this Code In Your HTML Page...it will disable ...Enter Button..
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable
If we use this query it will return Primary key error
.... So better to choose which columns need to be moved, like
INSERT INTO db1.dbo.TempTable // (List of columns here)
SELECT (Same list of columns here)
FROM db2.dbo.TempTable
I only had one model i wanted to use, so i ended up with the following code:
var JsonImageModel = Newtonsoft.Json.JsonConvert.SerializeObject(Images, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Routes
Use them to define specific routes that aren't managed by controllers.
Controllers
Use them when you want to use traditional MVC architecture
Solution to your problem
You don't register controllers as routes unless you want a specific 'named' route for a controller action.
Rather than create a route for your controllers actions, just register your controller:
Route::controller('user');
Now your controller is registered, you can navigate to http://localhost/mysite/public/user
and your get_index
will be run.
You can also register all controllers in one go:
Route::controller(Controller::detect());
This can do the trick,
function createLog($data){
$file = "Your path/incompletejobs.txt";
$fh = fopen($file, 'a') or die("can't open file");
fwrite($fh,$data);
fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"
$result=mysql_query($qry);
if(!$result){
createLog(mysql_error());
}
You can simply use multiprocessing.Pool
:
from multiprocessing import Pool
def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>
if __name__ == '__main__':
pool = Pool() # Create a multiprocessing Pool
pool.map(process_image, data_inputs) # process data_inputs iterable with pool
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
Using os.path.getsize
:
>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611
The output is in bytes.
Here's a solution:
dates <- c("14.01.2013", "26.03.2014")
# Date format:
dates2 <- strptime(dates, format = "%d.%m.%Y")
dif <- diff(as.numeric(dates2)) # difference in seconds
dif/(60 * 60 * 24 * 7) # weeks
[1] 62.28571
dif/(60 * 60 * 24 * 30) # months
[1] 14.53333
dif/(60 * 60 * 24 * 30 * 3) # quartes
[1] 4.844444
dif/(60 * 60 * 24 * 365) # years
[1] 1.194521
Basically you should not mess the question with answer, because it is confusing.
Then you could specify what convert mean and pick one of this solution
List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));
List<String> valueList = Collections.list(Collections.enumeration(map.values()));
For fedora26 and postgres9.6
First, log as user root then enter to psql by the following commands
$ su postgres
then
$ psql
in psql
find location of hba_file ==> means pg_hba.conf
postgres=# show hba_file ;
hba_file
--------------------------------------
/etc/postgresql/9.6/main/pg_hba.conf
(1 row)
in file pg_hba.conf
change user access to this
host all all 127.0.0.1/32 md5
Short version of (correct) tzaman answer will be (for fresh SVN)
svn switch ^/branches/v1p2p3
--relocate
switch is deprecated anyway, when it needed you'll have to use svn relocate
command
Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)
On Windows, the caret character (^
) must be escaped:
svn switch ^^/branches/v1p2p3
In older Java versions, instead of "::" or lambd, you can use:
public interface Action {
void execute();
}
public class ActionImpl implements Action {
@Override
public void execute() {
System.out.println("execute with ActionImpl");
}
}
public static void main(String[] args) {
Action action = new Action() {
@Override
public void execute() {
System.out.println("execute with anonymous class");
}
};
action.execute();
//or
Action actionImpl = new ActionImpl();
actionImpl.execute();
}
Or passing to the method:
public static void doSomething(Action action) {
action.execute();
}
If someone need to do it with one command after install, run this !
sed -i 's/<policy domain="coder" rights="none" pattern="PDF" \/>/<policy domain="coder" rights="read|write" pattern="PDF" \/>/g' /etc/ImageMagick-6/policy.xml
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
When you call a Linq statement like this:
// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));
You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:
var count = Enumerable.Count(x, s => s.StartsWith("x"));
So the error you are getting above is because the first parameter, source
(which would be x
in the sample above) is null.
Also make sure that you have allowed codeigniter to log the type of messages you want in a config file.
i.e $config['log_threshold'] = [log_level ranges 0-4];
I definitely wouldn't use Block1. It doesn't seem right having the Error block in an IF statement unrelated to Errors.
Blocks 2,3 & 4 I guess are variations of a theme. I prefer the use of Blocks 3 & 4 over 2 only because of a dislike of the GOTO statement; I generally use the Block4 method. This is one example of code I use to check if the Microsoft ActiveX Data Objects 2.8 Library is added and if not add or use an earlier version if 2.8 is not available.
Option Explicit
Public booRefAdded As Boolean 'one time check for references
Public Sub Add_References()
Dim lngDLLmsadoFIND As Long
If Not booRefAdded Then
lngDLLmsadoFIND = 28 ' load msado28.tlb, if cannot find step down versions until found
On Error GoTo RefErr:
'Add Microsoft ActiveX Data Objects 2.8
Application.VBE.ActiveVBProject.references.AddFromFile _
Environ("CommonProgramFiles") + "\System\ado\msado" & lngDLLmsadoFIND & ".tlb"
On Error GoTo 0
Exit Sub
RefErr:
Select Case Err.Number
Case 0
'no error
Case 1004
'Enable Trust Centre Settings
MsgBox ("Certain VBA References are not available, to allow access follow these steps" & Chr(10) & _
"Goto Excel Options/Trust Centre/Trust Centre Security/Macro Settings" & Chr(10) & _
"1. Tick - 'Disable all macros with notification'" & Chr(10) & _
"2. Tick - 'Trust access to the VBA project objects model'")
End
Case 32813
'Err.Number 32813 means reference already added
Case 48
'Reference doesn't exist
If lngDLLmsadoFIND = 0 Then
MsgBox ("Cannot Find Required Reference")
End
Else
For lngDLLmsadoFIND = lngDLLmsadoFIND - 1 To 0 Step -1
Resume
Next lngDLLmsadoFIND
End If
Case Else
MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
End
End Select
On Error GoTo 0
End If
booRefAdded = TRUE
End Sub
IMHO the biggest advantage that REST enables is that of reducing client/server coupling. It is much easier to evolve a REST interface over time without breaking existing clients.
JavaScript-ViewState-Parser:
The parser should work with most non-encrypted ViewStates. It doesn’t handle the serialization format used by .NET version 1 because that version is sorely outdated and therefore too unlikely to be encountered in any real situation.
http://deadliestwebattacks.com/2011/05/29/javascript-viewstate-parser/
Parsing .NET ViewState
A Spirited Peek into ViewState, Part I:
http://deadliestwebattacks.com/2011/05/13/a-spirited-peek-into-viewstate-part-i/
A Spirited Peek into ViewState, Part II:
http://deadliestwebattacks.com/2011/05/25/a-spirited-peek-into-viewstate-part-ii/
Try the --cd= option. Assuming your GIT Bash resides in C:\Program Files\Git it would be:
"C:\Program Files\Git\git-bash.exe" --cd="e:\SomeFolder"
If used inside registry key, folder parameter can be provided with %1:
"C:\Program Files\Git\git-bash.exe" --cd="%1"
It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.
But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.
To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.
This is very old post but if anyone ran into similar problem and need quick answer:
listBox1.IndexFromPoint(new Point(e.X,e.Y))>=0
e.Clicks == 2
this way is a bit more flexible than using all()
:
my_list = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
all_zeros = False if False in [x[2] == 0 for x in my_list] else True
any_zeros = True if True in [x[2] == 0 for x in my_list] else False
or more succinctly:
all_zeros = not False in [x[2] == 0 for x in my_list]
any_zeros = 0 in [x[2] for x in my_list]
There are a several things you need to address to get it working
@ouput
its @code
AddWithValue
since its not supposed to have a value just you Add
.ExecuteNonQuery
if you're not returning rows Try
SqlParameter output = new SqlParameter("@code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
MessageBox.Show(output.Value.ToString());
I have implemented one link
N.B. for processing json, i used jackson. You can remove that also, if you need
What are dex files: Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app.
Reason for this exception: The DEX specification limits the total number of methods that can be referenced within a single DEX file to 65,536 (64K reference limit) —including Android framework methods, library methods, and methods in your own code.
Step 01. Add the following dependency as follows
For Non-Androidx Users,
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
defaultConfig {
minSdkVersion 16
targetSdkVersion 28
multiDexEnabled true //ADD THIS LINE
}
For Androidx Users,
dependencies {
implementation 'androidx.multidex:multidex:2.0.1'
}
defaultConfig {
minSdkVersion 16
targetSdkVersion 28
multiDexEnabled true //ADD THIS LINE
}
Step 02:
After adding those Sync projects and before you run the project make sure to Build a project before the run. otherwise, you will get an exception.
For Python 2.5 and older:
>>> [(a, b, c) for a in [1,2,3] for b in ['a','b'] for c in [4,5]]
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4),
(2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5),
(3, 'b', 4), (3, 'b', 5)]
Here's a recursive version of product()
(just an illustration):
def product(*args):
if not args:
return iter(((),)) # yield tuple()
return (items + (item,)
for items in product(*args[:-1]) for item in args[-1])
Example:
>>> list(product([1,2,3], ['a','b'], [4,5]))
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4),
(2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5),
(3, 'b', 4), (3, 'b', 5)]
>>> list(product([1,2,3]))
[(1,), (2,), (3,)]
>>> list(product([]))
[]
>>> list(product())
[()]
Lets try to understand in a different way.
What may happen if Abstraction is not there and What may happen if Encapsulation is not there.
If Abstraction is not there, then you can say the object is use less. You cannot identify the object nor can you access any functionality of it. Take a example of a TV, if you do not have an option to power on, change channel, increase or decrease volume etc., then what's the use of TV and how do you use it ?
If Encapsulation is not there or not being implemented properly, then you may misuse the object. There by data/components may get misused. Take the same example of TV, If there is no encapsulation done to the volume of TV, then the volume controller may be misused by making it come below or go beyond its limit (0-40/50).
Yes, you can use the two-chord hotkey (Ctrl+K, Ctrl+F if you're using the General profile) to format your selection.
Other formatting options are under menu Edit → Advanced, and like all Visual Studio commands, you can set your own hotkey via menu Tools → Options → Environment → Keyboard (the format selection command is called Edit.FormatSelection
).
Formatting doesn't do anything with blank lines, but it will indent your code according to some rules that are usually slightly off from what you probably want.
Use SpecialCells to delete only the rows that are visible after autofiltering:
ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:
ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")
base directory + your filename
This work for my:
log4j.logger.org.hibernate.type=trace
Also can try:
log4j.category.org.hibernate.type=trace
In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:
.collapse-row.collapsed + tr {
display: none;
}
'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.
Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/
Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly mscorlib
Yes, this technically can go wrong when you execute code on .NET 4.0 instead of .NET 4.5. The attribute was moved from System.Core.dll to mscorlib.dll in .NET 4.5. While that sounds like a rather nasty breaking change in a framework version that is supposed to be 100% compatible, a [TypeForwardedTo] attribute is supposed to make this difference unobservable.
As Murphy would have it, every well intended change like this has at least one failure mode that nobody thought of. This appears to go wrong when ILMerge was used to merge several assemblies into one and that tool was used incorrectly. A good feedback article that describes this breakage is here. It links to a blog post that describes the mistake. It is rather a long article, but if I interpret it correctly then the wrong ILMerge command line option causes this problem:
/targetplatform:"v4,c:\windows\Microsoft.NET\Framework\v4.0.30319"
Which is incorrect. When you install 4.5 on the machine that builds the program then the assemblies in that directory are updated from 4.0 to 4.5 and are no longer suitable to target 4.0. Those assemblies really shouldn't be there anymore but were kept for compat reasons. The proper reference assemblies are the 4.0 reference assemblies, stored elsewhere:
/targetplatform:"v4,C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"
So possible workarounds are to fall back to 4.0 on the build machine, install .NET 4.5 on the target machine and the real fix, to rebuild the project from the provided source code, fixing the ILMerge command.
Do note that this failure mode isn't exclusive to ILMerge, it is just a very common case. Any other scenario where these 4.5 assemblies are used as reference assemblies in a project that targets 4.0 is liable to fail the same way. Judging from other questions, another common failure mode is in build servers that were setup without using a valid VS license. And overlooking that the multi-targeting packs are a free download.
Using the reference assemblies in the c:\program files (x86) subdirectory is a rock hard requirement. Starting at .NET 4.0, already important to avoid accidentally taking a dependency on a class or method that was added in the 4.01, 4.02 and 4.03 releases. But absolutely essential now that 4.5 is released.
To show both:
<div style="height:250px; width:550px; overflow-x:scroll ; overflow-y: scroll; padding-bottom:10px;"> </div>
Hide X Axis:
<div style="height:250px; width:550px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;"> </div>
Hide Y Axis:
<div style="height:250px; width:550px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;"> </div>
SELECT *
FROM sys.all_sql_modules
WHERE definition LIKE '%CreatedDate%'
Thanks.I changed heap space from 2000MB to 1024MB and it worked...
No my friend its very simple, try using this:
AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.
I use this:
function fnIsAppleMobile()
{
if (navigator && navigator.userAgent && navigator.userAgent != null)
{
var strUserAgent = navigator.userAgent.toLowerCase();
var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
if (arrMatches != null)
return true;
} // End if (navigator && navigator.userAgent)
return false;
} // End Function fnIsAppleMobile
var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove
The most secure way to accomplish this is using Int32.TryParse method. See here: http://dotnetperls.com/int-tryparse
You could use a library called requests.
import requests
r = requests.get("http://example.com/foo/bar")
This is quite easy. Then you can do like this:
>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content)
I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447
Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
There is no difference between US ASCII and UTF-8, so there isn't any need to reconvert it.
But here a little hint, if you have trouble with special-chars while recoding.
Add //TRANSLIT after the source-charset-Parameter.
Example:
iconv -f ISO-8859-1//TRANSLIT -t UTF-8 filename.sql > utf8-filename.sql
This helps me with strange types of quotes, which are always breaking the character set reencode process.
This is to merge selected columns from two tables.
If table_1
contains t1_a,t1_b,t1_c..,id,..t1_z
columns,
and table_2
contains t2_a, t2_b, t2_c..., id,..t2_z
columns,
and only t1_a, id, t2_a are required in the final table, then
mergedCSV = table_1[['t1_a','id']].merge(table_2[['t2_a','id']], on = 'id',how = 'left')
# save resulting output file
mergedCSV.to_csv('output.csv',index = False)
By design, dictionaries are not sortable. If you need this capability in a dictionary, look at SortedDictionary instead.
Just in case, you are using the GMaps.js library, which makes it a bit simpler to do things like Geocoding and custom pins, here's how you solve this issue using the techniques learned from the previous answers.
var Gmap = new GMaps({
div: '#main-map', // FYI, this setting property used to be 'el'. It didn't need the '#' in older versions
lat: 51.044308,
lng: -114.0630914,
zoom: 15
});
// To access the Native Google Maps object use the .map property
if(Gmap.map) {
// Disabling mouse wheel scroll zooming
Gmap.map.setOptions({ scrollwheel: false });
}
Instead of RenderViewToString
I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
With recent Maven versions (3) and recent version of the maven compiler plugin (3.7.0), I notice that adding a source folder with the build-helper-maven-plugin
is not required if the folder that contains the source code to add in the build is located in the target
folder or a subfolder of it.
It seems that the compiler maven plugin compiles any java source code located inside this folder whatever the directory that contains them.
For example having some (generated or no) source code in target/a
, target/generated-source/foo
will be compiled and added in the outputDirectory : target/classes
.
enter the android terminal and then you can type the following commands :dumpsys cpuinfo
shell@android:/ $ dumpsys cpuinfo
Load: 0.8 / 0.75 / 1.15
CPU usage from 69286ms to 9283ms ago with 99% awake:
47% 1118/com.wxg.sodproject: 12% user + 35% kernel
1.6% 1225/android.process.media: 1% user + 0.6% kernel
1.3% 263/mpdecision: 0.1% user + 1.2% kernel
0.1% 32747/kworker/u:1: 0% user + 0.1% kernel
0.1% 883/com.android.systemui: 0.1% user + 0% kernel
0.1% 521/system_server: 0.1% user + 0% kernel / faults: 14 minor
0.1% 1826/com.quicinc.trepn: 0.1% user + 0% kernel
0.1% 2462/kworker/0:2: 0.1% user + 0% kernel
0.1% 32649/kworker/0:0: 0% user + 0.1% kernel
0% 118/mmcqd/0: 0% user + 0% kernel
0% 179/surfaceflinger: 0% user + 0% kernel
0% 46/kinteractiveup: 0% user + 0% kernel
0% 141/jbd2/mmcblk0p26: 0% user + 0% kernel
0% 239/sdcard: 0% user + 0% kernel
0% 1171/com.xiaomi.channel:pushservice: 0% user + 0% kernel / faults: 1 minor
0% 1207/com.xiaomi.channel: 0% user + 0% kernel / faults: 1 minor
0% 32705/kworker/0:1: 0% user + 0% kernel
12% TOTAL: 3.2% user + 9.4% kernel + 0% iowait
curl
without any options will perform a GET request. It will simply return the data from the URI specified. Not retrieve the file itself to your local machine.
When you do,
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
You will receive binary data:
|?>?$! <R?HP@T*?Pm?Z??jU???ZP+UAUQ@?
??{X\? K???>0c?yF[i?}4?!?V¸?H_?)nO#?;I??vg^_ ??-Hm$$N0.
???%Y[?L?U3?_^9??P?T?0'u8?l?4 ...
In order to save this, you can use:
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png > image.png
to store that raw image data inside of a file.
An easier way though, is just to use wget
.
$ wget https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
$ ls
.
..
apple-touch-icon-144x144-precomposed.png
Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open @cur
begin try
fetch last from @cur into @lastNum, @data
fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value
while @i < @lastNum
begin
set @i += 1
--Do your job here
print @data
fetch next from @cur into @rowNum, @data
end
end try
begin catch
close @cur --|
deallocate @cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close @cur
deallocate @cur
jQuery
if( ['class', 'class2'].some(c => [...element[0].classList].includes(c)) )
Vanilla JS
if( ['class', 'class2'].some(c => [...element.classList].includes(c)) )
Try the below code. I am using this code for opening a PDF file. You can use it for other files also.
File file = new File(Environment.getExternalStorageDirectory(),
"Report.pdf");
Uri path = Uri.fromFile(file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
startActivity(pdfOpenintent);
}
catch (ActivityNotFoundException e) {
}
If you want to open files, you can change the setDataAndType(path, "application/pdf")
. If you want to open different files with the same intent, you can use Intent.createChooser(intent, "Open in...");
. For more information, look at How to make an intent with multiple actions.
$new_input = array('type' => 'text', 'label' => 'First name', 'show' => true, 'required' => true);
$options['inputs']['name'] = $new_input;
you can convert the integer dataframe into string first and then do the operation e.g.
df3['nID']=df3['nID'].astype(str)
grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))
Just write a method for changing imageview
public void setImage(final Context mContext, final ImageView imageView, int picture)
{
if (mContext != null && imageView != null)
{
try
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
imageView.setImageDrawable(mContext.getResources().getDrawable(picture, mContext.getApplicationContext().getTheme()));
} else
{
imageView.setImageDrawable(mContext.getResources().getDrawable(picture));
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Put the word.txt directly as a child of the project root folder and a peer of src
Project_Root
src
word.txt
Disclaimer: I'd like to explain why this works for this particular case and why it may not work for others.
Why it works:
When you use File
or any of the other FileXxx
variants, you are looking for a file on the file system relative to the "working directory". The working directory, can be described as this:
When you run from the command line
C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1
the working directory is C:\EclipseWorkspace\ProjectRoot\bin
. With your IDE (at least all the ones I've worked with), the working directory is the ProjectRoot
. So when the file is in the ProjectRoot
, then using just the file name as the relative path is valid, because it is at the root of the working directory.
Similarly, if this was your project structure ProjectRoot\src\word.txt
, then the path "src/word.txt"
would be valid.
Why it May not Work
For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin
. So in this case it will fail, as there is not bin\word.txt
Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.
That being said, you need to determine if the file is to be an embedded-resource (or just "resource" - terms which sometimes I'll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get built into the classpath. With the file in the project root, you must configure the build to include the file. But if you put the file in the src
or in some directory below, then the default build should put it into the class path.
You can access classpath resource in a number of ways. You can make use of the Class
class, which has getResourceXxx
method, from which you use to obtain classpath resources.
For example, if you changed your project structure to ProjectRoot\src\resources\word.txt
, you could use this:
InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
getResourceAsStream
returns an InputStream
, but obtains an URL under the hood. Alternatively, you could get an URL
if that's what you need. getResource()
will return an URL
For Maven users, where the directory structure is like src/main/resources
, the contents of the resources
folder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")
Use
var isEmpty: Bool { get }
Example
let lang = "Swift 5"
if lang.isEmpty {
print("Empty string")
}
If you want to ignore white spaces
if lang.trimmingCharacters(in: .whitespaces).isEmpty {
print("Empty string")
}
Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:
*.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html
Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html
Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
Code snippets: For encoding:
String temp = new String(Base64.getEncoder().encode(key.getEncoded()));
For decoding:
byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");
change it to
$.post({
url = 'getData.php',
data : { 'id' id } ,
dataType : 'text'
});
This way ajax will not try to parse the data into json or similar
select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;
HTH
When you set to install it "for all users" (not for the current user only), you won't need to route Android Studio for the JAVA_HOME. Of course, have JDK installed.
I had issues with rowcount always returning -1 no matter what solution I tried.
I found the following a good replacement to check for a null result.
c.execute("SELECT * FROM users WHERE id=?", (id_num,))
row = c.fetchone()
if row == None:
print("There are no results for this query")
Although this is linked to Android
documentation (Wayback Machine) and My own code on Github, it will work for Java in general. My answer is an extension of dmeister's Answer with just code that is much easier to read and understand.
@Override
public int hashCode() {
// Start with a non-zero constant. Prime is preferred
int result = 17;
// Include a hash for each field.
// Primatives
result = 31 * result + (booleanField ? 1 : 0); // 1 bit » 32-bit
result = 31 * result + byteField; // 8 bits » 32-bit
result = 31 * result + charField; // 16 bits » 32-bit
result = 31 * result + shortField; // 16 bits » 32-bit
result = 31 * result + intField; // 32 bits » 32-bit
result = 31 * result + (int)(longField ^ (longField >>> 32)); // 64 bits » 32-bit
result = 31 * result + Float.floatToIntBits(floatField); // 32 bits » 32-bit
long doubleFieldBits = Double.doubleToLongBits(doubleField); // 64 bits (double) » 64-bit (long) » 32-bit (int)
result = 31 * result + (int)(doubleFieldBits ^ (doubleFieldBits >>> 32));
// Objects
result = 31 * result + Arrays.hashCode(arrayField); // var bits » 32-bit
result = 31 * result + referenceField.hashCode(); // var bits » 32-bit (non-nullable)
result = 31 * result + // var bits » 32-bit (nullable)
(nullableReferenceField == null
? 0
: nullableReferenceField.hashCode());
return result;
}
EDIT
Typically, when you override hashcode(...)
, you also want to override equals(...)
. So for those that will or has already implemented equals
, here is a good reference from my Github...
@Override
public boolean equals(Object o) {
// Optimization (not required).
if (this == o) {
return true;
}
// Return false if the other object has the wrong type, interface, or is null.
if (!(o instanceof MyType)) {
return false;
}
MyType lhs = (MyType) o; // lhs means "left hand side"
// Primitive fields
return booleanField == lhs.booleanField
&& byteField == lhs.byteField
&& charField == lhs.charField
&& shortField == lhs.shortField
&& intField == lhs.intField
&& longField == lhs.longField
&& floatField == lhs.floatField
&& doubleField == lhs.doubleField
// Arrays
&& Arrays.equals(arrayField, lhs.arrayField)
// Objects
&& referenceField.equals(lhs.referenceField)
&& (nullableReferenceField == null
? lhs.nullableReferenceField == null
: nullableReferenceField.equals(lhs.nullableReferenceField));
}
Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.
Another option that is perhaps the simplest one in terms of the command line is adding the built-in --trace-time
option:
curl -X POST -d @file server:port --trace-time
Even though it technically does not output the timings of the various steps as requested by the OP, it does display the timestamps for all steps of the request as shown below. Using this, you can (fairly easily) calculate how long each step has taken.
$ curl https://www.google.com --trace-time -v -o /dev/null
13:29:11.148734 * Rebuilt URL to: https://www.google.com/
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 013:29:11.149958 * Trying 172.217.20.36...
13:29:11.149993 * TCP_NODELAY set
13:29:11.163177 * Connected to www.google.com (172.217.20.36) port 443 (#0)
13:29:11.164768 * ALPN, offering h2
13:29:11.164804 * ALPN, offering http/1.1
13:29:11.164833 * successfully set certificate verify locations:
13:29:11.164863 * CAfile: none
CApath: /etc/ssl/certs
13:29:11.165046 } [5 bytes data]
13:29:11.165099 * (304) (OUT), TLS handshake, Client hello (1):
13:29:11.165128 } [512 bytes data]
13:29:11.189518 * (304) (IN), TLS handshake, Server hello (2):
13:29:11.189537 { [100 bytes data]
13:29:11.189628 * TLSv1.2 (IN), TLS handshake, Certificate (11):
13:29:11.189658 { [2104 bytes data]
13:29:11.190243 * TLSv1.2 (IN), TLS handshake, Server key exchange (12):
13:29:11.190277 { [115 bytes data]
13:29:11.190507 * TLSv1.2 (IN), TLS handshake, Server finished (14):
13:29:11.190539 { [4 bytes data]
13:29:11.190770 * TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
13:29:11.190797 } [37 bytes data]
13:29:11.190890 * TLSv1.2 (OUT), TLS change cipher, Client hello (1):
13:29:11.190915 } [1 bytes data]
13:29:11.191023 * TLSv1.2 (OUT), TLS handshake, Finished (20):
13:29:11.191053 } [16 bytes data]
13:29:11.204324 * TLSv1.2 (IN), TLS handshake, Finished (20):
13:29:11.204358 { [16 bytes data]
13:29:11.204417 * SSL connection using TLSv1.2 / ECDHE-ECDSA-CHACHA20-POLY1305
13:29:11.204451 * ALPN, server accepted to use h2
13:29:11.204483 * Server certificate:
13:29:11.204520 * subject: C=US; ST=California; L=Mountain View; O=Google LLC; CN=www.google.com
13:29:11.204555 * start date: Oct 2 07:29:00 2018 GMT
13:29:11.204585 * expire date: Dec 25 07:29:00 2018 GMT
13:29:11.204623 * subjectAltName: host "www.google.com" matched cert's "www.google.com"
13:29:11.204663 * issuer: C=US; O=Google Trust Services; CN=Google Internet Authority G3
13:29:11.204701 * SSL certificate verify ok.
13:29:11.204754 * Using HTTP2, server supports multi-use
13:29:11.204795 * Connection state changed (HTTP/2 confirmed)
13:29:11.204840 * Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
13:29:11.204881 } [5 bytes data]
13:29:11.204983 * Using Stream ID: 1 (easy handle 0x55846ef24520)
13:29:11.205034 } [5 bytes data]
13:29:11.205104 > GET / HTTP/2
13:29:11.205104 > Host: www.google.com
13:29:11.205104 > User-Agent: curl/7.61.0
13:29:11.205104 > Accept: */*
13:29:11.205104 >
13:29:11.218116 { [5 bytes data]
13:29:11.218173 * Connection state changed (MAX_CONCURRENT_STREAMS == 100)!
13:29:11.218211 } [5 bytes data]
13:29:11.251936 < HTTP/2 200
13:29:11.251962 < date: Fri, 19 Oct 2018 10:29:11 GMT
13:29:11.251998 < expires: -1
13:29:11.252046 < cache-control: private, max-age=0
13:29:11.252085 < content-type: text/html; charset=ISO-8859-1
13:29:11.252119 < p3p: CP="This is not a P3P policy! See g.co/p3phelp for more info."
13:29:11.252160 < server: gws
13:29:11.252198 < x-xss-protection: 1; mode=block
13:29:11.252228 < x-frame-options: SAMEORIGIN
13:29:11.252262 < set-cookie: 1P_JAR=2018-10-19-10; expires=Sun, 18-Nov-2018 10:29:11 GMT; path=/; domain=.google.com
13:29:11.252297 < set-cookie: NID=141=pzXxp1jrJmLwFVl9bLMPFdGCtG8ySQKxB2rlDWgerrKJeXxfdmB1HhJ1UXzX-OaFQcnR1A9LKYxi__PWMigjMBQHmI3xkU53LI_TsYRbkMNJNdxs-caQQ7fEcDGE694S; expires=Sat, 20-Apr-2019 10:29:11 GMT; path=/; domain=.google.com; HttpOnly
13:29:11.252336 < alt-svc: quic=":443"; ma=2592000; v="44,43,39,35"
13:29:11.252368 < accept-ranges: none
13:29:11.252408 < vary: Accept-Encoding
13:29:11.252438 <
13:29:11.252473 { [5 bytes data]
100 12215 0 12215 0 0 112k 0 --:--:-- --:--:-- --:--:-- 112k
13:29:11.255674 * Connection #0 to host www.google.com left intact
I had this problem just now and I tried the require_once trick, but it would just echo the CSS above all my php code without actually applying the styles.
What I did to fix it, though, was wrap all my php in their own plain HTML templates. Just type out html in the first line of the document and pick the suggestion html:5 to get the HTML boilerplate, like you would when you're just starting a plain HTML doc. Then cut the closing body and html tags and paste them all the way down at the bottom, below the closing php tag to wrap your php code without actually changing anything. Finally, you can just put your plain old link to your stylesheet into the head of your HTML. Works just fine.
>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200
I have such a method in my application, but it does not use jQuery:
/* Get the TOP position of a given element. */
function getPositionTop(element){
var offset = 0;
while(element) {
offset += element["offsetTop"];
element = element.offsetParent;
}
return offset;
}
/* Is a given element is visible or not? */
function isElementVisible(eltId) {
var elt = document.getElementById(eltId);
if (!elt) {
// Element not found.
return false;
}
// Get the top and bottom position of the given element.
var posTop = getPositionTop(elt);
var posBottom = posTop + elt.offsetHeight;
// Get the top and bottom position of the *visible* part of the window.
var visibleTop = document.body.scrollTop;
var visibleBottom = visibleTop + document.documentElement.offsetHeight;
return ((posBottom >= visibleTop) && (posTop <= visibleBottom));
}
Edit : This method works well for I.E. (at least version 6). Read the comments for compatibility with FF.
$('element[name="element_name"]').click(function(){
//do stuff
});
in your case:
$('input[name="btnName"]').click(function(){
//do stuff
});
This seems to work for me.
def make_Ramp( ramp_colors ):
from colour import Color
from matplotlib.colors import LinearSegmentedColormap
color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
plt.figure( figsize = (15,3))
plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
plt.xticks([])
plt.yticks([])
return color_ramp
custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] )
I know that it is a very old question, but I wanted to add the good solution with some in depth explanation. You will have to execute two statements on Ubuntu like systems and then it works like a charm.
Permissions in Linux can be represented with three digits. The first digit defines the permission of the owner of the files. The second digit the permissions of a specific group of users. The third digit defines the permissions for all users who are not the owner nor member of the group.
The webserver is supposed to execute with an id that is a member of the group. The webserver should never run with the same id as the owner of the files and directories. In Ubuntu runs apache under the id www-data. That id should be a member of the group for whom the permissions are specified.
To give the directory in which you want to change the content of files the proper rights, execute the statement:
find %DIR% -type d -exec chmod 770 {} \;
.That would imply in the question of the OP that the permissions for the directory %ROOT%/database should be changed accordingly. It is therefor important not to have files within that directory that should never get changed, or removed. It is therefor best practice to create a separate directory for files whose content must be changed.
Reading permissions (4) for a directory means being able to collect all files and directories with their metadata within a directory. Write permissions (2) gives the permission to change the content of the directory. Implying adding and removing files, changing permissions etc.. Execution permission (1) means that you have the right to go into that directory. Without the latter is it impossible to go deeper into the directory. The webserver needs read, write and execute permissions when the content of a file should be changed. Therefor needs the group the digit 7.
The second statement is in the question of the OP:
find %DOCUMENT_ROOT%/database -type f -exec chmod 760 {} \;
Being able to read and write a document is required, but it is not required to execute the file. The 7 is given to the owner of the files, the 6 to the group. The webserver does not need to have the permission to execute the file in order to change its content. Those write permissions should only be given to files in that directory.
All other users should not be given any permission.
For directories that do not require to change its files are group permissions of 5 sufficient. Documentation about permissions and some examples:
https://wiki.debian.org/Permissions
https://www.linux.com/learn/tutorials/309527-understanding-linux-file-permissions
If you have installed openssl
, you can use:
echo -n "foobar" | openssl dgst -sha256
For other algorithms you can replace -sha256
with -md4
, -md5
, -ripemd160
, -sha
, -sha1
, -sha224
, -sha384
, -sha512
or -whirlpool
.
It is just such simple as writing:
$('input[type=file]').val()
Anyway, I suggest using name or ID attribute to select your input. And with event, it should look like this:
$('input[type=file]').change(function(e){
$in=$(this);
$in.next().html($in.val());
});
You simply need to remove v-bind (:) from selected and required attributes. Like this :-
<template>_x000D_
<select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
<option selected>Choose Province</option>_x000D_
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
</select>_x000D_
</template>
_x000D_
You are not binding anything to the vue instance through these attributes thats why it is giving error.
I too get this error sometimes when I dismiss dialog and finish activity from onPostExecute method. I guess sometimes activity gets finished before dialog successfully dismisses.
Simple, yet effective solution that works for me
@Override
protected void onPostExecute(MyResult result) {
try {
if ((this.mDialog != null) && this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.mDialog = null;
}
}
The answer above suggests changing the function to echo data rather than return it so that it can be captured.
For a function or program that you can't modify where the return value needs to be saved to a variable (like test
/[
, which returns a 0/1 success value), echo $?
within the command substitution:
# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"
# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"
E.g.
$ echo $REMOTE_ADDR
$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0
For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:
# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []
# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0
I had a similar problem. I had to schedule bunch of tasks that should be executed during a day using ScheduledExecutorService
.
This was solved by one task starting at 3:30 AM scheduling all other tasks relatively to his current time. And rescheduling himself for the next day at 3:30 AM.
With this scenario daylight savings are not an issue anymore.
The simplest way is to edit the user settings and customise workbench.colorCustomizations
There is also the option modify the current theme which will copy the current theme settings and let you save it as a *.color-theme.json
JSON5 file
1.get all tables and views from information_schema.tables, include those of information_schema and pg_catalog.
select * from information_schema.tables
2.get tables and views belong certain schema
select * from information_schema.tables
where table_schema not in ('information_schema', 'pg_catalog')
3.get tables only(almost \dt)
select * from information_schema.tables
where table_schema not in ('information_schema', 'pg_catalog') and
table_type = 'BASE TABLE'
You can use SilverLight to launch an application from the browser (this will work only on IE and Firefox, newer versions of chrome don't support this)
Example code here
The opposite of the ==
compare operator is !=
.
Like user2680100 said, in Golang you can have the structure:
if <statement>; <evaluation> {
[statements ...]
} else {
[statements ...]
}
This is useful to shortcut some expressions that need error checking, or another kind of boolean checking, like:
var number int64
if v := os.Getenv("NUMBER"); v != "" {
if number, err = strconv.ParseInt(v, 10, 64); err != nil {
os.Exit(42)
}
} else {
os.Exit(1)
}
With this you can achieve something like (in C):
Sprite *buffer = get_sprite("foo.png");
Sprite *foo_sprite = (buffer != 0) ? buffer : donut_sprite
But is evident that this sugar in Golang have to be used with moderation, for me, personally, I like to use this sugar with max of one level of nesting, like:
var number int64
if v := os.Getenv("NUMBER"); v != "" {
number, err = strconv.ParseInt(v, 10, 64)
if err != nil {
os.Exit(42)
}
} else {
os.Exit(1)
}
You can also implement ternary expressions with functions like func Ternary(b bool, a interface{}, b interface{}) { ... }
but i don't like this approach, looks like a creation of a exception case in syntax, and creation of this "features", in my personal opinion, reduce the focus on that matters, that is algorithm and readability, but, the most important thing that makes me don't go for this way is that fact that this can bring a kind of overhead, and bring more cycles to in your program execution.
Try this:
webBrowser1.DocumentText =
"<html><body>Please enter your name:<br/>" +
"<input type='text' name='userName'/><br/>" +
"<a href='http://www.microsoft.com'>continue</a>" +
"</body></html>";
If you got this problem in Visual Studio 2017, chances are you're working with an MVC 4 project created in a previous version of VS with a reference hint path pointing to C:\Program Files (x86)\Microsoft ASP.NET
. Visual Studio 2017 does not install this directory anymore.
We usually solve this by installing a copy of Visual Studio 2015 alongside our 2017 instance, and that installs the necessary libraries in the above path. Then we update all the references in the affected projects and we're good to go.
There is a good blog about this topic: http://www.baeldung.com/jackson-serialize-dates Use @JsonFormat looks the most simple way.
public class Event {
public String name;
@JsonFormat
(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
public Date eventDate;
}
Code generation would be the only other way I can think of. Personally, I'd got with a generally reusable reflection solution (unless that part of the code is absolutely performance-critical). Using JMS sounds like overkill (additional dependency, and that's not even what it's meant for). Besides, it probably uses reflection as well under the hood.
I am using below code for today and database date.
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20
According to the documentation, the first argument can be any of the following:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
Using river can present issues when your operation scales up. River will use a ton of memory when under heavy operation. I recommend implementing your own elasticsearch models, or if you're using mongoose you can build your elasticsearch models right into that or use mongoosastic which essentially does this for you.
Another disadvantage to Mongodb River is that you'll be stuck using mongodb 2.4.x branch, and ElasticSearch 0.90.x. You'll start to find that you're missing out on a lot of really nice features, and the mongodb river project just doesn't produce a usable product fast enough to keep stable. That said Mongodb River is definitely not something I'd go into production with. It's posed more problems than its worth. It will randomly drop write under heavy load, it will consume lots of memory, and there's no setting to cap that. Additionally, river doesn't update in realtime, it reads oplogs from mongodb, and this can delay updates for as long as 5 minutes in my experience.
We recently had to rewrite a large portion of our project, because its a weekly occurrence that something goes wrong with ElasticSearch. We had even gone as far as to hire a Dev Ops consultant, who also agrees that its best to move away from River.
UPDATE: Elasticsearch-mongodb-river now supports ES v1.4.0 and mongodb v2.6.x. However, you'll still likely run into performance problems on heavy insert/update operations as this plugin will try to read mongodb's oplogs to sync. If there are a lot of operations since the lock(or latch rather) unlocks, you'll notice extremely high memory usage on your elasticsearch server. If you plan on having a large operation, river is not a good option. The developers of ElasticSearch still recommend you to manage your own indexes by communicating directly with their API using the client library for your language, rather than using river. This isn't really the purpose of river. Twitter-river is a great example of how river should be used. Its essentially a great way to source data from outside sources, but not very reliable for high traffic or internal use.
Also consider that mongodb-river falls behind in version, as its not maintained by ElasticSearch Organization, its maintained by a thirdparty. Development was stuck on v0.90 branch for a long time after the release of v1.0, and when a version for v1.0 was released it wasn't stable until elasticsearch released v1.3.0. Mongodb versions also fall behind. You may find yourself in a tight spot when you're looking to move to a later version of each, especially with ElasticSearch under such heavy development, with many very anticipated features on the way. Staying up on the latest ElasticSearch has been very important as we rely heavily on constantly improving our search functionality as its a core part of our product.
All in all you'll likely get a better product if you do it yourself. Its not that difficult. Its just another database to manage in your code, and it can easily be dropped in to your existing models without major refactoring.
JSON does not allow real line-breaks. You need to replace all the line breaks with \n
.
eg:
"first line
second line"
can saved with:
"first line\nsecond line"
Note:
for Python
, this should be written as:
"first line\\nsecond line"
where \\
is for escaping the backslash, otherwise python will treat \n
as
the control character "new line"
The results from json.Unmarshal
(into var data interface{}
) do not directly match your Go type and variable declarations. For example,
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
type Tracks struct {
Toptracks []Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr []Attr_info
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []Streamable_info
Artist []Artist_info
Attr []Track_attr_info
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
url += "&limit=1" // limit data for testing
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data interface{} // TopTracks
err = json.Unmarshal(body, &data)
if err != nil {
panic(err.Error())
}
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
Output:
Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]
Thanks for asking; the JDK does not seem to interact with the Windows registry.
However, the JRE does in certain instances.
In the debugger you don't need to add back slashes, the input field understands the special chars.
In java code you need to escape the special chars
The itertools
module contains a filter function for iterators. The first element of the filtered iterator can be obtained by calling next()
on it:
from itertools import ifilter
print ifilter((lambda i: i > 3), range(10)).next()
<html>
<style>
.selectBox{
color:White;
}
.optionBox{
color:black;
}
</style>
<body>
<select class = "selectBox">
<option class = "optionBox">One</option>
<option class = "optionBox">Two</option>
<option class = "optionBox">Three</option>
</select>
Have you checked that those classes are present in the CSS? Are you using twitter-bootstrap-rails gem? It still uses Bootstrap 2.X version and those are Bootstrap 3.X classes. The CSS grid changed since.
You can switch to the bootstrap3 branch of the gem https://github.com/seyhunak/twitter-bootstrap-rails/tree/bootstrap3 or include boostrap in an alternative way.
C++17 now provides the [[maybe_unused]]
attribute.
http://en.cppreference.com/w/cpp/language/attributes
Quite nice and standard.
For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly
and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.
This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.
To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.
cc -DDISPLAY_STRING demo.c
If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.
#define TERMINAL "/dev/ttyUSB0"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int set_interface_attribs(int fd, int speed)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error from tcgetattr: %s\n", strerror(errno));
return -1;
}
cfsetospeed(&tty, (speed_t)speed);
cfsetispeed(&tty, (speed_t)speed);
tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~PARENB; /* no parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
/* setup for non-canonical mode */
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
/* fetch bytes as they become available */
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
printf("Error from tcsetattr: %s\n", strerror(errno));
return -1;
}
return 0;
}
void set_mincount(int fd, int mcount)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error tcgetattr: %s\n", strerror(errno));
return;
}
tty.c_cc[VMIN] = mcount ? 1 : 0;
tty.c_cc[VTIME] = 5; /* half second timer */
if (tcsetattr(fd, TCSANOW, &tty) < 0)
printf("Error tcsetattr: %s\n", strerror(errno));
}
int main()
{
char *portname = TERMINAL;
int fd;
int wlen;
char *xstr = "Hello!\n";
int xlen = strlen(xstr);
fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
printf("Error opening %s: %s\n", portname, strerror(errno));
return -1;
}
/*baudrate 115200, 8 bits, no parity, 1 stop bit */
set_interface_attribs(fd, B115200);
//set_mincount(fd, 0); /* set to pure timed read */
/* simple output */
wlen = write(fd, xstr, xlen);
if (wlen != xlen) {
printf("Error from write: %d, %d\n", wlen, errno);
}
tcdrain(fd); /* delay for output */
/* simple noncanonical input */
do {
unsigned char buf[80];
int rdlen;
rdlen = read(fd, buf, sizeof(buf) - 1);
if (rdlen > 0) {
#ifdef DISPLAY_STRING
buf[rdlen] = 0;
printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
unsigned char *p;
printf("Read %d:", rdlen);
for (p = buf; rdlen-- > 0; p++)
printf(" 0x%x", *p);
printf("\n");
#endif
} else if (rdlen < 0) {
printf("Error from read: %d: %s\n", rdlen, strerror(errno));
} else { /* rdlen == 0 */
printf("Timeout from read\n");
}
/* repeat read to get full message */
} while (1);
}
For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.
I had the same problem, and
neither umount /path -f
,
neither umount.nfs /path -f
,
neither fuser -km /path
,
works
finally I found a simple solution >.<
sudo /etc/init.d/nfs-common restart
, then lets do the simple umount
;-)
I collected many topics to make universal function with many outputs (years, months, days, hours, minutes, seconds) with string or parse to int and direction +- if you need to know what side is direction of the difference.
Use example:
$date1='2016-05-27 02:00:00';
$format='Y-m-d H:i:s';
echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format);
#1 years 3 months 2 days 22 hours 1 minutes 59 seconds (string)
echo timeDifference($date1, $format, '2017-08-30 00:01:59', $format,false, '%a days %h hours');
#459 days 22 hours (string)
echo timeDifference('2016-05-27 00:00:00', $format, '2017-08-30 00:01:59', $format,true, '%d days -> %H:%I:%S', true);
#-3 days -> 00:01:59 (string)
echo timeDifference($date1, $format, '2016-05-27 00:05:51', $format, false, 'seconds');
#9 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, false, 'hours');
#5 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours');
#-5 (string)
echo timeDifference($date1, $format, '2016-05-27 07:00:00', $format, true, 'hours',true);
#-5 (int)
Function
function timeDifference($date1_pm_checked, $date1_format,$date2, $date2_format, $plus_minus=false, $return='all', $parseInt=false)
{
$strtotime1=strtotime($date1_pm_checked);
$strtotime2=strtotime($date2);
$date1 = new DateTime(date($date1_format, $strtotime1));
$date2 = new DateTime(date($date2_format, $strtotime2));
$interval=$date1->diff($date2);
$plus_minus=(empty($plus_minus)) ? '' : ( ($strtotime1 > $strtotime2) ? '+' : '-'); # +/-/no_sign before value
switch($return)
{
case 'y';
case 'year';
case 'years';
$elapsed = $interval->format($plus_minus.'%y');
break;
case 'm';
case 'month';
case 'months';
$elapsed = $interval->format($plus_minus.'%m');
break;
case 'a';
case 'day';
case 'days';
$elapsed = $interval->format($plus_minus.'%a');
break;
case 'd';
$elapsed = $interval->format($plus_minus.'%d');
break;
case 'h';
case 'hour';
case 'hours';
$elapsed = $interval->format($plus_minus.'%h');
break;
case 'i';
case 'minute';
case 'minutes';
$elapsed = $interval->format($plus_minus.'%i');
break;
case 's';
case 'second';
case 'seconds';
$elapsed = $interval->format($plus_minus.'%s');
break;
case 'all':
$parseInt=false;
$elapsed = $plus_minus.$interval->format('%y years %m months %d days %h hours %i minutes %s seconds');
break;
default:
$parseInt=false;
$elapsed = $plus_minus.$interval->format($return);
}
if($parseInt)
return (int) $elapsed;
else
return $elapsed;
}
DECLARE @COMBINED_STRINGS AS VARCHAR(50),
@STRING1 AS VARCHAR(20),
@STRING2 AS VARCHAR(20);
SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SELECT @COMBINED_STRINGS;
SELECT '2' + '3';
I typed this in a sql file named TEST.sql and I run it. I got the following out put.
+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| 0 |
+-------------------+
1 row in set (0.00 sec)
+-----------+
| '2' + '3' |
+-----------+
| 5 |
+-----------+
1 row in set (0.00 sec)
After looking into this issue a bit more I found the best and sure sort way for string concatenation in SQL is by using CONCAT method. So I made the following changes in the same file.
#DECLARE @COMBINED_STRINGS AS VARCHAR(50),
# @STRING1 AS VARCHAR(20),
# @STRING2 AS VARCHAR(20);
SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
#SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SET @COMBINED_STRINGS = (SELECT CONCAT(@STRING1, @STRING2));
SELECT @COMBINED_STRINGS;
#SELECT '2' + '3';
SELECT CONCAT('2','3');
and after executing the file this was the output.
+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| rupesh'smalviya |
+-------------------+
1 row in set (0.00 sec)
+-----------------+
| CONCAT('2','3') |
+-----------------+
| 23 |
+-----------------+
1 row in set (0.00 sec)
SQL version I am using is: 14.14
Suppose you want to insert a particular line of text (not an empty line):
@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1
@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /p L=
IF %%i==%insertat% ECHO(!TL!
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
Try the following code:
ActivityManager activityManager = (ActivityManager) newContext.getSystemService( Context.ACTIVITY_SERVICE );
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo appProcess : appProcesses){
if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
Log.i("Foreground App", appProcess.processName);
}
}
Process name is the package name of the app running in foreground. Compare it to the package name of your application. If it is the same then your application is running on foreground.
I hope this answers your question.
A shorter form can be used:
return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString()
EDIT: Haven't paid attention to ExecuteScalar. It does really return null if the field is absent in the return result. So use instead:
return (accountNumber == null) ? string.Empty : accountNumber.ToString()
C is a very low-level language, so it permits you to create almost any legal object (.o) file that you can conceive of. You should think of C as basically dressed-up assembly language.
In particular, C does not require functions to be declared before they are used. If you call a function without declaring it, the use of the function becomes it's (implicit) declaration. In a simple test I just ran, this is only a warning in the case of built-in library functions like printf (at least in GCC), but for random functions, it will compile just fine.
Of course, when you try to link, and it can't find foo, then you will get an error.
In the case of library functions like printf, some compilers contain built-in declarations for them so they can do some basic type checking, so when the implicit declaration (from the use) doesn't match the built-in declaration, you'll get a warning.
I just watched the 30 minute Unity Dependency Injection IoC Screencast by David Hayden and felt that was a good explaination with examples. Here is a snippet from the show notes:
The screencast shows several common usages of the Unity IoC, such as:
Here is some code. It uses 2 classes (Card.java and Deck.java) to accomplish this issue, and to top it off it auto sorts it for you when you create the deck object. :)
import java.util.*;
public class deck2 {
ArrayList<Card> cards = new ArrayList<Card>();
String[] values = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String[] suit = {"Club", "Spade", "Diamond", "Heart"};
static boolean firstThread = true;
public deck2(){
for (int i = 0; i<suit.length; i++) {
for(int j=0; j<values.length; j++){
this.cards.add(new Card(suit[i],values[j]));
}
}
//shuffle the deck when its created
Collections.shuffle(this.cards);
}
public ArrayList<Card> getDeck(){
return cards;
}
public static void main(String[] args){
deck2 deck = new deck2();
//print out the deck.
System.out.println(deck.getDeck());
}
}
//separate class
public class Card {
private String suit;
private String value;
public Card(String suit, String value){
this.suit = suit;
this.value = value;
}
public Card(){}
public String getSuit(){
return suit;
}
public void setSuit(String suit){
this.suit = suit;
}
public String getValue(){
return value;
}
public void setValue(String value){
this.value = value;
}
public String toString(){
return "\n"+value + " of "+ suit;
}
}
An alternative solution to using the <ripple>
tag (which I personally prefer not to do, because the colors are not "default"), is the following:
Create a drawable for the button background, and include <item android:drawable="?attr/selectableItemBackground">
in the <layer-list>
Then (and I think this is the important part) programmatically set backgroundResource(R.drawable.custom_button)
on your button instance.
Button btn_temp = view.findViewById(R.id.btn_temp);
btn_temp.setBackgroundResource(R.drawable.custom_button);
<Button
android:id="@+id/btn_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button"
android:text="Test" />
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="10dp" />
</shape>
</item>
<item android:drawable="?attr/selectableItemBackground" />
</layer-list>
Here is the solution with recursion, that looks simple:
const toRoman = (num, result = '') => {
const map = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
for (const key in map) {
if (num >= map[key]) {
if (num !== 0) {
return toRoman(num - map[key], result + key);
}
}
}
return result;
};
console.log(toRoman(402)); // CDII
console.log(toRoman(3000)); // MMM
console.log(toRoman(93)); // XCIII
console.log(toRoman(4)); // IV
_x000D_
Your onTap
override receives the MapView
from which you can obtain the Context
:
@Override
public boolean onTap(GeoPoint p, MapView mapView)
{
// ...
Intent intent = new Intent();
intent.setClass(mapView.getContext(), FullscreenView.class);
startActivity(intent);
// ...
}
If you want to check if some string is present in another string, use something like String.contains
If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.
Example: Suppose you have some regex a(b|c) that checks if a string matches ab
or ac
.*(a(b|c)).*
will check if a string contains a ab
or ac
.
A disadvantage of this method is that it will not give you the location of the match.
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
This would be a get/set in C# using the smallest amount of code possible. You get auto-implemented properties in C# 3.0+.
public class Contact
{
public string Name { get; set; }
}
To make it a touch less java specific, the basic principle would be to convert to some linear date format, julian days, modified julian days, seconds since some epoch, etc, add your day, and convert back.
The reason for doing this is that you farm out the "get the leap day, leap second, etc right' problem to someone who has, with some luck, not mucked this problem up.
I will caution you that getting these conversion routines right can be difficult. There are an amazing number of different ways that people mess up time, the most recent high profile example was MS's Zune. Dont' poke too much fun at MS though, it's easy to mess up. It doesn't help that there are multiple different time formats, say, TAI vs TT.
Since ECMAScript6, one can use Set
:
var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
If you give a default value to each primary constructor parameter:
data class Item(var id: String = "",
var title: String = "",
var condition: String = "",
var price: String = "",
var categoryId: String = "",
var make: String = "",
var model: String = "",
var year: String = "",
var bodyStyle: String = "",
var detail: String = "",
var latitude: Double = 0.0,
var longitude: Double = 0.0,
var listImages: List<String> = emptyList(),
var idSeller: String = "")
and from the class where the instances you can call it without arguments or with the arguments that you have that moment
var newItem = Item()
var newItem2 = Item(title = "exampleTitle",
condition = "exampleCondition",
price = "examplePrice",
categoryId = "exampleCategoryId")
You can set the ReadOnly property to true.
Quoth the link:
When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.
It is one of the annotation used to map/handle dynamic URIs. You can even specify a regular expression for URI dynamic parameter to accept only specific type of input.
For example, if the URL to retrieve a book using a unique number would be:
URL:http://localhost:8080/book/9783827319333
The number denoted at the last of the URL can be fetched using @PathVariable as shown:
@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)
public String showBookDetails(@PathVariable("ISBN") String id,
Model model){
model.addAttribute("ISBN", id);
return "bookDetails";
}
In short it is just another was to extract data from HTTP requests in Spring.
Of all the options above I would use
if (mysql_num_rows($result)==0) { PERFORM ACTION }
checking against the result like below
if (!$result) { PERFORM ACTION }
This will be true if a mysql_error occurs so effectively if an error occurred you could then enter a duplicate user-name...
sizeof
returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7]
which is 7 * sizeof(char)
. Since sizeof(char) = 1
, the result is 7.
Expanding this to another example:
int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));
would yield 5 * sizeof(int)
, so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int)
might differ)
To return to your problem:
It seems like, that what you want to know is the length of the string which is contained inside your array and not the total array size.
By definition C-Strings have to be terminated with a trailing '\0' (0-Byte). So to get the appropriate length of the string contained within your array, you have to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.
All standard functions build upon this definition, so if you call strlen
to retrieve
the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.
Another thing you might need to know that only because you don't fill the remaining elements of your char[7]
with a value, they actually do contain random undefined values.
Hope that helped.
I think the most significant problem is that you're incrementing code
as you read stuff in, and then returning the final value of code
, i.e. you'll be returning a pointer to the end of the string. You probably want to make a copy of code
before the loop, and return that instead.
Also, C strings need to be null-terminated. You need to make sure that you place a '\0'
directly after the final character that you read in.
Note: You could just use fgets()
to get the entire line in one hit.
You want the path.join() function from os.path.
>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'
This builds your path with os.sep (instead of the less portable '/'
) and does it more efficiently (in general) than using +
.
However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:
start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
os.makedirs (final_path)
I had the same problem and which got resolved by using ./
before the directory name in my node.js
app, i.e.
app.use(express.static('./public'));
I suggest a custom alias on you .gitconfig
.
You have to way to do:
1) With git command:
git config --global alias.check-file <command>
2) Editing ~/.gitconfig
and add this line on alias section:
[alias]
check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi; }; f"
Once launched command (1) or saved file (2), on your workspace you can test it:
$ git check-file
$ Filename missing
$ git check-file README.md
$ File tracked
$ git check-file foo
$ File not tracked
Another thing to watch out for, is that this error can happen if you have a nested
<form
tag within the .Net form.
Remove this line from your code:
console.info(JSON.parse(scatterSeries));
copy mysql-connector-java-5.1.24-bin.jar
Paste it into \Apache Software Foundation\Tomcat 6.0\lib\<--here-->
Restart Your Server from Eclipes.
Done
I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.
attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))
Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.
- all changed code included in this reply; close to android tutorial
I've been spending plenty of time on this issue, so I decided to create an account and share my outcomes with you.
The official android tutorial "Taking Photos Simply" turned out to not quite hold what it promised. The code provided there did not work on my device: a Samsung Galaxy S4 Mini GT-I9195 running android version 4.4.2 / KitKat / API Level 19.
I figured out that the main problem was the following line in the method invoked when capturing the photo (dispatchTakePictureIntent
in the tutorial):
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
It resulted in the intent subsequently catched by onActivityResult
being null.
To solve this problem, I pulled much inspiration out of earlier replies here and some helpful posts on github (mostly this one by deepwinter - big thanks to him; you might want to check out his reply on a closely related post as well).
Following these pleasant pieces of advice, I chose the strategy of deleting the mentioned putExtra
line and doing the corresponding thing of getting back the taken picture from the camera within the onActivityResult() method instead.
The decisive lines of code to get back the bitmap associated with the picture are:
Uri uri = intent.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
I created an exemplary app which just has the ability to take a picture, save it on the SD card and display it. I think this might be helpful to people in the same situation as me when I stumbled on this issue, since the current help suggestions mostly refer to rather extensive github posts which do the thing in question but aren't too easy to oversee for newbies like me. With respect to the file system Android Studio creates per default when creating a new project, I just had to change three files for my purpose:
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.simpleworkingcameraapp.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="takePicAndDisplayIt"
android:text="Take a pic and display it." />
<ImageView
android:id="@+id/image1"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
MainActivity.java :
package com.example.android.simpleworkingcameraapp;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private ImageView image;
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image1);
}
// copied from the android development pages; just added a Toast to show the storage location
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_LONG).show();
return image;
}
public void takePicAndDisplayIt(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
File file = null;
try {
file = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}
}
@Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
if (requestCode == REQUEST_TAKE_PHOTO && resultcode == RESULT_OK) {
Uri uri = intent.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
}
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.simpleworkingcameraapp">
<!--only added paragraph-->
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- only crucial line to add; for me it still worked without the other lines in this paragraph -->
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Note that the solution I found for the problem also led to a simplification of the android manifest file: the changes suggested by the android tutorial in terms of adding a provider are no longer needed since I am not making use of any in my java code. Hence, only few standard lines -mostly regarding permissions- had to be added to the manifest file.
It might additionally be valuable to point out that Android Studio's autoimport may not be capable of handling java.text.SimpleDateFormat
and java.util.Date
. I had to import both of them manually.
The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:
#!/usr/bin/python
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
print lxml.etree.tostring(the_doc, pretty_print=True)
Output:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
It also supports adding to an already-made node, e.g. after the above you could say
the_doc.append(FIELD2('another value again', name='hithere'))
To dismiss a keyboard after the keyboard has popped up, there are 2 cases,
when the UITextField is inside a UIScrollView
when the UITextField is outside a UIScrollView
2.when the UITextField is outside a UIScrollView override the method in your UIViewController subclass
you must also add delegate for all UITextView
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
to create a IBAction, press ctrl+ click the UITapGesture and drag it to the .h file of viewcontroller.
Here I have named tappedEvent as my action name
- (IBAction)tappedEvent:(id)sender {
[self.view endEditing:YES]; }
the abouve given Information was derived from the following link, please refer for more information or contact me if you dont understand the abouve data.
http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/
When you don't care about removing the Html Dom-Element, use *ngIf.
Otherwise, use this:
<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
COUNTER: {{numberOfUnreadAlerts}}
</div>
You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:
SELECT
airline, flt_no, fairport, tairport, depart, arrive, fare
FROM
flights
INNER JOIN
airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
airports to_port ON (to_port.code = flights.tairport)
WHERE
from_port.code = '?' OR to_port.code = '?' OR airports.city='?'
Note that the to_port
and from_port
are aliases for the first and second copies of the airports
table.
What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
<Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
<Rectangle.Fill>
<SolidColorBrush Color="#FF00AE00" />
</Rectangle.Fill>
</Rectangle>
</Grid>
I am describing a simple method which worked very smoothly in Python (Django Framework).
1. While sending the request, send the request like this
http://server/action?id=a,b
2. Now in my backend, I split the value received with a split function which always creates a list.
id_filter = id.split(',')
Example: So if I send two values in the request,
http://server/action?id=a,b
then the filter on the data is
id_filter = ['a', 'b']
If I send only one value in the request,
http://server/action?id=a
then the filter outcome is
id_filter = ['a']
3. To actually filter the data, I simply use the 'in' function
queryset = queryset.filter(model_id__in=id_filter)
which roughly speaking performs the SQL equivalent of
WHERE model_id IN ('a', 'b')
with the first request and,
WHERE model_id IN ('a')
with the second request.
This would work with more than 2 parameter values in the request as well !
This is working for me. Which version of Flask are you using?
from flask import jsonify
...
@app.route('/test/json')
def test_json():
list = [
{'a': 1, 'b': 2},
{'a': 5, 'b': 10}
]
return jsonify(results = list)
Simplest of all solutions for OFFICE 365:
from O365 import Message
html_template = """
<html>
<head>
<title></title>
</head>
<body>
{}
</body>
</html>
"""
final_html_data = html_template.format(df.to_html(index=False))
o365_auth = ('sender_username@company_email.com','Password')
m = Message(auth=o365_auth)
m.setRecipients('receiver_username@company_email.com')
m.setSubject('Weekly report')
m.setBodyHTML(final)
m.sendMessage()
here df is a dataframe converted to html Table, which is being injected to html_template
Quick trick-
SELECT CAST('<A><![CDATA[' + CAST(LogInfo as nvarchar(max)) + ']]></A>' AS xml)
FROM Logs
WHERE IDLog = 904862629
IEnumerable<Customer> filteredList = originalList
.GroupBy(customer => customer.CustomerId)
.Select(group => group.First());
It is a way to simplify error checking and avoid deep nested if's. For example:
do {
// do something
if (error) {
break;
}
// do something else
if (error) {
break;
}
// etc..
} while (0);
Overriding maven-javadoc-plugin
configuration only, does not fix the problem with mvn site
(used e.g during the release stage). Here's what I had to do:
<profile>
<id>doclint-java8-disable</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.3</version>
<configuration>
<reportPlugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</plugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
</profile>
The configuration seem alright, except that you should use excludeFilters
instead of excludes
:
@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}
Set the DataGridView property
gridView1.AutoGenerateColumns = true;
And make sure the list of objects your are binding, those object properties should be public.
Just add parameters, split by comma:
UPDATE tablename SET column1 = "value1", column2 = "value2" ....
see the link also MySQL UPDATE
$('#grid').trigger( 'reloadGrid' );
I made a deleteRabbitMqQs.sh, which accepts arguments to search the list of queues for, selecting only ones matching the pattern you want. If you offer no arguments, it will delete them all! It shows you the list of queues its about to delete, letting you quit before doing anything destructive.
for word in "$@"
do
args=true
newQueues=$(rabbitmqctl list_queues name | grep "$word")
queues="$queues
$newQueues"
done
if [ $# -eq 0 ]; then
queues=$(rabbitmqctl list_queues name | grep -v "\.\.\.")
fi
queues=$(echo "$queues" | sed '/^[[:space:]]*$/d')
if [ "x$queues" == "x" ]; then
echo "No queues to delete, giving up."
exit 0
fi
read -p "Deleting the following queues:
${queues}
[CTRL+C quit | ENTER proceed]
"
while read -r line; do
rabbitmqadmin delete queue name="$line"
done <<< "$queues"
If you want different matching against the arguments you pass in, you can alter the grep in line four. When deleting all queues, it won't delete ones with three consecutive spaces in them, because I figured that eventuality would be rarer than people who have rabbitmqctl printing its output out in different languages.
Enjoy!
I think rake must be preinstalled if you want work with bundler. Try to install rake via 'gem install' and then run 'bundle install' again:
gem install rake && bundle install
If you are using rvm ( http://rvm.io ) rake is installed by default...