There is also a POSIX library for POSIX operating systems. Check for compatability
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
void *task(void *argument){
char* msg;
msg = (char*)argument;
std::cout<<msg<<std::endl;
}
int main(){
pthread_t thread1, thread2;
int i1,i2;
i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
compile with -lpthread
The Fusion Log Settings Viewer changer script is bar none the best way to do this.
In ASP.NET, it has been tricky at times to get this to work correctly. This script works great and was listed on Scott Hanselman's Power Tool list as well. I've personally used it for years and its never let me down.
Let me Improve a example with threads in case you want download many files.
import math
import random
import threading
import requests
from clint.textui import progress
# You must define a proxy list
# I suggests https://free-proxy-list.net/
proxies = {
0: {'http': 'http://34.208.47.183:80'},
1: {'http': 'http://40.69.191.149:3128'},
2: {'http': 'http://104.154.205.214:1080'},
3: {'http': 'http://52.11.190.64:3128'}
}
# you must define the list for files do you want download
videos = [
"https://i.stack.imgur.com/g2BHi.jpg",
"https://i.stack.imgur.com/NURaP.jpg"
]
downloaderses = list()
def downloaders(video, selected_proxy):
print("Downloading file named {} by proxy {}...".format(video, selected_proxy))
r = requests.get(video, stream=True, proxies=selected_proxy)
nombre_video = video.split("/")[3]
with open(nombre_video, 'wb') as f:
total_length = int(r.headers.get('content-length'))
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length / 1024) + 1):
if chunk:
f.write(chunk)
f.flush()
for video in videos:
selected_proxy = proxies[math.floor(random.random() * len(proxies))]
t = threading.Thread(target=downloaders, args=(video, selected_proxy))
downloaderses.append(t)
for _downloaders in downloaderses:
_downloaders.start()
You are very close; currently you compare the row[2]
with integer 0
, make the comparison with the string "0"
. When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:
row[2]!="0":
Also, you can use the with
keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close
statements:
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != "0":
writer.writerow(row)
Note that input
is a Python builtin, so I've used another variable name instead.
Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0"
would work, so you can either use strip(row[2]) != 0
, or check against " 0"
.
The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:
$ cat test.py
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != " 0":
writer.writerow(row)
$ cat first.csv
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py
$ cat first_edit.csv
6.5, 5.4, 1, 320
The correct command is the following one.
VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"
The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.
"Alter column position" in the PostgreSQL Wiki says:
PostgreSQL currently defines column order based on the
attnum
column of thepg_attribute
table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.
That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.
One other idea occurs to me: you can define a VIEW
that specifies the order of columns how you like it, without changing the physical position of the column in the base table.
If you want to change theme of an already existing activity, call recreate()
after setTheme()
.
Note: don't call recreate if you change theme in onCreate()
, to avoid infinite loop.
Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method
using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
Or is you want to do it based on what you were trying to do , you can try this
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
If we also want to handle white spaces and unwanted tabs-
Check and Try the below script (Unit Tested)-
--Declaring
DECLARE @Tbl TABLE(col_1 VARCHAR(100));
--Test Samples
INSERT INTO @Tbl (col_1)
VALUES
(' EY y
Salem')
, (' EY P ort Chennai ')
, (' EY Old Park ')
, (' EY ')
, (' EY ')
,(''),(null),('d
f');
SELECT col_1 AS INPUT,
LTRIM(RTRIM(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(col_1,CHAR(10),' ')
,CHAR(11),' ')
,CHAR(12),' ')
,CHAR(13),' ')
,CHAR(14),' ')
,CHAR(160),' ')
,CHAR(13)+CHAR(10),' ')
,CHAR(9),' ')
,' ',CHAR(17)+CHAR(18))
,CHAR(18)+CHAR(17),'')
,CHAR(17)+CHAR(18),' ')
)) AS [OUTPUT]
FROM @Tbl;
In bootstrap 4.1, the w-100 class is required along with img-fluid for images smaller than the page to be stretched:
<div class="container">
<div class="row">
<img class='img-fluid w-100' src="#" alt="" />
</div>
</div>
see closed issue: https://github.com/twbs/bootstrap/issues/20830
(As of 2018-04-20, the documentation is wrong: https://getbootstrap.com/docs/4.1/content/images/ says that img-fluid applies max-width: 100%; height: auto;" but img-fluid does not resolve the issue, and neither does manually adding those style attributes with or without bootstrap classes on the img tag.)
http://blog.parkji.co.uk/2013/08/11/native-drag-and-drop-in-angularjs.html This is simple method for creating native draggable angularJS elements
I had an almost identical error:
Error while connecting to MySQL: Authentication plugin 'caching_sha2_password' is not supported
The solution for me was simple:
My db username/password creds were incorrect. The error was not descriptive of the problem, so I thought I would share this in case someone else runs into this.
You will have a server key something like this AIzaSyDiTEVq4Li1pj7IyraRlyRU9adc-49-KVY available in the Settings section of firebase console console.firebase.google.com/project/project-XXXXXXXXXXXXX/settings/cloudmessaging.
Specify the correct key with your code and try again.
Array.from(myMap.keys())
does not work in google application scripts.
Trying to use it results in the error TypeError: Cannot find function from in object function Array() { [native code for Array.Array, arity=1] }
.
To get a list of keys in GAS do this:
var keysList = Object.keys(myMap);
According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.
You can input variables via switch -e
$ gnuplot -e "filename='foo.data'" foo.plg
In foo.plg you can then use that variable
$ cat foo.plg
plot filename
pause -1
To make "foo.plg" a bit more generic, use a conditional:
if (!exists("filename")) filename='default.dat'
plot filename
pause -1
Note that -e
has to precede the filename otherwise the file runs before the -e
statements. In particular, running a shebang gnuplot #!/usr/bin/env gnuplot
with ./foo.plg -e ...
CLI arguments will ignore use the arguments provided.
CSS 'fixed' solution (like Facebook does):
body_temp = $("<div class='body_temp' />")
.append($('body').contents())
.css('position', 'fixed')
.css('top', "-" + scrolltop + 'px')
.width($(window).width())
.appendTo('body');
to toggle to normal state:
var scrolltop = Math.abs($('.body_temp').position().top);
$('body').append($('.body_temp').contents()).scrollTop(scrolltop);
Since the return
statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).
The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if
condition is false anyway.
Note that Python supports a syntax that allows you to use only one return
statement in your case:
return A+1 if A > B else A-1
If, for example, x = 5 and is stored as string, you can also just:
x = x + 0
and the new x would be stored as a numeric value.
Just before executing the query: alter session set NLS_DATE_FORMAT = "DD.MM.YYYY HH24:MI:SS"; or whichever format you are giving the information to the date function. This should fix the ORA error
Unless you have more style sheets than that, you've messed up your break points:
#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)
The 3rd media query is probably meant to be min-width: 901px
. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.
Edit for updated question:
(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)
Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width
for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:
(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)
Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.
use array_rand()
see php manual -> http://php.net/manual/en/function.array-rand.php
One simple solution to this is to replace the item being changed in the ObservableCollection which notifies the collection of the changed item. In the sample code snippet below Artists is the ObservableCollection and artist is an item of the type in the ObservableCollection:
var index = Artists.IndexOf(artist);
Artists.RemoveAt(index);
artist.IsFollowed = true; // change something in the item
Artists.Insert(index, artist);
I wrote this method:
private string GetUrlParameter(HttpRequestBase request, string parName)
{
string result = string.Empty;
var urlParameters = HttpUtility.ParseQueryString(request.Url.Query);
if (urlParameters.AllKeys.Contains(parName))
{
result = urlParameters.Get(parName);
}
return result;
}
And I call it like this:
string fooBar = GetUrlParameter(Request, "FooBar");
if (!string.IsNullOrEmpty(fooBar))
{
}
You should have a look on the -regextype
argument of find
, see manpage:
-regextype type
Changes the regular expression syntax understood by -regex and -iregex
tests which occur later on the command line. Currently-implemented
types are emacs (this is the default), posix-awk, posix-basic,
posix-egrep and posix-extended.
I guess the emacs
type doesn't support the [[:digit:]]
construct. I tried it with posix-extended
and it worked as expected:
find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'
You need to use delimiters with regexes in PHP. You can use the often used /
, but PHP lets you use any matching characters, so @
and #
are popular.
If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote()
.
First, you should read how function invocation works in JavaScript. I suspect that alone is enough to answer your question. But here's a summary of what is happening:
Array.prototype.slice
extracts the slice
method from Array
's prototype. But calling it directly won't work, as it's a method (not a function) and therefore requires a context (a calling object, this
), otherwise it would throw Uncaught TypeError: Array.prototype.slice called on null or undefined
.
The call()
method allows you to specify a method's context, basically making these two calls equivalent:
someObject.slice(1, 2);
slice.call(someObject, 1, 2);
Except the former requires the slice
method to exist in someObject
's prototype chain (as it does for Array
), whereas the latter allows the context (someObject
) to be manually passed to the method.
Also, the latter is short for:
var slice = Array.prototype.slice;
slice.call(someObject, 1, 2);
Which is the same as:
Array.prototype.slice.call(someObject, 1, 2);
"Reuse types" is not always the problem when this error occurs.
When adding a reference to an older service, click 'advanced' and there 'Add Web Reference'. Now link to your wsdl and everything should be working.
You can access the code values for the characters in your string using the ord()
built-in function. If you then need to format this in binary, the string.format()
method will do the job.
a = "test"
print(' '.join(format(ord(x), 'b') for x in a))
(Thanks to Ashwini Chaudhary for posting that code snippet.)
While the above code works in Python 3, this matter gets more complicated if you're assuming any encoding other than UTF-8. In Python 2, strings are byte sequences, and ASCII encoding is assumed by default. In Python 3, strings are assumed to be Unicode, and there's a separate bytes
type that acts more like a Python 2 string. If you wish to assume any encoding other than UTF-8, you'll need to specify the encoding.
In Python 3, then, you can do something like this:
a = "test"
a_bytes = bytes(a, "ascii")
print(' '.join(["{0:b}".format(x) for x in a_bytes]))
The differences between UTF-8 and ascii encoding won't be obvious for simple alphanumeric strings, but will become important if you're processing text that includes characters not in the ascii character set.
you can also print the data onto your HTML/JSP document. like:-
<!DOCTYPE html>
<html>
<head>
<title>Jsp Sample</title>
<%@page import="java.sql.*;"%>
</head>
<body bgcolor=yellow>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection)DriverManager.getConnection(
"jdbc:mysql://localhost:3306/forum","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student;");
%><table border=1 align=center style="text-align:center">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>SKILL</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<%while(rs.next())
{
%>
<tr>
<td><%=rs.getString("id") %></td>
<td><%=rs.getString("name") %></td>
<td><%=rs.getString("skill") %></td>
<td><%=rs.getString("action") %></td>
</tr>
<%}%>
</tbody>
</table><br>
<%}
catch(Exception e){
out.print(e.getMessage());%><br><%
}
finally{
st.close();
con.close();
}
%>
</body>
</html>
<!--executeUpdate() mainupulation and executeQuery() for retriving-->
This function will recursively put only files into a list.
import os
def ls_files(dir):
files = list()
for item in os.listdir(dir):
abspath = os.path.join(dir, item)
try:
if os.path.isdir(abspath):
files = files + ls_files(abspath)
else:
files.append(abspath)
except FileNotFoundError as err:
print('invalid directory\n', 'Error: ', err)
return files
In WPF, the background is not a Color
, it is a Brush
. So, try this for starters:
using System.Windows.Media;
// ....
ButtonToday.Background = new SolidColorBrush(Colors.Red);
More sensibly, though, you should probably look at doing this in your Xaml instead of in code.
Try This Code Here I created a table for get primary key column in oracle which is called test and then query
create table test
(
id int,
name varchar2(20),
city varchar2(20),
phone int,
constraint pk_id_name_city primary key (id,name,city)
);
SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TEST' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner ORDER BY cols.table_name, cols.position;
EDIT: As pointed out in the comment, itoa()
is not a standard, so better use sprintf() approach suggested in the rivaling answer!
You can use itoa()
function to convert your integer value to a string.
Here is an example:
int num = 321;
char snum[5];
// convert 123 to string [buf]
itoa(num, snum, 10);
// print our string
printf("%s\n", snum);
If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.
Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.
To change the priority of the connections:
You can create a boolean field and check it inside run:
public class Task implements Runnable {
private volatile boolean isRunning = true;
public void run() {
while (isRunning) {
//do work
}
}
public void kill() {
isRunning = false;
}
}
To stop it just call
task.kill();
This should work.
private boolean isGpsEnabled()
{
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
console.log(typeof json_data !== 'undefined'
? json_data.length : 'There is no spoon.');
...or more simply...
console.log(json_data ? json_data.length : 'json_data is null or undefined');
Have you changed the mode of the files?
I did it on my machine and the local dev machine had 777 given to all the files whereas the repo had 755 which showed every file as modified. I did git diff
and it showed the old mode and new mode are different.
If that is the problem then you can easily ignore them by
git config core.filemode false
Cheers
You can use Gson like below
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(object);
From the post JSON pretty print using Gson
Alternatively, You can use Jackson like below
ObjectMapper mapper = new ObjectMapper();
String perttyStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
From the post Pretty print JSON in Java (Jackson)
Hope this help!
Use it like this to allow for single space.
$newtag = preg_replace("/[^a-zA-Z0-9\s]/", "", $tag)
Here is a javascript code to add users.
Start mongod
with --auth = true
Access admin database from mongo shell and pass the javascript file.
mongo admin "Filename.js"
"Filename.js"
// Adding admin user
db.addUser("admin_username", " admin_password");
// Authenticate admin user
db.auth("admin_username ", " admin_password ");
// use database code from java script
db = db.getSiblingDB("newDatabase");
// Adding newDatabase database user
db.addUser("database_username ", " database_ password ");
Now user addition is complete, we can verify accessing the database from mongo shell
So, there is a simple fix for this. It is admittedly awkward, but it works. xcopy will not prompt to find out if the destination is a directory or file IF the new file(filename) already exists. If you precede your xcopy command with a simple echo to the new filename, it will overwrite the empty file. Example
echo.>newfile.txt
xcopy oldfile.txt newfile.txt /Y
This works like a charm in AutoCad VBA and I grabbed it from an excel forum. I don't know why you all make it so complicated?
FREQUENTLY ASKED QUESTIONS
Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to create it using VBA code. How can I do this?
Answer: You can test to see if a directory exists using the VBA code below:
(Quotes below are omitted to avoid confusion of programming code)
If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then
MkDir "c:\TOTN\Excel\Examples"
End If
I face this problem on daily basis, so to resolve this I kill adb.exe by executing following command :
taskkill /f /im adb.exe
Note : You should have administrative rights to execute the above command.
You've accidentally set "Pause on Exceptions" to all/uncaught exceptions.
Go to the "Sources" tab. At the bottom toolbar, toggle the button that looks like the pause symbol surrounded by a circle (4th button from the left) until the color of the circle turns black to turn it off.
If you're on a shared hosting environment you won't have access to the php.ini to make these changes, if you need access, a virtual private server (VPS) or a dedicated server may be a better option if you're confident in managing it yourself.
Alternatively if you create a new file called .htaccess in your root of your web directory (Ensure it doesn't contain a .txt extension if using notepad to create the file) and copy something like this inside.
php_value settingToChange 6000
This will only work if your hosting provider let's you override the certain config value. Best to ask if it doesn't work after trying.
If you give the enum a raw Int value it will make looping much easier.
For example, you can use anyGenerator
to get a generator that can enumerate across your values:
enum Suit: Int, CustomStringConvertible {
case Spades, Hearts, Diamonds, Clubs
var description: String {
switch self {
case .Spades: return "Spades"
case .Hearts: return "Hearts"
case .Diamonds: return "Diamonds"
case .Clubs: return "Clubs"
}
}
static func enumerate() -> AnyGenerator<Suit> {
var nextIndex = Spades.rawValue
return anyGenerator { Suit(rawValue: nextIndex++) }
}
}
// You can now use it like this:
for suit in Suit.enumerate() {
suit.description
}
// or like this:
let allSuits: [Suit] = Array(Suit.enumerate())
However, this looks like a fairly common pattern, wouldn't it be nice if we could make any enum type enumerable by simply conforming to a protocol? Well with Swift 2.0 and protocol extensions, now we can!
Simply add this to your project:
protocol EnumerableEnum {
init?(rawValue: Int)
static func firstValue() -> Int
}
extension EnumerableEnum {
static func enumerate() -> AnyGenerator<Self> {
var nextIndex = firstRawValue()
return anyGenerator { Self(rawValue: nextIndex++) }
}
static func firstRawValue() -> Int { return 0 }
}
Now any time you create an enum (so long as it has an Int raw value), you can make it enumerable by conforming to the protocol:
enum Rank: Int, EnumerableEnum {
case Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
}
// ...
for rank in Rank.enumerate() { ... }
If your enum values don't start with 0
(the default), override the firstRawValue
method:
enum DeckColor: Int, EnumerableEnum {
case Red = 10, Blue, Black
static func firstRawValue() -> Int { return Red.rawValue }
}
// ...
let colors = Array(DeckColor.enumerate())
The final Suit class, including replacing simpleDescription
with the more standard CustomStringConvertible protocol, will look like this:
enum Suit: Int, CustomStringConvertible, EnumerableEnum {
case Spades, Hearts, Diamonds, Clubs
var description: String {
switch self {
case .Spades: return "Spades"
case .Hearts: return "Hearts"
case .Diamonds: return "Diamonds"
case .Clubs: return "Clubs"
}
}
}
// ...
for suit in Suit.enumerate() {
print(suit.description)
}
Swift 3 syntax:
protocol EnumerableEnum {
init?(rawValue: Int)
static func firstRawValue() -> Int
}
extension EnumerableEnum {
static func enumerate() -> AnyIterator<Self> {
var nextIndex = firstRawValue()
let iterator: AnyIterator<Self> = AnyIterator {
defer { nextIndex = nextIndex + 1 }
return Self(rawValue: nextIndex)
}
return iterator
}
static func firstRawValue() -> Int {
return 0
}
}
In case you don't want to pollute your model with annotations and want to perform some custom operations, you could use mixins.
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.setMixInAnnotation(Person.class, PersonMixin.class);
mapper.registerModule(simpleModule);
Override age:
public abstract class PersonMixin {
@JsonSerialize(using = PersonAgeSerializer.class)
public String age;
}
Do whatever you need with the age:
public class PersonAgeSerializer extends JsonSerializer<Integer> {
@Override
public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(String.valueOf(integer * 52) + " months");
}
}
Add this parameter to JAVA_OPTS
or to the command line in Maven:
-Dhttps.protocols=TLSv1.2
Divide and Conquer
Divide and Conquer works by dividing the problem into sub-problems, conquer each sub-problem recursively and combine these solutions.
Dynamic Programming
Dynamic Programming is a technique for solving problems with overlapping subproblems. Each sub-problem is solved only once and the result of each sub-problem is stored in a table ( generally implemented as an array or a hash table) for future references. These sub-solutions may be used to obtain the original solution and the technique of storing the sub-problem solutions is known as memoization.
You may think of DP = recursion + re-use
A classic example to understand the difference would be to see both these approaches towards obtaining the nth fibonacci number. Check this material from MIT.
Divide and Conquer approach
Dynamic Programming Approach
My key was password protected which was causing the problem, a working file is now listed below (for help of future googlers)
FROM ubuntu
MAINTAINER Luke Crooks "[email protected]"
# Update aptitude with new repo
RUN apt-get update
# Install software
RUN apt-get install -y git
# Make ssh dir
RUN mkdir /root/.ssh/
# Copy over private key, and set permissions
# Warning! Anyone who gets their hands on this image will be able
# to retrieve this private key file from the corresponding image layer
ADD id_rsa /root/.ssh/id_rsa
# Create known_hosts
RUN touch /root/.ssh/known_hosts
# Add bitbuckets key
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts
# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git
let httpParams = new HttpParams();
Object.keys(data).forEach(function (key) {
httpParams = httpParams.append(key, data[key]);
});
Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)
Going forward the object can be passed directly instead of HttpParams.
getCountries(data: any) {
// We don't need any more these lines
// let httpParams = new HttpParams();
// Object.keys(data).forEach(function (key) {
// httpParams = httpParams.append(key, data[key]);
// });
return this.httpClient.get("/api/countries", {params: data})
}
And just to be completely random for those who don't always want a black screen.
@(IF not "%1" == "max" (start /MAX cmd /Q /C %0 max&X)ELSE set A=0&set C=1&set V=A&wmic process where name="cmd.exe" CALL setpriority "REALTIME">NUL)&CLS
:Y
(IF %A% EQU 10 set A=A)&(IF %A% EQU 11 set A=B)&(IF %A% EQU 12 set A=C)&(IF %A% EQU 13 set A=D)&(IF %A% EQU 14 set A=E)&(IF %A% EQU 15 set A=F)
(IF %V% EQU 10 set V=A)&(IF %V% EQU 11 set V=B)&(IF %V% EQU 12 set V=C)&(IF %V% EQU 13 set V=D)&(IF %V% EQU 14 set V=E)&(IF %V% EQU 15 set V=F)
(IF %A% EQU %V% set A=0)
title %A%%V%%random%6%random%%random%%random%%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%&color %A%%V%&ECHO %random%%C%%random%%random%%random%%random%6%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%&(IF %C% EQU 46 (TIMEOUT /T 1 /NOBREAK>nul&set C=1&CLS&SET /A A=%random% %%15 +1&SET /A V=%random% %%15 +1)ELSE set /A C=%C%+1)&goto Y
This will change screen color also both are random.
Try this :
$('.close-button').on('click', function(){
$('.element').removeClass('grown');
$('.element').addClass('spot');
});
$('.element').on('click', function(){
$(this).removeClass('spot');
$(this).addClass('grown');
});
I hope I understood your question.
this is my test function that I use to check Memcache on the server
<?php
public function test()
{
// memcache test - make sure you have memcache extension installed and the deamon is up and running
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";
var_dump($get_result);
}
if you see something like this
Server's version: 1.4.5_4_gaa7839e
Store data in the cache (data will expire in 10 seconds)
Data from the cache:
object(stdClass)#3 (2) { ["str_attr"]=> string(4) "test" ["int_attr"]=> int(123) }
it means that everything is okay
Cheers!
If you wrapped your divs, like this:
<div id="main">
<div id="sidebar"></div>
<div id="page-wrap"></div>
</div>
You could use this styling:
#main {
width: 800px;
margin: 0 auto;
}
#sidebar {
width: 200px;
height: 400px;
background: red;
float: left;
}
#page-wrap {
width: 600px;
background: #ffffff;
height: 400px;
margin-left: 200px;
}
This is a slightly different look though, so I'm not sure it's what you're after. This would center all 800px
as a unit, not the 600px
centered with the 200px
on the left side. The basic approach is your sidebar floats left, but inside the main div, and the #page-wrap
has the width of your sidebar as it's left margin to move that far over.
Update based on comments: For this off-centered look, you can do this:
<div id="page-wrap">
<div id="sidebar"></div>
</div>
With this styling:
#sidebar {
position: absolute;
left: -200px;
width: 200px;
height: 400px;
background: red;
}
#page-wrap {
position: relative;
width: 600px;
background: #ffffff;
height: 400px;
margin: 0 auto;
}
Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:
If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:
Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:
Install the 2 components from 1 above
You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project
NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!
The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:
=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60
In Windows, capitalization in paths doesn't matter. In Linux it does.
When you autoload, use "Foo" not "foo".
I believe that will do the trick.
I think it works when you take it out of autoloading because codeigniter is smart enough to figure out the capitalization in the path and classes are case independent in php.
Try the Content-Disposition
header
Content-Disposition: attachment; filename=<file name.ext>
I have found that Android Studio gives me a warning that getColor()
is deprecated when trying to do this:
Button11.setBackgroundColor(getResources().getColor(R.color.red))
So I found doing the method below to be the simple, up-to-date solution:
Button11.setBackgroundColor(ContextCompat.getColor(context, R.color.red))
You want to avoid hard-coding in the color argument, as it is considered bad code style.
Edit: After using setBackgroundColor()
with my own button, I saw that the internal button padding expanded. I couldn't find any way of changing it back to having both height and width set to "wrap_content". Maybe its a bug.
It is simple as you don't even expect.
If the value is positive it loaded when the container starts
If the value is not positive than the servelet is loaded when the request is made.
USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
to get table counts
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';
this also works
USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();
You can use operator Contains
,
private void ContainColumn(string columnName, DataTable table)
{
DataColumnCollection columns = table.Columns;
if (columns.Contains(columnName))
{
....
}
}
Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.
document.body.style.cursor = 'wait';
You should never assume register_global_variables
is turned on. Even if it is, it's deprecated and you should never use it that way.
Refer directly to the $_POST
or $_GET
variables. Most likely your form is POSTing, so you'd want your code to look something along the lines of this:
<input type="hidden" name="date" id="hiddenField" value="<?php echo $_POST['date'] ?>" />
If this doesn't work for you right away, print out the $_POST
or $_GET
variable on the page that would have the hidden form field and determine exactly what you want and refer to it.
echo "<pre>";
print_r($_POST);
echo "</pre>";
You have to remove the semicolon in the css rule string:
$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
There are cases when they are necessary:
In code I work on I use explicit destructor call in allocators, I have implementation of simple allocator that uses placement new to return memory blocks to stl containers. In destroy I have:
void destroy (pointer p) {
// destroy objects by calling their destructor
p->~T();
}
while in construct:
void construct (pointer p, const T& value) {
// initialize memory with placement new
#undef new
::new((PVOID)p) T(value);
}
there is also allocation being done in allocate() and memory deallocation in deallocate(), using platform specific alloc and dealloc mechanisms. This allocator was used to bypass doug lea malloc and use directly for example LocalAlloc on windows.
I changed Scanner fin = new Scanner(file);
to Scanner fin = new Scanner(new File(file));
and it works perfectly now. I didn't think the difference mattered but there you go.
If you like to count duplicates on particular column(s):
len(df['one'])-len(df['one'].drop_duplicates())
If you want to count duplicates on entire dataframe:
len(df)-len(df.drop_duplicates())
Or simply you can use DataFrame.duplicated(subset=None, keep='first'):
df.duplicated(subset='one', keep='first').sum()
where
subset : column label or sequence of labels(by default use all of the columns)
keep : {‘first’, ‘last’, False}, default ‘first’
For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable
Solution 1: Not throwing an error, handle the error ourselves
async _fetch(request) {
const fetchResult = await fetch(request); //Making the req
const result = await fetchResult.json(); // parsing the response
if (fetchResult.ok) {
return result; // return success object
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
const error = new Error();
error.info = responseError;
return (error);
}
Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:
const userSaved = await apiCall(data); // calling fetch
if (userSaved instanceof Error) {
debug.log('Failed saving user', userSaved); // handle error
return;
}
debug.log('Success saving user', userSaved); // handle success
Solution 2: Throwing an error, using try/catch
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
let error = new Error();
error = { ...error, ...responseError };
throw (error);
}
Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:
try {
const userSaved = await apiCall(data); // calling fetch
debug.log('Success saving user', userSaved); // handle success
} catch (e) {
debug.log('Failed saving user', userSaved); // handle error
}
Solution 3: Using customer error
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
throw new ClassError(result.message, result.data, result.code);
}
And:
class ClassError extends Error {
constructor(message = 'Something went wrong', data = '', code = '') {
super();
this.message = message;
this.data = data;
this.code = code;
}
}
Hope it helped.
Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:
// All code to find the files are here and is working perfectly...
It doesn't make sense to call a API Controller from another controller on the same website.
This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...
I suspect that the SelectedItem property of the ComboBox does not change until the control has been validated (which occurs when the control loses focus), whereas the SelectedValue property changes whenever the user selects an item.
Here is a reference to the focus events that occur on controls:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx
I had the same problem in VS2017, Xamarin.Forms project. Reading this bug link:
https://bugzilla.xamarin.com/show_bug.cgi?id=33181#c53
To solve the problem in this case: Right-click on [xaml-file-name].xaml
, choose Properties
, then change the Build Action
to Content
then back to Embedded resource
.
This has a good general description: https://gephi.wordpress.com/tag/maven/
Let me make a few statement that can put the difference in focus:
We migrated our code base from Ant to Maven
All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.
Basic functionalities of a repository manager like Sonatype are:
Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:
file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode
data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file
To disable the constraint you have ALTER
the table using NOCHECK
ALTER TABLE [TABLE_NAME] NOCHECK CONSTRAINT [ALL|CONSTRAINT_NAME]
To enable you to have to use double CHECK:
ALTER TABLE [TABLE_NAME] WITH CHECK CHECK CONSTRAINT [ALL|CONSTRAINT_NAME]
Once completed, if you need to check the status, use this script to list the constraint status. Will be very helpfull:
SELECT (CASE
WHEN OBJECTPROPERTY(CONSTID, 'CNSTISDISABLED') = 0 THEN 'ENABLED'
ELSE 'DISABLED'
END) AS STATUS,
OBJECT_NAME(CONSTID) AS CONSTRAINT_NAME,
OBJECT_NAME(FKEYID) AS TABLE_NAME,
COL_NAME(FKEYID, FKEY) AS COLUMN_NAME,
OBJECT_NAME(RKEYID) AS REFERENCED_TABLE_NAME,
COL_NAME(RKEYID, RKEY) AS REFERENCED_COLUMN_NAME
FROM SYSFOREIGNKEYS
ORDER BY TABLE_NAME, CONSTRAINT_NAME,REFERENCED_TABLE_NAME, KEYNO
When trying to compile and use class Elsewhere
(from Earwicker's answer) I get:
error LNK2001: unresolved external symbol "private: static class StaticStuff Elsewhere::staticStuff" (?staticStuff@Elsewhere@@0VStaticStuff@@A)
It seems is not possible to initialize static attributes of non-integer types without putting some code outside the class definition (CPP).
To make that compile you can use "a static method with a static local variable inside" instead. Something like this:
class Elsewhere
{
public:
static StaticStuff& GetStaticStuff()
{
static StaticStuff staticStuff; // constructor runs once, single instance
return staticStuff;
}
};
And you may also pass arguments to the constructor or initialize it with specific values, it is very flexible, powerfull and easy to implement... the only thing is you have a static method containing a static variable, not a static attribute... syntaxis changes a bit, but still useful. Hope this is useful for someone,
Hugo González Castro.
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
I just faced the same issue, I managed to make it work on my machine, however the change I did is not the same way it is mentioned in the documentation so it could be an issue of angular version routing module, mine is Angular 7
It only worked when I changed the lazy module main route entry path with same path as configured at the app-routes.ts
routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
{path: '',
children: [{
path:'home',
loadChildren :'lazy module path'
}]
}];
routes configured at HomeModule
const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
{path: 'default', component: MyPageComponent},
]
instead of
const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
{path: 'default', component: MyPageComponent},
]
In my case, this problem was solved by clicking 'Kernel' (shown on the top of notebooks) and then 'Reconnect'.
Note Added: In some versions of Jupyter, there is not 'Reconnect'.
Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.
> def get_browser():
> """Get the browser (a "driver")."""
> # find the path with 'which chromedriver'
> path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
> 'venv/bin/chromedriver')
> download_dir = "/home/moose/selenium-download/"
> print("Is directory: {}".format(os.path.isdir(download_dir)))
>
> from selenium.webdriver.chrome.options import Options
> chrome_options = Options()
> chrome_options.add_experimental_option('prefs', {
> "plugins.plugins_list": [{"enabled": False,
> "name": "Chrome PDF Viewer"}],
> "download": {
> "prompt_for_download": False,
> "default_directory": download_dir
> }
> })
>
> browser = webdriver.Chrome(path_to_chromedriver,
> chrome_options=chrome_options)
> return browser
Expanding on your comment to SquareCog's reply, you could do:
INSERT INTO X VALUES(Y,Z) WHERE Y NOT IN (SELECT Y FROM X)
INSERT INTO X2 VALUES(Y2,Z2) WHERE Y2 NOT IN (SELECT Y FROM X2)
INSERT INTO X3 VALUES(Y3,Z3) WHERE Y3 NOT IN (SELECT Y FROM X3)
Here, I assume that column Y is present in all three tables. Note that performance will be poor if the tables are not indexed on Y.
Oh yeah, Y has a unique constraint on it--so they're indexed, and this should perform optimally.
Personally, I generally dislike return parameters for a number of reasons:
I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.
Here's another code example, this one a bit less trivial:
pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
pair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.first << endl;
cout << result.second << endl;
Does this print groundspeed and course, or course and groundspeed? It's not obvious.
Compare to this:
struct Velocity {
double speed;
double azimuth;
};
Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
double planeAirspeed, double planeCourse);
Velocity result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.speed << endl;
cout << result.azimuth << endl;
I think this is clearer.
So I think my first choice in general is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.
I am doing some basic array in JGrasp and found that with an accessor method for a char[][] array to use ('.') to place a single dot.
If using Angular CLI v7+, the webpack version is printed in the output of ng version
:
-> ng version
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 7.0.6
Node: 11.0.0
OS: darwin x64
Angular: 7.1.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, material, platform-browser
... platform-browser-dynamic, router
Package Version
-----------------------------------------------------------
@angular-devkit/architect 0.10.6
@angular-devkit/build-angular 0.10.6
@angular-devkit/build-optimizer 0.10.6
@angular-devkit/build-webpack 0.10.6
@angular-devkit/core 7.0.6
@angular-devkit/schematics 7.0.6
@angular/cli 7.0.6
@ngtools/webpack 7.0.6
@schematics/angular 7.0.6
@schematics/update 0.10.6
rxjs 6.3.3
typescript 3.1.6
webpack 4.19.1
If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.
Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.
If you really had to achieve this affect while keeping the children as position: absolute
, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.
Alternatively, just use float: left
/float:right
and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden
on the parent (or any other clearfix technique) to cause its height to expand to that of its children.
article {
position: relative;
overflow: hidden;
}
.one {
position: relative;
float: left;
margin-top: 10px;
margin-left: 10px;
background: red;
width: 30px;
height: 30px;
}
.two {
position: relative;
float: right;
margin-top: 10px;
margin-right: 10px;
background: blue;
width: 30px;
height: 30px;
}
Actually, a Swing component does have multiple dimensions, as:
SetBounds is a shortcut for setting current size plus location of the widget if you don't use any layout manager.
If you use a layout manager, it is the responsibility of the layout manager to lay out your components, taking into account the preferred size you set, and ensuring that the comonent never gets smaller than its minimumSize or bigger than its maximumSize.
In this case, the layoutManager will call setSize (or setBounds), and you can not really control the position or dimension of the component.
The whole point of using a layout manager is to have a platform and window-size independent way of laying out your components automatically, therefore you don't expect to call setSize from your code.
(Personal comment: There are buggy layout managers, I personally hate all of them and rolled my own, which offers the flexibility of MigLayout without the learning curve.)
Actually, the following works fine for me and creates new windows:
test.cmd:
@echo off
start test2.cmd
start test3.cmd
echo Foo
pause
test2.cmd
@echo off
echo Test 2
pause
exit
test3.cmd
@echo off
echo Test 3
pause
exit
Combine that with parameters to start
, such as /min
, as Moshe pointed out if you don't want the new windows to spawn in front of you.
yum -y remove php*
to remove all php packages then you can install the 5.6 ones.
Here is my solution. It works also with COM objects and allows to access collection/array items from COM objects.
public static object GetPropValue(this object obj, string name)
{
foreach (string part in name.Split('.'))
{
if (obj == null) { return null; }
Type type = obj.GetType();
if (type.Name == "__ComObject")
{
if (part.Contains('['))
{
string partWithoundIndex = part;
int index = ParseIndexFromPropertyName(ref partWithoundIndex);
obj = Versioned.CallByName(obj, partWithoundIndex, CallType.Get, index);
}
else
{
obj = Versioned.CallByName(obj, part, CallType.Get);
}
}
else
{
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
}
return obj;
}
private static int ParseIndexFromPropertyName(ref string name)
{
int index = -1;
int s = name.IndexOf('[') + 1;
int e = name.IndexOf(']');
if (e < s)
{
throw new ArgumentException();
}
string tmp = name.Substring(s, e - s);
index = Convert.ToInt32(tmp);
name = name.Substring(0, s - 1);
return index;
}
Use an call thru section, it works
<div id="content">
<section id="home">
...
</section>
Call the above the thru
<a href="#home">page1</a>
Scrolling needs jquery paste this.. on above to ending body closing tag..
<script>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
Take a look at onBeforeUnload
.
It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. Are you sure?";
}
</script>
Edit: Most browsers no longer allow a custom message for onbeforeunload
.
See this bug report from the 18th of February, 2016.
onbeforeunload dialogs are used for two things on the Modern Web:
1. Preventing users from inadvertently losing data.
2. Scamming users.In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.
Firefox already does this[...]
You can call UserPrincipal.FindByIdentity
inside System.DirectoryServices.AccountManagement
:
using System.DirectoryServices.AccountManagement;
using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}
Add a step attribute to the number input
<input type="number" step="0.01">
Source: http://blog.pamelafox.org/2012/05/triggering-numeric-keyboards-with-html5.html
I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.
MariaDB running on Raspbian - the file containing bind-address is hard to pinpoint. MariaDB have some not-very-helpful-info on the subject.
I used
# sudo grep -R bind-address /etc
to locate where the damn thing is.
I also had to set the privileges and hosts in the mysql like everyone above pointed out.
And also had some fun time opening the 3306 port for remote connections to my Raspberry Pi - finally used iptables-persistent.
All works great now.
Why not using pyvmomi original function SmartConnectNoSSL
.
They added this function on June 14, 2016
and named it ConnectNoSSL
, one day after they changed the name to SmartConnectNoSSL
, use that instead of by passing the warning with unnecessary lines of code in your project?
Provides a standard method for connecting to a specified server without SSL verification. Useful when connecting to servers with self-signed certificates or when you wish to ignore SSL altogether
service_instance = connect.SmartConnectNoSSL(host=args.ip,
user=args.user,
pwd=args.password)
Set the columns Width
property to be a proportional width such as *
Take a surprise from gnu11!
typedef struct {
uint8_t messType;
uint8_t ax; //axis
uint32_t position;
uint32_t velocity;
}TgotoData;
TgotoData tmpData = { 0 };
nothing is zero.
mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name
should probably be
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
Hibernate has its own sql features that is known as hibernate query language. for retriving data from database using hibernate.
String sql_query = "from employee"//user table name which is in database.
Query query = session.createQuery(sql_query);
//for fetch we need iterator
Iterator it=query.iterator();
while(it.hasNext())
{
s=(employee) it.next();
System.out.println("Id :"+s.getId()+"FirstName"+s.getFirstName+"LastName"+s.getLastName);
}
for fetch we need Iterator for that define and import package.
Try:
next(g)
Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.
You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.
And what is p->param?
Actually, it isn't clear what do you want to do
Entity Framework – Use a Guid as the primary key
Using a Guid as your tables primary key, when using Entity Framework, requires a little more effort than when using a integer. The setup process is straightforward, after you’ve read/been shown how to do it.
The process is slightly different for the Code First and Database First approaches. This post discusses both techniques.
Code First
Using a Guid as the primary key when taking the code first approach is simple. When creating your entity, add the DatabaseGenerated attribute to your primary key property, as shown below;
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
Entity framework will create the column as you would expect, with a primary key and uniqueidentifier data type.
codefirst-defaultvalue
Also notice, very important, that the default value on the column has been set to (newsequentialid())
. This generates a new sequential (continuous) Guid for each row. If you were so inclined, you could change this to newid()
), which would result in a completely random Guid for each new row. This will be cleared each time your database gets dropped and re-created, so this works better when taking the Database First approach.
Database First
The database first approach follows a similar line to the code first approach, but you’ll have to manually edit your model to make it work.
Ensure that you edit the primary key column and add the (newsequentialid()) or (newid()) function as the default value before doing anything.
Next, open you EDMX diagram, select the appropriate property and open the properties window. Ensure that StoreGeneratedPattern is set to identity.
databasefirst-model
No need to give your entity an ID in your code, that will be populated for you automatically after the entity has been commited to the database;
using (ApplicationDbContext context = new ApplicationDbContext())
{
var person = new Person
{
FirstName = "Random",
LastName = "Person";
};
context.People.Add(person);
context.SaveChanges();
Console.WriteLine(person.Id);
}
Important Note: Your Guid field MUST be a primary key, or this does not work. Entity Framework will give you a rather cryptic error message!
Summary
Guid (Globally Unique Identifiers) can easily be used as primary keys in Entity Framework. A little extra effort is required to do this, depending on which approach you are taking. When using the code first approach, add the DatabaseGenerated attribute to your key field. When taking the Database First approach, explicitly set the StoredGeneratedPattern to Identity on your model.
[1]: https://i.stack.imgur.com/IxGdd.png
[2]: https://i.stack.imgur.com/Qssea.png
This still loops through the cartesian product of the two lists, but it does it one line:
>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False
This also have the advantage that any
short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings
in linesX
. If you want to find multiple occurrences you could do something like this:
>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]
If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.
The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).
For this example, let's draw a RED pixel at position 100x50.
Mat foo;
int x=100, y=50;
Solution 1:
Create a macro function that obtains the pixel from the array.
#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
Solution 2:
Get's the pixel using the method ptr.
unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
i saw into Eclipse > Preferences>installed JREs > JRE Definition i found the directory of java_home so it's /Library/Java/JavaVirtualMachines/jdk1.7.0_17.jdk/Contents/Home
I'm planning to static import the following to allow for the method reference to be used inline:
public static <T> Predicate<T> not(Predicate<T> t) {
return t.negate();
}
e.g.
Stream<String> s = ...;
long nonEmptyStrings = s.filter(not(String::isEmpty)).count();
Update: Starting from Java-11, the JDK offers a similar solution built-in as well.
Aggregated List of Libraries
This works too
var i = 1;_x000D_
$('button').click(function() {_x000D_
$('#red').clone().appendTo('#test').prop('id', 'red' + i);_x000D_
i++; _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
<div id="test">_x000D_
<button>Clone</button>_x000D_
<div class="red" id="red">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<style>_x000D_
.red {_x000D_
width:20px;_x000D_
height:20px;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
</style>
_x000D_
1: Create a class WebMvcConfig and extend it as shown from the WebMvcConfiguration and override addCorsMappings method.
2: Most importantly don't forget to make it @Configuration annotation because it should be loaded with Main Spring class to allow Cross-Origin.
@Configuration
public class WebMvcCofig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
}
pcolor()
with the vmin
, vmax
parameters.It is detailed in this answer: https://stackoverflow.com/a/3376734/21974
var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"};
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;
In Visual Studio 2015 go to the Analyze Menu and select "Calculate Code Metrics".
For Vue2 this applies:
var bus = new Vue()
// in component A's method
bus.$emit('id-selected', 1)
// in component B's created hook
bus.$on('id-selected', function (id) {
// ...
})
See here for the Vue docs. And here is more detail on how to set up this event bus exactly.
If you'd like more info on when to use properties, events and/ or centralized state management see this article.
See below comment of Thomas regarding Vue 3.
If it's not a local application powered by JavaScript with full access permissions, you can't get the size of any file just from the path name. Web pages running javascript do not have access to the local filesystem for security reasons.
You can use a graceful degrading file uploader like SWFUpload if you want to show a progress bar. HTML5 also has the File API, but that is not widely supported just yet. If a user selects the file for an input[type=file]
element, you can get details about the file from the files
collection:
alert(myInp.files[0].size);
You definitely don't need to use the various different llvm-ar etc programs:
SET (CMAKE_AR "/usr/bin/llvm-ar") SET (CMAKE_LINKER "/usr/bin/llvm-ld") SET (CMAKE_NM "/usr/bin/llvm-nm") SET (CMAKE_OBJDUMP "/usr/bin/llvm-objdump") SET (CMAKE_RANLIB "/usr/bin/llvm-ranlib")
These are made to work on the llvm internal format and as such aren't useful to the build of your application.
As a note -O4 will invoke LTO on your program which you may not want (it will increase compile time greatly) and clang defaults to c99 mode so that flag isn't necessarily needed either.
Exception : java.net.ConnectException
This means your request didn't getting response from server in stipulated time. And their are some reasons for this exception:
Download
Call
ilmerge /target:winexe /out:c:\output.exe c:\input.exe C:\input.dll
Write below code in your MainActivity.java file instead of your code.
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i("clicks","You Clicked B1");
Intent i=new Intent(MainActivity.this, MainActivity2.class);
startActivity(i);
}
}
And Declare MainActivity2 into your Androidmanifest.xml file using below code.
<activity
android:name=".MainActivity2"
android:label="@string/title_activity_main">
</activity>
If you must load the gif image from URL, you can always embed the gif in an image tag in a UIWebView
.
No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.
$('input.yourClass:checkbox:checked').each(function () {
var sThisVal = $(this).val();
});
This would get all checkboxes of the class name "yourClass". I like this example since it uses the jQuery selector checked instead of doing a conditional check. Personally I would also use an array to store the value, then use them as needed, like:
var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
arr.push($(this).val());
});
I prefer to use @Transactional
on services layer at method level.
If you pass the -v
flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:
$ ansible-playbook -v playbook.yaml
Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:
[defaults]
log_path=/path/to/logfile
Ansible will look in several places for the config file:
ansible.cfg
in the current directory where you ran ansible-playbook
~/.ansible.cfg
/etc/ansible/ansible.cfg
Note, while the above answers are correct, if you want, you can do something like:
alert("The variable named x1 has value: " + x1);
In general for AnInterface
and anInstance
of any class:
AnInterface.class.isAssignableFrom(anInstance.getClass());
One solution (though not very pretty) is to use Apache common List/Set mutation
import org.apache.commons.collections.list.SetUniqueList;
final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());
it is a list without duplicates
All of these methods are great. I have found another simple resource that is a great example of creating a dynamic form using "onchange" with AJAX.
http://www.w3schools.com/php/php_ajax_database.asp
I simply modified the text table output to anther select dropdown populated based on the selection of the first drop down. For my application a user will select a state then the second dropdown will be populated with the cities for the selected state. Much like the JSON example above but with php and mysql.
C:\java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
prepend in front of bootstrap class path
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xloggc:<file> log GC status to a file with time stamps
-Xbatch disable background compilation
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
-Xprof output cpu profiling data
-Xfuture enable strictest checks, anticipating future default
-Xrs reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni perform additional checks for JNI functions
-Xshare:off do not attempt to use shared class data
-Xshare:auto use shared class data if possible (default)
-Xshare:on require using shared class data, otherwise fail.
The -X options are non-standard and subject to change without notice.
Just using:
$('.tag-class').removeAttr('style');
or
$('#tag-id').removeAttr('style');
Here is a DLL that shows:
* Hard drive ID (unique hardware serial number written in drive's IDE electronic chip)
* Partition ID (volume serial number)
* CPU ID (unique hardware ID)
* CPU vendor
* CPU running speed
* CPU theoretic speed
* Memory Load ( Total memory used in percentage (%) )
* Total Physical ( Total physical memory in bytes )
* Avail Physical ( Physical memory left in bytes )
* Total PageFile ( Total page file in bytes )
* Available PageFile( Page file left in bytes )
* Total Virtual( Total virtual memory in bytes )
* Available Virtual ( Virtual memory left in bytes )
* Bios unique identification numberBiosDate
* Bios unique identification numberBiosVersion
* Bios unique identification numberBiosProductID
* Bios unique identification numberBiosVideo
(text grabbed from original web site)
It works with C#.
you have to generate ssh key and add it in your github account in settings go to your project where you clone inside that run these command.-
1-ssh-keygen -t rsa -b 4096 -C "[email protected]"
after the command you will get some options path and name can be leave empty and you can put password.
2-eval $(ssh-agent -s) .
3-ssh-add ~/.ssh/id_rsa
after this command you have to put same password that you created in 1st command
and after that you can check your default home directory or whatever directory it is showing on the terminal .pub file open and copy the key and past in github settings new ssh
In preferences Java -> Code Style -> Formatter, edit the profile. Under the Line Wrapping tab is the primary option for line width (Maximum line width:). In the Comments tab you have a separate option Maximum line width for comments:, which will also need to be changed to affect comment wrapping.
You will need to make your own profile to make these changes in if you using one of the [Built-in]
ones. Just click "New..." on the formatter preferences page.
You can always abuse type juggling:
function zpad(int $value, int $pad): string {
return substr(1, $value + 10 ** $pad);
}
This wont work as expected if either 10 ** pad > INT_MAX
or value >= 10 * pad
.
I use this script to delete last 10 commands in history:
pos=$HISTCMD; start=$(( $pos-11 )); end=$(( $pos-1 )); for i in $(eval echo "{${start}..${end}}"); do history -d $start; done
It uses $HISTCMD
environment var to get the history index and uses that to delete last 10 entries in history
.
There are several solutions depending on what you need...
If you want to add a custom header (or set of headers) to an individual request then just add the headers
property:
// Request with custom header
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});
If you want to add a default header (or set of headers) to every request then use $.ajaxSetup()
:
$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
If you want to add a header (or set of headers) to every request then use the beforeSend
hook with $.ajaxSetup()
:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
Edit (more info): One thing to be aware of is that with ajaxSetup
you can only define one set of default headers and you can only define one beforeSend
. If you call ajaxSetup
multiple times, only the last set of headers will be sent and only the last before-send callback will execute.
Unfortunately, for a database independent solution, you will need to know everything about the column. If it is used in other tables as a foreign key, they will need to be modified as well.
ALTER TABLE MyTable ADD MyNewColumn OLD_COLUMN_TYPE;
UPDATE MyTable SET MyNewColumn = MyOldColumn;
-- add all necessary triggers and constraints to the new column...
-- update all foreign key usages to point to the new column...
ALTER TABLE MyTable DROP COLUMN MyOldColumn;
For the very simplest of cases (no constraints, triggers, indexes or keys), it will take the above 3 lines. For anything more complicated it can get very messy as you fill in the missing parts.
However, as mentioned above, there are simpler database specific methods if you know which database you need to modify ahead of time.
I met these warnings on mempcpy
function. Man page says this function is a GNU extension and synopsis shows:
#define _GNU_SOURCE
#include <string.h>
When #define
is added to my source before the #include
, declarations for the GNU extensions are made visible and warnings disappear.
Jackson and Gson are the most complete Java JSON packages regarding actual data binding support; many other packages only provide primitive Map/List (or equivalent tree model) binding. Both have complete support for generic types, as well, as enough configurability for many common use cases.
Since I am more familiar with Jackson, here are some aspects where I think Jackson has more complete support than Gson (apologies if I miss a Gson feature):
It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.
The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
public class BooksController : ApiController
{
// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query)
{
// ...
}
}
public class BookQuery
{
public string Author { get; set; }
public string Title { get; set; }
public string ISBN { get; set; }
public string SomethingElse { get; set; }
public DateTime? Date { get; set; }
}
It even supports multiple parameters, as long as the properties don't conflict.
// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
{
// ...
}
public class Paging
{
public string Sort { get; set; }
public int Skip { get; set; }
public int Take { get; set; }
}
Update:
In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.
This is one of the very good and step by step process to set up PostgreSQL
in ubuntu server. I have tried it with Ubuntu 16.04
and its working.
Untested, but there are some binaries available at:
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
Some other options, just for reference
-10.days.ago
# Available in Rails 4
DateTime.now.days_ago(-10)
Just list out all options I know:
[1] Time.now + 10.days
[2] 10.days.from_now
[3] -10.days.ago
[4] DateTime.now.days_ago(-10)
[5] Date.today + 10
So now, what is the difference between them if we care about the timezone:
[1, 4]
With system timezone[2, 3]
With config timezone of your Rails app[5]
Date only no time included in resultIE 5 through 8 has a bug where using delete on properties of a host object (Window, Global, DOM etc) throws TypeError "object does not support this action".
var el=document.getElementById("anElementId");
el.foo = {bar:"baz"};
try{
delete el.foo;
}catch(){
//alert("Curses, drats and double double damn!");
el.foo=undefined; // a work around
}
Later if you need to check where the property has a meaning full value use el.foo !== undefined
because "foo" in el
will always return true in IE.
If you really need the property to really disappear...
function hostProxy(host){
if(host===null || host===undefined) return host;
if(!"_hostProxy" in host){
host._hostproxy={_host:host,prototype:host};
}
return host._hostproxy;
}
var el=hostProxy(document.getElementById("anElementId"));
el.foo = {bar:"baz"};
delete el.foo; // removing property if a non-host object
if your need to use the host object with host api...
el.parent.removeChild(el._host);
You can create a function which would allow you to do the same as timeout but also for other functions:
function run_cmd {
cmd="$1"; timeout="$2";
grep -qP '^\d+$' <<< $timeout || timeout=10
(
eval "$cmd" &
child=$!
trap -- "" SIGTERM
(
sleep $timeout
kill $child 2> /dev/null
) &
wait $child
)
}
And could run as below:
run_cmd "echoFooBar" 10
Note: The solution came from one of my questions: Elegant solution to implement timeout for bash commands and functions
If you need to get current position in form's area(got experimentally), try:
Console.WriteLine("Current mouse position in form's area is " +
(Control.MousePosition.X - this.Location.X - 8).ToString() +
"x" +
(Control.MousePosition.Y - this.Location.Y - 30).ToString()
);
Although, 8 and 30 integers were found by experimenting.
Would be awesome if someone could explain why exactly these numbers ^.
Also, there's another variant(considering code is in Form's CodeBehind):
Point cp = PointToClient(Cursor.Position); // Getting a cursor's position according form's area
Console.WriteLine("Cursor position: X = " + cp.X + ", Y = " + cp.Y);
the best explanation i've found is this:
What is the difference betwen INTEGER and NUMBER? When should we use NUMBER and when should we use INTEGER? I just wanted to update my comments here...
NUMBER always stores as we entered. Scale is -84 to 127. But INTEGER rounds to whole number. The scale for INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It means, INTEGER is constrained number. The decimal place will be rounded. But NUMBER is not constrained.
INTEGER is always slower then NUMBER. Since integer is a number with added constraint. It takes additional CPU cycles to enforce the constraint. I never watched any difference, but there might be a difference when we load several millions of records on the INTEGER column. If we need to ensure that the input is whole numbers, then INTEGER is best option to go. Otherwise, we can stick with NUMBER data type.
Here is the link
My solution based on Mahdi Hijazi answer, but without any custom views:
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:id="@+id/scrollVertical"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<WateverViewYouWant/>
</ScrollView>
</HorizontalScrollView>
final HorizontalScrollView hScroll = (HorizontalScrollView) value.findViewById(R.id.scrollHorizontal);
final ScrollView vScroll = (ScrollView) value.findViewById(R.id.scrollVertical);
vScroll.setOnTouchListener(new View.OnTouchListener() { //inner scroll listener
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
hScroll.setOnTouchListener(new View.OnTouchListener() { //outer scroll listener
private float mx, my, curX, curY;
private boolean started = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
curX = event.getX();
curY = event.getY();
int dx = (int) (mx - curX);
int dy = (int) (my - curY);
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (started) {
vScroll.scrollBy(0, dy);
hScroll.scrollBy(dx, 0);
} else {
started = true;
}
mx = curX;
my = curY;
break;
case MotionEvent.ACTION_UP:
vScroll.scrollBy(0, dy);
hScroll.scrollBy(dx, 0);
started = false;
break;
}
return true;
}
});
You can change the order of the scrollviews. Just change their order in layout and in the code. And obviously instead of WateverViewYouWant you put the layout/views you want to scroll both directions.
Convert PPK to OpenSSh
OS X: Install Homebrew, then run
brew install putty
Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search
To generate the private key:
cd ~
puttygen id_dsa.ppk -O private-openssh -o id_dsa
and to generate the public key:
puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub
Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:
mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub
connect with ssh server
ssh -i ~/.ssh/id_dsa username@servername
Port Forwarding to connect mysql remote server
ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName
Java Closures are going to be a part of J2SE 8 and is set to be released by the end of 2012.
Java 8's closures support include the concept of Lambda Expressions, Method Reference, Constructor Reference and the Default Methods.
For more information and working examples for this please visit: http://amitrp.blogspot.in/2012/08/at-first-sight-with-closures-in-java.html
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
AndroidManifest.xml
<activity ...
android:theme="@style/FullScreenTheme"
>
</activity>
For hide ActionBar / StatusBar
style.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
...
</style>
<style name="FullScreenTheme" parent="AppTheme">
<!--this property will help hide the ActionBar-->
<item name="windowNoTitle">true</item>
<!--currently, I don't know why we need this property since use windowNoTitle only already help hide actionbar. I use it because it is used inside Theme.AppCompat.Light.NoActionBar (you can check Theme.AppCompat.Light.NoActionBar code). I think there are some missing case that I don't know-->
<item name="windowActionBar">false</item>
<!--this property is used for hiding StatusBar-->
<item name="android:windowFullscreen">true</item>
</style>
To hide the system navigation bar
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
setContentView(R.layout.activity_main)
...
}
}
For hide ActionBar / StatusBar
style.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
...
</style>
<style name="FullScreenTheme" parent="AppTheme">
<!--don't need any config for hide ActionBar because our apptheme is NoActionBar-->
<!--this property is use for hide StatusBar-->
<item name="android:windowFullscreen">true</item> //
</style>
To hide the system navigation bar
Similar like Theme.AppCompat.Light.DarkActionBar
.
There exists now a dedicated bash script plugin called "Bash editor". It's available at eclipse market place:
You can find it at https://marketplace.eclipse.org/content/bash-editor or by marketplace client when searching for "bash".
The plugin does also provide a debugger. Inisde official Bash Editor
YouTube playlist you can find some tutorials about usage etc.
PS: I am the author of the mentioned plugin.
Here's another way
Sub testborder()
Dim rRng As Range
Set rRng = Sheet1.Range("B2:D5")
'Clear existing
rRng.Borders.LineStyle = xlNone
'Apply new borders
rRng.BorderAround xlContinuous
rRng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
rRng.Borders(xlInsideVertical).LineStyle = xlContinuous
End Sub
Here's how to do it inside ViewModel
and FusedLocationProviderClient
, code in Kotlin
locationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val position = CameraPosition.Builder()
.target(LatLng(it.latitude, it.longitude))
.zoom(15.0f)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
}
}
From Interface Builder:
Programmatically:
SWift 4
Using label extension
extension UILabel {
func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {
guard let labelText = self.text else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = lineHeightMultiple
let attributedString:NSMutableAttributedString
if let labelattributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelattributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// Line spacing attribute
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
Now call extension function
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) . // try values 1.0 to 5.0
// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0
Or using label instance (Just copy & execute this code to see result)
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
Swift 3
let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
Define the expected and desired output for a normal case, with correct input.
Now, implement the test by declaring a class, name it anything (Usually something like TestAddingModule), and add the testAdd method to it (i.e. like the one below) :
assertEquals(expectedVal,calculatedVal)
.Test your method by running it (in Eclipse, right click, select Run as ? JUnit test).
//for normal addition
@Test
public void testAdd1Plus1()
{
int x = 1 ; int y = 1;
assertEquals(2, myClass.add(x,y));
}
Add other cases as desired.
Test that your method handles Null inputs gracefully (example below).
//if you are using 0 as default for null, make sure your class works in that case.
@Test
public void testAdd1Plus1()
{
int y = 1;
assertEquals(0, myClass.add(null,y));
}
<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}
</style>
</head>
<body>
<div class="scroll">You can use the overflow property when you want to have better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>
</body>
</html>
$('#my_sel').val($('#my_sel option:selected').next().val());
$('#my_sel').val($('#my_sel option:selected').prev().val());
The compiled dll should have public Class.
I feel this answer will be very simple and easy to understand.
int print1000(int num=1)
{
printf("%d\n", num);
// it will check first the num is less than 1000.
// If yes then call recursive function to print
return num<1000 && print1000(++num);
}
int main()
{
print1000();
return 0;
}
Your datatype is wrong, change datatype for dataType.
For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.
// server.js
// ==================
// BASE SETUP
// import the packages we need
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Logger
app.use(morgan('dev'));
// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------
//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === "OPTIONS")
res.send(200);
else
next();
}
// -------------------------------------------------------------
// STACKOVERFLOW -- END OF THIS SECTION, ONE MORE SECTION BELOW
// -------------------------------------------------------------
// =================================================
// ROUTES FOR OUR API
var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");
// ======================================================
// REGISTER OUR ROUTES with app
// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------
app.use(allowCrossDomain);
// -------------------------------------------------------------
// STACKOVERFLOW -- OK THAT IS THE LAST THING.
// -------------------------------------------------------------
app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);
// =================
// START THE SERVER
var port = process.env.PORT || 8080; // set our port
app.listen(port);
console.log('API Active on port ' + port);
If you are planning to use JdbcTemplate in multiple locations, it would be a good idea to create a Spring Bean for it.
Using Java Config it would be:
@Configuration
public class DBConfig {
@Bean
public DataSource dataSource() {
//create a data source
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
@Bean
public TransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
Then a repository that uses that JdbcTemplate could be:
@Repository
public class JdbcSomeRepository implements SomeRepository {
private final JdbcTemplate jdbcTemplate ;
@Autowired
public JdbcSomeRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
@Transactional
public int someUpdate(SomeType someValue, SomeOtherType someOtherValue) {
return jdbcTemplate.update("INSERT INTO SomeTable(column1, column2) VALUES(?,?)", someValue, someOtherValue)
}
}
The update method from JdbcTemplate that I have used can be found here.
Transform Rotate and Translate in single line css:-How?
div.className{_x000D_
transform : rotate(270deg) translate(-50%, 0); _x000D_
-webkit-transform: rotate(270deg) translate(-50%, -50%); _x000D_
-moz-transform: rotate(270deg) translate(-50%, -50%); _x000D_
-ms-transform: rotate(270deg) translate(-50%, -50%); _x000D_
-o-transform: rotate(270deg) translate(-50%, -50%); _x000D_
float:left;_x000D_
position:absolute;_x000D_
top:50%;_x000D_
left:50%;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="className">_x000D_
<span style="font-size:50px">A</span>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
If I get you right, you need ..\..\src
It's because size_t can be anything other than an int (maybe a struct). The idea is that it decouples it's job from the underlying type.
For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'});
only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)
It could just be something that runs once the first time you initialize collapse with those parameters.
You will have more luck using the show
and hide
methods.
Here is an example:
$(function() {
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('.collapse-init').on('click', function() {
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
$('.panel-collapse').collapse('show');
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
});
});
Update
Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.
I don't understand what's going on or why the show
seemed to be toggling in some places.
But After messing around for a while.. Finally came with the following solution:
$(function() {
var transition = false;
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('#accordion').on('show.bs.collapse',function(){
if($active){
$('#accordion .in').collapse('hide');
}
});
$('#accordion').on('hidden.bs.collapse',function(){
if(transition){
transition = false;
$('.panel-collapse').collapse('show');
}
});
$('.collapse-init').on('click', function() {
$('.collapse-init').prop('disabled','true');
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
if($('.panel-collapse.in').length){
transition = true;
$('.panel-collapse.in').collapse('hide');
}
else{
$('.panel-collapse').collapse('show');
}
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
setTimeout(function(){
$('.collapse-init').prop('disabled','');
},800);
});
});
Try something like
$("#container").on('click', 'someLinkSelector', function(){ $("#container").html( <new html with new spans> ) });
You basically need to attach your events from a non-dynamic part of the DOM so it can watch for dynamically-created elements.
Simple swift 3 solution - add code to viewDidLoad:
let indentView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 20))
textField.leftView = indentView
textField.leftViewMode = .always
No need for ridiculously long code
There is a simple solution if you can install and use puttygen tool. Below are the steps. You should have the passphrase of the private key.
step 1: Download latest puttygen and open puttygen
step 2: Load your existing private key file, see below image
step 3: Enter passphrase for key if asked and hit ok
step 4: as shown in the below image select "conversion" menu tab and select "Export OpenSSH key"
Save new private key file at preferred location and use accordingly.
Add your php folder path to the System PATH and everything should work fine. It will also fix some other extensions that are broken.
var array = string.split(',')
and good morning, too, since I have to type 30 chars ...
Step 1: Create separate component like this
Component name : pagebase.js
Step 2: Inside this use code this
export const BASE_URL = "http://192.168.10.10:4848/";
export const API_KEY = 'key_token';
Step 3: Use it in any component, for using it first import this component then use it. Import it and use it:
import * as base from "./pagebase";
base.BASE_URL
base.API_KEY
I believe that the problem is that the WebRequest
measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager
will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit
which by default gets the value from ServicePointManager.DefaultConnectionLimit
. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.
I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint
limitation.
Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest
does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.
And yes, you must code your app around the WebRequest.BeginGetRequestStream
(for POST
s with content) and WebRequest.BeginGetResponse
(for GET
s and POSTS
s). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint
issue is orthogonal to this: the queueing behavior happens with async calls too.
I think you used somehow the right way to show the number only on the keyboard so better try the given line with xml in your edit text and it will work perfectly so here the code is-
android:inputType="number"
In case any doubt you can again ask to me i'll try to completely sort out your problem. Thanks
for (var key in data) {
alert("User " + data[key] + " is #" + key); // "User john is #234"
}
Some more pre-conditions are needed for the ones written by Bill K and dadinn
Object[] newArray = new Object[src.length - 1];
if (i > 0){
System.arraycopy(src, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}
return newArray;
What about this :
public static bool SafeInvoke( this Control control, MethodInvoker method )
{
if( control != null && ! control.IsDisposed && control.IsHandleCreated && control.FindForm().IsHandleCreated )
{
if( control.InvokeRequired )
{
control.Invoke( method );
}
else
{
method();
}
return true;
}
else return false;
}
You could use a regular expression like this
If Regex.IsMatch(number, "^[0-9 ]+$") Then
...
End If
Instead of #error, try redefining the macro, just before it is being used. Compilation will fail and compiler will provide the current value it thinks applies to the macro.
#define BOOST_VERSION blah
There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.
This being said, there are some things that you can indeed do:
You can place images within cells using IMAGE(URL)
, but they cannot be linked to Apps Script functions.
You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))
You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.
I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem
String fileContents = new File('/path/to/file').text
If you need to specify the character encoding, use the following instead:
String fileContents = new File('/path/to/file').getText('UTF-8')
I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:
var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();
to ckeck the status use the below command, which worked on debian....
/etc/init.d/mysql status
to start my sql server use the below command
/etc/init.d/mysql start
to stop the server use the below command
/etc/init.d/mysql stop
The AngularJS documentation on directives is pretty well written for what the symbols mean.
To be clear, you cannot just have
scope: '@'
in a directive definition. You must have properties for which those bindings apply, as in:
scope: {
myProperty: '@'
}
I strongly suggest you read the documentation and the tutorials on the site. There is much more information you need to know about isolated scopes and other topics.
Here is a direct quote from the above-linked page, regarding the values of scope
:
The scope property can be true, an object or a falsy value:
falsy: No scope will be created for the directive. The directive will use its parent's scope.
true
: A new child scope that prototypically inherits from its parent will be created for the directive's element. If multiple directives on the same element request a new scope, only one new scope is created. The new scope rule does not apply for the root of the template since the root of the template always gets a new scope.
{...}
(an object hash): A new "isolate" scope is created for the directive's element. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.
Retrieved 2017-02-13 from https://code.angularjs.org/1.4.11/docs/api/ng/service/$compile#-scope-, licensed as CC-by-SA 3.0
you can check which fragment is currently loaded by this
supportFragmentManager.addOnBackStackChangedListener {
val myFragment = supportFragmentManager.fragments.last()
if (null != myFragment && myFragment is HomeFragment) {
//HomeFragment is visible or currently loaded
} else {
//your code
}
}
Do not use passwords. Use peer authentication instead:
postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb
You should read the documentation on storing stuff externally on Android. There's a multitude of problems that could exist with your current code, and I think going over the documentation might help you iron them out.