By creating this function ([DelimitedSplit]) which splits a string, you could do an OUTER APPLY to your SELECT.
CREATE FUNCTION [dbo].[DelimitedSplit]
--===== Define I/O parameters
(@pString VARCHAR(8000), @pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE! IT WILL KILL PERFORMANCE!
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
-- enough to cover VARCHAR(8000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a INNER JOIN E1 b ON b.N = a.N), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a INNER JOIN E2 b ON b.N = a.N), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(@pString, l.N1, l.L1)
FROM cteLen l
;
TEST
CREATE TABLE #Testdata
(
SomeID INT,
OtherID INT,
String VARCHAR(MAX)
)
INSERT #Testdata SELECT 1, 9, '18,20,22'
INSERT #Testdata SELECT 2, 8, '17,19'
INSERT #Testdata SELECT 3, 7, '13,19,20'
INSERT #Testdata SELECT 4, 6, ''
INSERT #Testdata SELECT 9, 11, '1,2,3,4'
SELECT
*
FROM #Testdata
OUTER APPLY [dbo].[DelimitedSplit](String,',')
DROP TABLE #Testdata
RESULT
SomeID OtherID String ItemNumber Item
1 9 18,20,22 1 18
1 9 18,20,22 2 20
1 9 18,20,22 3 22
2 8 17,19 1 17
2 8 17,19 2 19
3 7 13,19,20 1 13
3 7 13,19,20 2 19
3 7 13,19,20 3 20
4 6 1
9 11 1,2,3,4 1 1
9 11 1,2,3,4 2 2
9 11 1,2,3,4 3 3
9 11 1,2,3,4 4 4
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
In hadoop1.0:
hadoop fs -rmr /PATH/ON/HDFS
In hadoop2.0:
hdfs dfs -rm -R /PATH/ON/HDFS
Use \
to escape ,
in path
The default separator between values in a group is comma(,). To specify any other separator, use SEPARATOR
as shown below.
SELECT GROUP_CONCAT(id SEPARATOR '|')
FROM `table_level`
WHERE `parent_id`=4
GROUP BY `parent_id`;
5|6|9|10|12|14|15|17|18|779
To eliminate the separator, then use SEPARATOR ''
SELECT GROUP_CONCAT(id SEPARATOR '')
FROM `table_level`
WHERE `parent_id`=4
GROUP BY `parent_id`;
Refer for more info GROUP_CONCAT
arrayList.toArray(new Custom[0]);
Including the header afxwin.h
signalizes use of MFC. The following instructions (based on those on CodeProject.com) could help to get MFC code compiling:
Download and install the Windows Driver Kit.
Select menu Tools > Options… > Projects and Solutions > VC++ Directories.
In the drop-down menu Show directories for select Include files.
Add the following paths (replace $(WDK_directory)
with the directory where you installed Windows Driver Kit in the first step):
$(WDK_directory)\inc\mfc42
$(WDK_directory)\inc\atl30
In the drop-down menu Show directories for select Library files and add (replace $(WDK_directory)
like before):
$(WDK_directory)\lib\mfc\i386
$(WDK_directory)\lib\atl\i386
In the $(WDK_directory)\inc\mfc42\afxwin.inl
file, edit the following lines (starting from 1033):
_AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const
{ return ((HMENU) menu) == m_hMenu; }
_AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const
{ return ((HMENU) menu) != m_hMenu; }
to
_AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const
{ return ((HMENU) menu) == m_hMenu; }
_AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const
{ return ((HMENU) menu) != m_hMenu; }
In other words, add BOOL
after _AFXWIN_INLINE
.
Im not sure this will solve your problem since I dont know where it originats from, but when I import a project i go File -> Import -> Existing projects into workspace. Maybe it will circumvent your problem.
Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.
In the case of local variables you can not use any kind of accessor (public, protected or private).
You should also know what the static keyword means. In method checkYourself
, you use the Integer array locations
.
The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.
public class Test { //Capitalized name for classes are used in Java
private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later.
public Test(int[] locations) {
this.locations = locations;//To access to class member, when method argument has the same name use `this` key word.
}
public boolean checkYourSelf(int value) { //This method is accessed only from a object.
for(int location : locations) {
if(location == value) {
return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
}
}
return false; //Method should be simple and perform one task. So you can get more flexibility.
}
public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it.
public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.
String result;
if(test.checkYourSelf(2)) {//We moved outside the string
result = "Hurray";
} else {
result = "Try again"
}
System.out.println(result); //We have only one place where write is done. Easy to change in future.
}
}
Use this line to get the division behavior you want:
from __future__ import division
Alternatively, you could use modulus:
if (a % b) == 0: #do something
couple of months back, I had the same requirement for one of my projects. I searched a bit for it and found out the following solution. This is not the only solution but I found it to one of the simpler one.
Use the webservice at http://www.webservicex.net/uszip.asmx.
Specifically GetInfoByZIP()
method.
You will be able to query by any zipcode (ex: 40220
) and you will have a response back as the following...
<?xml version="1.0" encoding="UTF-8"?>
<NewDataSet>
<Table>
<CITY>Louisville</CITY>
<STATE>KY</STATE>
<ZIP>40220</ZIP>
<AREA_CODE>502</AREA_CODE>
<TIME_ZONE>E</TIME_ZONE>
</Table>
</NewDataSet>
Hope this helps...
Open xCode can be exhausting if you do it everytime, so you need to add this flag :
OR if you have build.json file at the root of your project, you must add this lines:
{
"ios": {
"debug": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
},
"release": {
"buildFlag": [
"-UseModernBuildSystem=0"
]
}
}
}
Hope this will help in the future
The Multipart File Upload worked after following code modification to Upload using RestTemplate
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
map, headers);
ResponseEntity<String> result = template.get().exchange(
contextPath.get() + path, HttpMethod.POST, requestEntity,
String.class);
And adding MultipartFilter to web.xml
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
At the moment, there isn't any open access to the NFC controller. There are currently no NFC APIs in the iOS 8 GM SDK - which would indicate that the NFC capability will be restricted to Apple Pay at launch. This is our understanding.
Clearly, the NXP chip inside the iPhone 6 is likely to be able to do more so this doesn't mean that additional features (pairing, tag scanning/encoding) will not be added for release or in the near future.
To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)
sed -i '/pattern/a \
line1 \
line2' inputfile
Output:
#cat inputfile
pattern
line1 line2
To prepend the lines before:
sed -i '/pattern/i \
line1 \
line2' inputfile
Output:
#cat inputfile
line1 line2
pattern
When you want to destroy a session completely, you need to do more then just
session_destroy();
First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:
<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>
The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.
Edit:
You need to remove the () from your exit code near the top of your script. it should just be
exit;
CHAR is a fixed length field; VARCHAR is a variable length field. If you are storing strings with a wildly variable length such as names, then use a VARCHAR, if the length is always the same, then use a CHAR because it is slightly more size-efficient, and also slightly faster.
I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)
case "$1" in
0|1) xinput set-prop 12 "Device Enabled" $1 ;;
*) echo "This script requires a 1 or 0 as first parameter." ;;
esac
In EclipseLink to get the SQL for a specific Query at runtime you can use the DatabaseQuery API:
Query query = em.createNamedQuery("findMe");
Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = ((EJBQueryImpl)query).getDatabaseQuery();
databaseQuery.prepareCall(session, new DatabaseRecord());
String sqlString = databaseQuery.getSQLString();
This SQL will contain ? for parameters. To get the SQL translated with the arguments you need a DatabaseRecord with the parameter values.
DatabaseRecord recordWithValues= new DatabaseRecord();
recordWithValues.add(new DatabaseField("param1"), "someValue");
String sqlStringWithArgs =
databaseQuery.getTranslatedSQLString(session, recordWithValues);
Source: How to get the SQL for a Query
To fix this, you must review your PHP.INI, and the mail services setup you have in your server.
But my best advice for you is to forget about the mail()
function. It depends on PHP.INI settings, it's configuration is different depending on the platform (Linux or Windows), and it can't handle SMTP authentication, which is a big trouble in current days. Too much headache.
Use "PHP Mailer" instead (https://github.com/PHPMailer/PHPMailer), it's a PHP class available for free, and it can handle almost any SMTP server, internal or external, with or without authentication, it works exactly the same way on Linux and Windows, and it won't depend on PHP.INI settings. It comes with many examples, it's very powerful and easy to use.
i like to use gawk for running multiple commands on a list, for instance
ls -l | gawk '{system("/path/to/cmd.sh "$1)}'
however the escaping of the escapable characters can get a little hairy.
You can check the element existence by
arr.Any(x => x == "One")
ClassLoader.getResourceAsStream
and Class.getResourceAsStream
are definitely the way to go for loading the resource data. However, I don't believe there's any way of "listing" the contents of an element of the classpath.
In some cases this may be simply impossible - for instance, a ClassLoader
could generate data on the fly, based on what resource name it's asked for. If you look at the ClassLoader
API (which is basically what the classpath mechanism works through) you'll see there isn't anything to do what you want.
If you know you've actually got a jar file, you could load that with ZipInputStream
to find out what's available. It will mean you'll have different code for directories and jar files though.
One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.
Are you logging into MySQL as root? You have to explicitly grant privileges to your "regular" MySQL user account while logged in as MySQL root.
First set up a root account for your MySQL database.
In the terminal type:
mysqladmin -u root password 'password'
To log into MySQL, use this:
mysql -u root -p
To set the privileges manually start the server with the skip-grant-tables option, open mysql client and manually update the mysql.user table and/or the mysql.db tables. This can be a tedious task though so if what you need is an account with all privs I would do the following.
Start the server with the skip-grant-tables
option
Start mysql client (without a username/password)
Issue the command
flush privileges;
which forces the grant tables to be loaded.
Create a new account with the GRANT command something like this (but replacing username and password with whatever you want to use.
GRANT ALL on *.* to 'username'@'localhost' identified by 'password';
Restart the server in normal mode (without skip-grant-tables) and log in with your newly created account.
Refer this MySQL docs.
The framework class has been modified to require a flag to inform fromHtml()
how to process line breaks. This was added in Nougat, and only touches on the challenge of incompatibilities of this class across versions of Android.
I've published a compatibility library to standardize and backport the class and include more callbacks for elements and styling:
While it is similar to the framework's Html class, some signature changes were required to allow more callbacks. Here's the sample from the GitHub page:
Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0);
// You may want to provide an ImageGetter, TagHandler and SpanCallback:
//Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0,
// imageGetter, tagHandler, spanCallback);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(fromHtml);
I have done this before, I think you need to remove the ActionResult. Make it a void and remove the return View(MyView). this is the solution
I made the following code so that even beginners can understand. Just copy the code and read comments. Note that message to be send is declared as a global variable which you can change just before sending the message. General changes can be done in Handler function.
multiplayerConnect.java
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class multiplayerConnect extends AppCompatActivity {
public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;
String bluetooth_message="00";
@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
@Override
public void handleMessage(Message msg_type) {
super.handleMessage(msg_type);
switch (msg_type.what){
case MESSAGE_READ:
byte[] readbuf=(byte[])msg_type.obj;
String string_recieved=new String(readbuf);
//do some task based on recieved string
break;
case MESSAGE_WRITE:
if(msg_type.obj!=null){
ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
connectedThread.write(bluetooth_message.getBytes());
}
break;
case CONNECTED:
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
break;
case CONNECTING:
Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
break;
case NO_SOCKET_FOUND:
Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplayer_bluetooth);
initialize_layout();
initialize_bluetooth();
start_accepting_connection();
initialize_clicks();
}
public void start_accepting_connection()
{
//call this on button click as suited by you
AcceptThread acceptThread = new AcceptThread();
acceptThread.start();
Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Object[] objects = set_pairedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) objects[position];
ConnectThread connectThread = new ConnectThread(device);
connectThread.start();
Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
}
});
}
public void initialize_layout()
{
lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
lv_paired_devices.setAdapter(adapter_paired_devices);
}
public void initialize_bluetooth()
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
finish();
}
//Add these permisions before
// <uses-permission android:name="android.permission.BLUETOOTH" />
// <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
// <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else {
set_pairedDevices = bluetoothAdapter.getBondedDevices();
if (set_pairedDevices.size() > 0) {
for (BluetoothDevice device : set_pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
}
}
}
}
public class AcceptThread extends Thread
{
private final BluetoothServerSocket serverSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
} catch (IOException e) { }
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null)
{
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(CONNECTED).sendToTarget();
}
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mHandler.obtainMessage(CONNECTING).sendToTarget();
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// bluetooth_message = "Initial message"
// mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[2]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
multiplayer_bluetooth.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Challenge player"/>
<ListView
android:id="@+id/lv_paired_devices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</ListView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Make sure Device is paired"/>
</LinearLayout>
you seem to have not created an main method, which should probably look something like this (i am not sure)
class RunThis
{
public static void main(String[] args)
{
Calculate answer = new Calculate();
answer.getNumber1();
answer.getNumber2();
answer.setNumber(answer.getNumber1() , answer.getNumber2());
answer.getOper();
answer.setOper(answer.getOper());
answer.getAnswer();
}
}
the point is you should have created a main method under some class and after compiling you should run the .class file containing main method. In this case the main method is under RunThis i.e RunThis.class.
I am new to java this may or may not be the right answer, correct me if i am wrong
I use
android:scaleX="0.70"
android:scaleY="0.70"
to ajust the size of checkbox
then I set margins like this
android:layout_marginLeft="-10dp"
to adjust ths location of the checkbox.
I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.
I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:
<?php
echo phpinfo();
?>
There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from
PHPIniDir 'c:\PHP\'
to
PHPIniDir 'c:\PHP'
Pay the attention that the last slash disturbed everything!
Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!
If you want to learn your data summary (df)
provides the min, 1st quantile, median and mean, 3rd quantile and max of numerical columns and the frequency of the top levels of the factor columns.
.NET is not very helpful, but you can try the following algorithm:
Here is the call:
var encoding = FileHelper.GetEncoding(filePath);
if (encoding == null)
throw new Exception("The file encoding is not supported. Please choose one of the following encodings: UTF8/UTF7/iso-8859-1");
Here is the code:
public class FileHelper
{
/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM) and if not found try parsing into diferent encodings
/// Defaults to UTF8 when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding or null.</returns>
public static Encoding GetEncoding(string filename)
{
var encodingByBOM = GetEncodingByBOM(filename);
if (encodingByBOM != null)
return encodingByBOM;
// BOM not found :(, so try to parse characters into several encodings
var encodingByParsingUTF8 = GetEncodingByParsing(filename, Encoding.UTF8);
if (encodingByParsingUTF8 != null)
return encodingByParsingUTF8;
var encodingByParsingLatin1 = GetEncodingByParsing(filename, Encoding.GetEncoding("iso-8859-1"));
if (encodingByParsingLatin1 != null)
return encodingByParsingLatin1;
var encodingByParsingUTF7 = GetEncodingByParsing(filename, Encoding.UTF7);
if (encodingByParsingUTF7 != null)
return encodingByParsingUTF7;
return null; // no encoding found
}
/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM)
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
private static Encoding GetEncodingByBOM(string filename)
{
// Read the BOM
var byteOrderMark = new byte[4];
using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
file.Read(byteOrderMark, 0, 4);
}
// Analyze the BOM
if (byteOrderMark[0] == 0x2b && byteOrderMark[1] == 0x2f && byteOrderMark[2] == 0x76) return Encoding.UTF7;
if (byteOrderMark[0] == 0xef && byteOrderMark[1] == 0xbb && byteOrderMark[2] == 0xbf) return Encoding.UTF8;
if (byteOrderMark[0] == 0xff && byteOrderMark[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
if (byteOrderMark[0] == 0xfe && byteOrderMark[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
if (byteOrderMark[0] == 0 && byteOrderMark[1] == 0 && byteOrderMark[2] == 0xfe && byteOrderMark[3] == 0xff) return Encoding.UTF32;
return null; // no BOM found
}
private static Encoding GetEncodingByParsing(string filename, Encoding encoding)
{
var encodingVerifier = Encoding.GetEncoding(encoding.BodyName, new EncoderExceptionFallback(), new DecoderExceptionFallback());
try
{
using (var textReader = new StreamReader(filename, encodingVerifier, detectEncodingFromByteOrderMarks: true))
{
while (!textReader.EndOfStream)
{
textReader.ReadLine(); // in order to increment the stream position
}
// all text parsed ok
return textReader.CurrentEncoding;
}
}
catch (Exception ex) { }
return null; //
}
}
You could also set onclick to call your function like this:
foo.onclick = function() { callYourJSFunction(arg1, arg2); };
This way, you can pass arguments too. .....
I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.
Because you're not specifying a precision and a rounding-mode. BigDecimal is complaining that it could use 10, 20, 5000, or infinity decimal places, and it still wouldn't be able to give you an exact representation of the number. So instead of giving you an incorrect BigDecimal, it just whinges at you.
However, if you supply a RoundingMode and a precision, then it will be able to convert (eg. 1.333333333-to-infinity to something like 1.3333 ... but you as the programmer need to tell it what precision you're 'happy with'.
$newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
$newstr = str_replace("'", '', $newstr);
I put them on two separate lines to make the code a little more clear.
Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z
.
One thing not mentioned in other answers is checking the text size. It is often needed to make sure the text fits the image (e.g. shorten the text if oversized) or to determine location to draw the text (e.g. aligned text top center). Pillow/PIL offers two methods to check the text size, one via ImageFont and one via ImageDraw. As shown below, the font doesn't handle multiple lined, while ImageDraw does.
In [28]: im = Image.new(mode='RGB',size=(240,240))
In [29]: font = ImageFont.truetype('arial')
In [30]: draw = ImageDraw.Draw(im)
In [31]: t1 = 'hello world!'
In [32]: t2 = 'hello \nworld!'
In [33]: font.getsize(t1), font.getsize(t2) # the height is the same
Out[33]: ((52, 10), (60, 10))
In [35]: draw.textsize(t1, font), draw.textsize(t2, font) # handles multi-lined text
Out[35]: ((52, 10), (27, 24))
......../info/refs?service=git-upload-pack not found: did you run git update-server-info on the server?
For me the issue was a password issue. I run Keychain and deleted Github passwords. I run the pull command after that and it asked me for username and password. After that it worked ok.
If you use Robert Harder's Base64 utility, then you can do:
InputStream is = new Base64.InputStream(cph);
Or with sun's JRE, you can do:
InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.
There are other Stack Overflow questions about Base64 decoding, such as this one.
See this. Your code would be something like the following:
from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}
You can also use this on existing querysets:
from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}
If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:
arg = args.order_by('-rating')[0]
Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0]
part will raise an IndexError
). If you want to avoid that behavior and instead simply return None
in that case, use .first()
:
arg = args.order_by('-rating').first() # may return None
extension UITableView {
/// Reloads a table view without losing track of what was selected.
func reloadDataSavingSelections() {
let selectedRows = indexPathsForSelectedRows
reloadData()
if let selectedRow = selectedRows {
for indexPath in selectedRow {
selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
}
}
}
tableView.reloadDataSavingSelections()
I want to add that if you are trying to do this for files/directories in a git repository to track if they have changed, then this is the best approach:
git log -1 --format=format:%H --full-diff <file_or_dir_name>
And if it's not a git-directory/repo, then answer by @ire_and_curses is probably the best bet:
tar c <dir_name> | md5sum
However, please note that tar
command will change the output hash if you run it in a different OS and stuff. If you want to be immune to that, this is the best approach, even though it doesn't look very elegant on first sight:
find <dir_name> -type f -print0 | sort -z | xargs -0 md5sum | md5sum | awk '{ print $1 }'
You may be able to use absolute positioning.
The container box should be set to position: relative
.
The top-right text should be set to position: absolute; top: 0; right: 0
.
The bottom-right text should be set to position: absolute; bottom: 0; right: 0
.
You'll need to experiment with padding
to stop the main contents of the box from running underneath the absolute positioned elements, as they exist outside the normal flow of the text contents.
temp = bankAccNos.contains(no) ? 1 : 2;
As an aside, under Windows, ProcessExplorer is fantastic for observing the existing TCP/IP connections for each process.
The best date utility I've used is date-fns for a few reasons:
Date
format.Package manager:
"date-fns": "^1.30.1"
Code:
import { addDays, subDays } from 'date-fns'
let today = new Date()
let yesterday = subDays(today, 1)
let tomorrow = addDays(today, 1)
Simple and awesome.
With the "classic" method, if the cast fails, an InvalidCastException
is thrown. With the as
method, it results in null
, which can be checked for, and avoid an exception being thrown.
Also, you can only use as
with reference types, so if you are typecasting to a value type, you must still use the "classic" method.
Note:
The as
method can only be used for types that can be assigned a null
value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null
value, they are valid to use with the as
operator.
If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited.
http://docs.python.org/library/threading.html#threading.Thread.daemon
Take a look at TOMEE
It has all the features that you need to build a complete Java EE app.
Load Testing: Large amount of users Stress Testing: Too many users, too much data, too little time and too little room
All the previous solutions hard-code 40 pixels specifically into the html or CSS in one fashion or another. What if the navbar contains a different font-size or an image? What if I have a good reason not to mess with the body padding in the first place? I have been searching for a solution to this problem, and here is what I came up with:
$(document).ready(function(){
$('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height()) + 1 )+'px'});
$(window).resize(function(){
$('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height()) + 1 )+'px'});
});
You can move it up or down by adjusting the '1'. It seems to work for me regardless of the size of the content in the navbar, before and after resizing.
I am curious what others think about this: please share your thoughts. (It will be refactored as not to repeat, btw.) Besides using jQuery, are there any other reasons not to approach the problem this way? I've even got it working with a secondary navbar like this:
$('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height())
+ $('.admin-nav').height() + 1 )+'px'});
PS: Above is on Bootstrap 2.3.2 - will it work in 3.x As long as the generic class names remain... in fact, it should work independent of bootstrap, right?
EDIT: Here is a complete jquery function that handles two stacked, responsive fixed navbars of dynamic size. It requires 3 html classes(or could use id's): user-top, admin-top, and contentwrap:
$(document).ready(function(){
$('.admin-top').css({'margin-top':($('.user-top').height()+0)+'px'});
$('.contentwrap') .css({'padding-top': (
$('.user-top').height()
+ $('.admin-top').height()
+ 0 )+'px'
});
$(window).resize(function(){
$('.admin-top').css({'margin-top':($('.user-top').height()+0)+'px'});
$('.contentwrap') .css({'padding-top': (
$('.user-top').height()
+ $('.admin-top').height()
+ 0 )+'px'
});
});
For a SOAP 1.2 Webservice, I normally use
curl --header "content-type: application/soap+xml" --data @filetopost.xml http://domain/path
@Frode F. gave the right answer.
By the Way Invoke-WebRequest
also prints you the 200 OK
and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod
which is lighter.
Also, keep in mind that you need to use | ConvertTo-Json
for the body only, not the header:
$body = @{
"UserSessionId"="12345678"
"OptionalEmail"="[email protected]"
} | ConvertTo-Json
$header = @{
"Accept"="application/json"
"connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
"Content-Type"="application/json"
}
Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
and you can then append a | ConvertTo-HTML
at the end of the request for better readability
jdk 6 comes with wsimport that u can use to create Java-classes from a WSDL. It also creates a Service-class.
http://docs.oracle.com/javase/6/docs/technotes/tools/share/wsimport.html
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
You are facing a double-encoding issue.
¦
and •
are absolutely equivalent to each other. Both refer to the Unicode character 'BULLET' (U+2022) and can exist side-by-side in HTML source code.
However, if that source-code is HTML-encoded again at some point, it will contain ¦
and &#8226;
. The former is rendered unchanged, the latter will come out as "•" on the screen.
This is correct behavior under these circumstances. You need to find the point where the superfluous second HTML-encoding occurs and get rid of it.
Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
Map.keys()
returns a MapIterator
object which can be converted to Array
using Array.from
:
let keys = Array.from( myMap.keys() );
// ["a", "b"]
EDIT: you can also convert iterable object to array using spread syntax
let keys =[ ...myMap.keys() ];
// ["a", "b"]
After some tries, these are the samples I am using in order to connect:
Specifying the username and the password:
sqlcmd -S 211.11.111.111 -U NotSA -P NotTheSaPassword
Specifying the DB as well:
sqlcmd -S 211.11.111.111 -d SomeSpecificDatabase -U NotSA -P NotTheSaPassword
To substantiate @deceze's claim that the default JSON encoding is UTF-8...
From IETF RFC4627:
JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.
Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.
00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8
Unfortunately we cant style reCaptcha v2, but it is possible to make it look better, here is the code:
.g-recaptcha-outer{
text-align: center;
border-radius: 2px;
background: #f9f9f9;
border-style: solid;
border-color: #37474f;
border-width: 1px;
border-bottom-width: 2px;
}
.g-recaptcha-inner{
width: 154px;
height: 82px;
overflow: hidden;
margin: 0 auto;
}
.g-recaptcha{
position:relative;
left: -2px;
top: -1px;
}
<div class="g-recaptcha-outer">
<div class="g-recaptcha-inner">
<div class="g-recaptcha" data-size="compact" data-sitekey="YOUR KEY"></div>
</div>
</div>
select s.sid as "Sid", s.serial# as "Serial#", nvl(s.username, ' ') as "Username", s.machine as "Machine", s.schemaname as "Schema name", s.logon_time as "Login time", s.program as "Program", s.osuser as "Os user", s.status as "Status", nvl(s.process, ' ') as "OS Process id"
from v$session s
where nvl(s.username, 'a') not like 'a' and status like 'ACTIVE'
order by 1,2
This query attempts to filter out all background processes.
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
((frmMain)this.Owner).MyListControl.Items.Add("abc");
Make sure to provide access level you want at Modifiers properties other than Private for MyListControl
at frmMain
The accepted answer by Adam (flex: 1 1 0
) works perfectly for flexbox containers whose width is either fixed, or determined by an ancestor. Situations where you want the children to fit the container.
However, you may have a situation where you want the container to fit the children, with the children equally sized based on the largest child. You can make a flexbox container fit its children by either:
position: absolute
and not setting width
or right
, ordisplay: inline-block
For such flexbox containers, the accepted answer does NOT work, the children are not sized equally. I presume that this is a limitation of flexbox, since it behaves the same in Chrome, Firefox and Safari.
The solution is to use a grid instead of a flexbox.
Demo: https://codepen.io/brettdonald/pen/oRpORG
<p>Normal scenario — flexbox where the children adjust to fit the container — and the children are made equal size by setting {flex: 1 1 0}</p>
<div id="div0">
<div>
Flexbox
</div>
<div>
Width determined by viewport
</div>
<div>
All child elements are equal size with {flex: 1 1 0}
</div>
</div>
<p>Now we want to have the container fit the children, but still have the children all equally sized, based on the largest child. We can see that {flex: 1 1 0} has no effect.</p>
<div class="wrap-inline-block">
<div id="div1">
<div>
Flexbox
</div>
<div>
Inside inline-block
</div>
<div>
We want all children to be the size of this text
</div>
</div>
</div>
<div id="div2">
<div>
Flexbox
</div>
<div>
Absolutely positioned
</div>
<div>
We want all children to be the size of this text
</div>
</div>
<br><br><br><br><br><br>
<p>So let's try a grid instead. Aha! That's what we want!</p>
<div class="wrap-inline-block">
<div id="div3">
<div>
Grid
</div>
<div>
Inside inline-block
</div>
<div>
We want all children to be the size of this text
</div>
</div>
</div>
<div id="div4">
<div>
Grid
</div>
<div>
Absolutely positioned
</div>
<div>
We want all children to be the size of this text
</div>
</div>
body {
margin: 1em;
}
.wrap-inline-block {
display: inline-block;
}
#div0, #div1, #div2, #div3, #div4 {
border: 1px solid #888;
padding: 0.5em;
text-align: center;
white-space: nowrap;
}
#div2, #div4 {
position: absolute;
left: 1em;
}
#div0>*, #div1>*, #div2>*, #div3>*, #div4>* {
margin: 0.5em;
color: white;
background-color: navy;
padding: 0.5em;
}
#div0, #div1, #div2 {
display: flex;
}
#div0>*, #div1>*, #div2>* {
flex: 1 1 0;
}
#div0 {
margin-bottom: 1em;
}
#div2 {
top: 15.5em;
}
#div3, #div4 {
display: grid;
grid-template-columns: repeat(3,1fr);
}
#div4 {
top: 28.5em;
}
The short answer is no. The long answer is yes. :-)
Markdown was designed to allow people to write simple, readable text that could be easily converted to a simple HTML markup. It doesn't really do document layout. For example, there's no real way to align an image to the right or left. As to your question, there's no markdown command to include a single link from one file to another in any version of markdown (so far as I know).
The closest you could come to this functionality is Pandoc. Pandoc allows you to merge files as a part of the transformation, which allows you to easily render multiple files into a single output. For example, if you were creating a book, then you could have chapters like this:
01_preface.md
02_introduction.md
03_why_markdown_is_useful.md
04_limitations_of_markdown.md
05_conclusions.md
You can merge them by doing executing this command within the same directory:
pandoc *.md > markdown_book.html
Since pandoc will merge all the files prior to doing the translation, you can include your links in the last file like this:
01_preface.md
02_introduction.md
03_why_markdown_is_useful.md
04_limitations_of_markdown.md
05_conclusions.md
06_links.md
So part of your 01_preface.md
could look like this:
I always wanted to write a book with [markdown][mkdnlink].
And part of your 02_introduction.md
could look like this:
Let's start digging into [the best text-based syntax][mkdnlink] available.
As long as your last file includes the line:
[mkdnlink]: http://daringfireball.net/projects/markdown
...the same command used before will perform the merge and conversion while including that link throughout. Just make sure you leave a blank line or two at the beginning of that file. The pandoc documentation says that it adds a blank line between files that are merged this way, but this didn't work for me without the blank line.
We'll check a Collection object is empty, null or not. these all methods which are given below, are present in org.apache.commons.collections4.CollectionUtils package.
Check on List or set type of collection Objects.
CollectionUtils.isEmpty(listObject);
CollectionUtils.isNotEmpty(listObject);
Check on Map type of Objects.
MapUtils.isEmpty(mapObject);
MapUtils.isNotEmpty(mapObject);
The return type of all methods is boolean.
none of the answers worked for me in 2017 with capybara 2.7. I got "ArgumentError: wrong number of arguments (given 2, expected 0)"
But this did:
find('#organizationSelect').all(:css, 'option').find { |o| o.value == 'option_name_here' }.select_option
I'm using gson 2.2.3
public class Main {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
JsonReader jsonReader = new JsonReader(new FileReader("jsonFile.json"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("descriptor")) {
readApp(jsonReader);
}
}
jsonReader.endObject();
jsonReader.close();
}
public static void readApp(JsonReader jsonReader) throws IOException{
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
System.out.println(name);
if (name.contains("app")){
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
if (n.equals("name")){
System.out.println(jsonReader.nextString());
}
if (n.equals("age")){
System.out.println(jsonReader.nextInt());
}
if (n.equals("messages")){
jsonReader.beginArray();
while (jsonReader.hasNext()) {
System.out.println(jsonReader.nextString());
}
jsonReader.endArray();
}
}
jsonReader.endObject();
}
}
jsonReader.endObject();
}
}
Use GregorianCalendar
. Set the date of the object, and then use getActualMaximum(Calendar.DAY_IN_MONTH)
.
http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29 (but it was the same in Java 1.4)
If you are using Docker, you may try an image that has Ubuntu with System D already active with this command:
docker run -d --name redis --privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro jrei/systemd-ubuntu:18.04
Then you just need to run:
docker exec -it redis /bin/bash
and there you can just install Redis, start it, restart it or whatever you need.
As Mongo shell support regex, that's completely possible.
db.users.findOne({"username" : /.*son.*/});
If we want the query to be case-insensitive, we can use "i" option, like shown below:
db.users.findOne({"username" : /.*son.*/i});
See: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
In my case I had to put textbox into a stack panel in order to stretch textbox on left side. Thanks to previous post. Just for an example I did set a background color to see what’s happens when window size is changing.
<StackPanel Name="JustContainer" VerticalAlignment="Center" HorizontalAlignment="Stretch" Background="BlueViolet" >
<TextBox
Name="Input" Text="Hello World"
MaxWidth="300"
HorizontalAlignment="Right"
Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}}">
</TextBox>
</StackPanel>
In bubble sort in ith iteration you have n-i-1 inner iterations (n^2)/2 total, but in insertion sort you have maximum i iterations on i'th step, but i/2 on average, as you can stop inner loop earlier, after you found correct position for the current element. So you have (sum from 0 to n) / 2 which is (n^2) / 4 total;
That's why insertion sort is faster than bubble sort.
Why not take the approach that GMail uses and show the number of messages in the page title?
Sometimes users don't want to be distracted when a new message arrives.
The simplest answer:
1111 + 1 = (1)0000. So 1111 must be -1. Then -1 + 1 = 0.
It's perfect to understand these all for me.
This works like a charm, fast and accurate:
function replace_string_in_file($filename, $string_to_replace, $replace_with){
$content=file_get_contents($filename);
$content_chunks=explode($string_to_replace, $content);
$content=implode($replace_with, $content_chunks);
file_put_contents($filename, $content);
}
Usage:
$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);
// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool
I just came up with this very simple method of clearing an entire sheet.
Sub ClearThisSheet()
ActiveSheet.UsedRange.ClearContents
End Sub
You can also set headers for the entire session:
TOKEN = 'abcd0123'
HEADERS = {'Authorization': 'token {}'.format(TOKEN)}
with requests.Session() as s:
s.headers.update(HEADERS)
resp = s.get('http://example.com/')
Unfortunately, none of the solution listed here helped me to resolve this issue. I fixed this issue by using http://127.0.0.1 (ip address) instead of http://localhost. A quick little hack to work with angular development with chrome browser.
I had to split a list for feature extraction in two parts lt,lc:
ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)
featsets = [(act_features((lt)),lc)
for lc, lt in ltexts]
def act_features(atext):
features = {}
for word in nltk.word_tokenize(atext):
features['cont({})'.format(word.lower())]=True
return features
Thanks to duncan answer, I end up with this:
marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())
From Oracle (but works in most SQL DBs):
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
HAVING COUNT(*) >= 3
P.S. it's faster one, because you have no Select withing Select methods here
If it's always going to be an even LHS/RHS split, you can also use the partition
method that's built into strings. It returns a 3-tuple as (LHS, separator, RHS)
if the separator is found, and (original_string, '', '')
if the separator wasn't present:
>>> "2.7.0_bf4fda703454".partition('_')
('2.7.0', '_', 'bf4fda703454')
>>> "shazam".partition("_")
('shazam', '', '')
Since Java 7 this is very easy and intuitive to do.
List<String> fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8));
for (int i = 0; i < fileContent.size(); i++) {
if (fileContent.get(i).equals("old line")) {
fileContent.set(i, "new line");
break;
}
}
Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8);
Basically you read the whole file to a List
, edit the list and finally write the list back to file.
FILE_PATH
represents the Path
of the file.
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
You should use System property instead of environment variable for this case. Edit your tomcat scripts for JAVA_OPTS and add property like:
-DAPP_MASTER_PASSWORD=foo
and in your code, write
System.getProperty("APP_MASTER_PASSWORD");
You can do this in Eclipse as well, instead of JAVA_OPTS, copy the line in VM parameters inside run configurations.
Just do:
echo substr($string, 0, -3);
You don't need to use a strlen
call, since, as noted in the substr docs:
If length is given and is negative, then that many characters will be omitted from the end of string
or you can simply use
def question_params
params.require(:question).permit(team_ids: [])
end
One more way for square matrix. No numpy, nor itertools, use (effective) in-place elements exchange.
def transpose(m):
for i in range(1, len(m)):
for j in range(i):
m[i][j], m[j][i] = m[j][i], m[i][j]
Using empty
is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE
.
Here is the code with line 156, it has try and catch above it
/// <summary>
/// Execute a SQL Query statement, using the default SQL connection for the application
/// </summary>
/// <param name="query">SQL query to execute</param>
/// <returns>DataTable of results</returns>
public static DataTable Query(string query)
{
DataTable results = new DataTable();
string configConnectionString = "ApplicationServices";
System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
System.Configuration.ConnectionStringSettings connString;
if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];
if (connString != null)
{
try
{
using (SqlConnection conn = new SqlConnection(connString.ToString()))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
dataAdapter.Fill(results);
return results;
}
catch (Exception ex)
{
throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
}
}
else
{
throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
}
}
else
{
throw new SqlException(string.Format("No connection strings found in Web.config file."));
}
}
Inspired by the great lead given by Doug Glancy's answer, I came up with a way to do the same thing without the need of an array-formula. Do not ask me why, but I am keen to avoid the use of array formulae if at all possible (not for any particular reason, it's just my style).
Here it is:
=SUMPRODUCT(MAX(($A:$A<>"")*(ROW(A:A))))
For finding the last non-empty row using Column A as the reference column
=SUMPRODUCT(MAX(($1:$1<>"")*(COLUMN(1:1))))
For finding the last non-empty column using row 1 as the reference row
This can be further utilized in conjunction with the index function to efficiently define dynamic named ranges, but this is something for another post as this is not related to the immediate question addressed herein.
I've tested the above methods with Excel 2010, both "natively" and in "Compatibility Mode" (for older versions of Excel) and they work. Again, with these you do not need to do any of the Ctrl+Shift+Enter. By leveraging the way sumproduct works in Excel we can get our arms around the need to carry array-operations but we do it without an array-formula. I hope someone out there may appreciate the beauty, simplicity and elegance of these proposed sumproduct solutions as much as I do. I do not attest to the memory-efficiency of the above solutions though. Just that they are simple, look beautiful, help the intended purpose and are flexible enough to extend their use to other purposes :)
Hope this helps!
All the best!
I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
content
</body>
<script type="text/javascript">
$("body").load(url);
</script>
</html>
The document says:
Copy the file into the
app/
folder of your Android Studio project, or into theapp/src/{build_type}
folder if you are using multiple build types.
First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
Then you use it like this. Caution! Makes the code extremely readable.
var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
// Do stuff here
}
Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.
SELECT DISTINCT 1 AS Expr1
FROM [User]
WHERE (UserID = 20070022)
It's so easy, man. Just press on the power button until you see the "Phone Options" screen and turn on mobile data. After that you can sign into your account or remotely unlock your device.
String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
LATEST UPDATE:
Use the official version from jCenter instead.
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
The dependencies below points to deprecated volley that is no longer maintained.
ORIGINAL ANSWER
You can use this in dependency section of your build.gradle file to use volley
dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}
UPDATED:
Its not official but a mirror copy of official Volley. It is regularly synced and updated with official Volley Repository so you can go ahead to use it without any worry.
I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.
If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.
For enable, the generic looks to be the following:
update-rc.d <service> enable
Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers
NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:
[anArray removeObjectAtIndex: index];
[anArray removeObject: item];
[anArray removeLastObject];
__del__
is a finalizer. It is called when an object is garbage collected which happens at some point after all references to the object have been deleted.
In a simple case this could be right after you say del x
or, if x
is a local variable, after the function ends. In particular, unless there are circular references, CPython (the standard Python implementation) will garbage collect immediately.
However, this is an implementation detail of CPython. The only required property of Python garbage collection is that it happens after all references have been deleted, so this might not necessary happen right after and might not happen at all.
Even more, variables can live for a long time for many reasons, e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of cycle of references — CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.
Since you have no guarantee it's executed, one should never put the code that you need to be run into __del__()
— instead, this code belongs to finally
clause of the try
block or to a context manager in a with
statement. However, there are valid use cases for __del__
: e.g. if an object X
references Y
and also keeps a copy of Y
reference in a global cache
(cache['X -> Y'] = Y
) then it would be polite for X.__del__
to also delete the cache entry.
If you know that the destructor provides (in violation of the above guideline) a required cleanup, you might want to call it directly, since there is nothing special about it as a method: x.__del__()
. Obviously, you should you do so only if you know that it doesn't mind to be called twice. Or, as a last resort, you can redefine this method using
type(x).__del__ = my_safe_cleanup_method
After reading cURL documentation on the options you used, it looks like the private key of certificate is not in the same file. If it is in different file, you need to mention it using --key file and supply passphrase.
So, please make sure that either cert.pem has private key (along with the certificate) or supply it using --key option.
Also, this documentation mentions that Note that this option assumes a "certificate" file that is the private key and the private certificate concatenated!
How they are concatenated? It is quite easy. Put them one after another in the same file.
You can get more help on this here.
I believe this might help you.
Use Noda Time:
var ld1 = new LocalDate(2012, 1, 1);
var ld2 = new LocalDate(2013, 12, 25);
var period = Period.Between(ld1, ld2);
Debug.WriteLine(period); // "P1Y11M24D" (ISO8601 format)
Debug.WriteLine(period.Years); // 1
Debug.WriteLine(period.Months); // 11
Debug.WriteLine(period.Days); // 24
There are three (3) ways to clone objects in JavaScript. As objects in JavaScript are reference values, you can't simply just copy using the =.
The ways are:
const food = { food: 'apple', drink: 'milk' }
// 1. Using the "Spread"
// ------------------
{ ...food }
// 2. Using "Object.assign"
// ------------------
Object.assign({}, food)
// 3. "JSON"
// ------------------
JSON.parse(JSON.stringify(food))
// RESULT:
// { food: 'apple', drink: 'milk' }
Hope that this can be used as a reference summary.
If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add
Name: X-UA-Compatible
Value: IE=edge
This will override your browser and your code.
Use Application.GetSaveAsFilename()
in the same way that you used Application.GetOpenFilename()
This below code snippet for scala users :
Option 1 :
Below snippet you can add at the file level
import org.apache.log4j.{Level, Logger}
Logger.getLogger("org").setLevel(Level.WARN)
Option 2 :
Note : which will be applicable for all the application which is using spark session.
import org.apache.spark.sql.SparkSession
private[this] implicit val spark = SparkSession.builder().master("local[*]").getOrCreate()
spark.sparkContext.setLogLevel("WARN")
Option 3 :
Note : This configuration should be added to your log4j.properties.. (could be like /etc/spark/conf/log4j.properties (where the spark installation is there) or your project folder level log4j.properties) since you are changing at module level. This will be applicable for all the application.
log4j.rootCategory=ERROR, console
IMHO, Option 1 is wise way since it can be switched off at file level.
For Angular 9+ You can add headers and params directly without the key-value notion:
const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params});
This probably isn't the best approach in Python, but as a Haskeller this lambda/map approach made perfect sense to me and is very short:
anydigit = lambda x: any(map(str.isdigit, x))
Doesn't need to be named of course. Named it could be used like anydigit("abc123")
, which feels like what I was looking for!
According to my knowledge we should use ng-change with the select option and in textbox case we should use ng-blur.
You can add them like this
Route::get('company/{name}', 'PublicareaController@companydetails');
Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.
In 2.3.2 the collapse
class wasn't getting replaced by the in
class. The in
class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse
class correctly is removed, and the <tr>
collapses.
Use @Chad's solution for the html, and try using these links for referencing Bootstrap:
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
I had the same issue because I had 2 .git
folders in the working directory.
Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git
folders, and, if so, deleting one of them.
That allowed me to upload the project successfully.
There is a HUGE difference between VARCHAR and TEXT. While VARCHAR fields can be indexed, TEXT fields cannot. VARCHAR type fields are stored inline while TEXT are stored offline, only pointers to TEXT data is actually stored in the records.
If you have to index your field for faster search, update or delete than go for VARCHAR, no matter how big. A VARCHAR(10000000) will never be the same as a TEXT field bacause these two data types are different in nature.
than go for TEXT.
Here's a version where you don't need a human to read a value and type it out themselves.
CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
Another option would be to employ the reusable Function
shared at the end of this answer.
Just adding to the other two answers, for those of us who need to have these Sequence
s created by a non-interactive script, while patching a live-ish DB for instance.
That is, when you don't wanna SELECT
the value manually and type it yourself into a subsequent CREATE
statement.
In short, you can not do:
CREATE SEQUENCE foo_a_seq
START WITH ( SELECT max(a) + 1 FROM foo );
... since the START [WITH]
clause in CREATE SEQUENCE
expects a value, not a subquery.
Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than
INSERT
,SELECT
,UPDATE
,DELETE
) statements in pgSQL AFAIK.
However, setval()
does! Thus, the following is absolutely fine:
SELECT setval('foo_a_seq', max(a)) FROM foo;
If there's no data and you don't (want to) know about it, use coalesce()
to set the default value:
SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
-- ^ ^ ^
-- defaults to: 0
However, having the current sequence value set to 0
is clumsy, if not illegal.
Using the three-parameter form of setval
would be more appropriate:
-- vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
-- ^ ^
-- is_called
Setting the optional third parameter of setval
to false
will prevent the next nextval
from advancing the sequence before returning a value, and thus:
the next
nextval
will return exactly the specified value, and sequence advancement commences with the followingnextval
.
— from this entry in the documentation
On an unrelated note, you also can specify the column owning the Sequence
directly with CREATE
, you don't have to alter it later:
CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
In summary:
CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
Function
Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function
.
CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
start_with INTEGER;
sequence_name TEXT;
BEGIN
sequence_name := table_name || '_' || column_name || '_seq';
EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
INTO start_with;
EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
' START WITH ' || start_with ||
' OWNED BY ' || table_name || '.' || column_name;
EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
' SET DEFAULT nextVal(''' || sequence_name || ''')';
RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;
Use it like so:
INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint
SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected
As far as the Android API got updated, the suggested method to show a full screen dialog is the following:
FragmentTransaction transaction = this.mFragmentManager.beginTransaction();
// For a little polish, specify a transition animation
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
// To make it fullscreen, use the 'content' root view as the container
// for the fragment, which is always the root view for the activity
transaction.add(android.R.id.content, this.mFragmentToShow).commit();
otherwise, if you don't want it to be shown fullscreen you can do this way:
this.mFragmentToShow.show(this.mFragmentManager, LOGTAG);
Hope it helps.
EDIT
Be aware that the solution I gave works but has got a weakness that sometimes could be troublesome. Adding the DialogFragment to the android.R.id.content
container won't allow you to handle the DialogFragment#setCancelable()
feature correctly and could lead to unexpected behaviors when adding the DialogFragment itself to the back stack as well.
So I'd suggested you to simple change the style of your DialogFragment in the onCreate method as follow:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Translucent_NoTitleBar);
}
Hope it helps.
HashSet<String>
(or) any Set
implementation may does the job for you. Set
don't allow duplicates.
Here is javadoc for HashSet.
Using wget
wget -O /tmp/myfile 'http://www.google.com/logo.jpg'
or curl:
curl -o /tmp/myfile 'http://www.google.com/logo.jpg'
Like this:
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.width();
var imgLength = images.length;
$(this).find(".scrolling").width( width * imgLength * 1.2 );
});
The $(this)
refers to the current .target
which will be looped through. Within this .target
I'm looking for the .scrolling img
and get the width. And then keep on going...
Images with different widths
If you want to calculate the width of all images (when they have different widths) you can do it like this:
// Get the total width of a collection.
$.fn.getTotalWidth = function(){
var width = 0;
this.each(function(){
width += $(this).width();
});
return width;
}
$(".target").each(function(){
var images = $(this).find(".scrolling img");
var width = images.getTotalWidth();
$(this).find(".scrolling").width( width * 1.2 );
});
To make it more generic of keeping both columns in df1
and df2
:
import pyspark.sql.functions as F
# Keep all columns in either df1 or df2
def outter_union(df1, df2):
# Add missing columns to df1
left_df = df1
for column in set(df2.columns) - set(df1.columns):
left_df = left_df.withColumn(column, F.lit(None))
# Add missing columns to df2
right_df = df2
for column in set(df1.columns) - set(df2.columns):
right_df = right_df.withColumn(column, F.lit(None))
# Make sure columns are ordered the same
return left_df.union(right_df.select(left_df.columns))
Basic Swift 3+ Solution
guard let url = URL(string: "http://www.stackoverflow.com") else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
}
task.resume()
You can use this tricks mentioned on this site http://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php.
Its very useful and easy to understand. All you need to create
<div class="videoWrapper">
<!-- Copy & Pasted from YouTube -->
<iframe width="560" height="349" src="http://www.youtube.com/embed/n_dZNLr2cME?rel=0&hd=1" frameborder="0" allowfullscreen></iframe>
</div>
.videoWrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
}
.videoWrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Here is your edited js fiddle for demonstration.
You must have an application associated with the file type. You must be in the folder that houses the file.
In gitbash: start file.extension
In Ubuntu I did not found httpd.conf
, It may not exit longer now.
Edit in apache2.conf
file working for me.
cd /etc/apache2
sudo gedit apache2.conf
Here in apache2.conf change
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
to
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
To make sure that an element is present you can do the following:
driver.findElements(By.id("id"));
That will return an array, if that array size is > 0 then the element/s is present.
Also, you need to provide more information, such as language and what have you tried before asking,
Good luck
http://www.useragentstring.com/
Visit that page, it'll give you a good explanation of each element of your user agent.
Mozilla:
MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore
Just follow these steps to transfer the apk onto the real device(with debugger key) and which is just for testing purpose. (Note: For proper distribution to the market you may need to sign your app with your keys and follow all the steps.)
Good luck !
JS
Create an external JavaScript file (i.e. mymap.js) with the following code
google.maps.visualRefresh = true; //Optional
var respMap;
function mymapini() {
var mapPos = new google.maps.LatLng(-0.172175,1.5); //Set the coordinates
var mapOpts = {
zoom: 10, //You can change this according your needs
disableDefaultUI: true, //Disabling UI Controls (Optional)
center: mapPos, //Center the map according coordinates
mapTypeId: google.maps.MapTypeId.ROADMAP
};
respMap = new google.maps.Map(document.getElementById('mymap'),
mapOpts);
var mapMarker = new google.maps.Marker({
position: mapPos,
map: respMap,
title: 'You can put any title'
});
//This centers automatically to the marker even if you resize your window
google.maps.event.addListener(respMap, 'idle', function() {
window.setTimeout(function() {
respMap.panTo(mapPos.getPosition());
}, 250);
});
}
google.maps.event.addDomListener(window, 'load', mymapini);
$("#modalOpen").click(function(){ //Use it like <a href="#" id="modalOpen"...
$("#myModal").show(); //ID from the Modal <div id="myModal">...
google.maps.event.trigger(respMap, 'resize');
});
HTML
Add the following code before the tag:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="js/mymap.js"></script>
Add this to the modal code:
<div id="mymap"></div>
CSS
Add this to your stylesheet:
#mymap { margin: 0; padding: 0; width:100%; height: 400px;}
To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.
Sub test_date_or_String()
Set c = ActiveCell
c.NumberFormat = "@"
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
c.NumberFormat = "m/d/yyyy"
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date
End Sub
This worked for me... try it
let image : UIImage = UIImage(named: "LogoName")
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
imageView.contentMode = .scaleAspectFit
imageView.image = image
navigationItem.titleView = imageView
Nothing can beat -
SELECT TOP 1 1 FROM products WHERE id = 'some value';
You don't need to count to know if there is a data in table. And don't use alias when not necessary.
If you are getting 500 - Internal server error that means you don't have permission to set these values by .htaccess. You have to contact your web server providers and ask to set AllowOverride Options
for your host or to put these lines in their virtual host configuration file.
For completeness; working with the data loaded into memory;
dim hf As integer: hf = freefile
dim lines() as string, i as long
open "c:\bla\bla.bla" for input as #hf
lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf
for i = 0 to ubound(lines)
debug.? "Line"; i; "="; lines(i)
next
I just found out, that by using asset_url
helper you solve that problem.
asset_url("backgrounds/pattern.png", image)
We can directly subtract dates to get difference in Days.
SET SERVEROUTPUT ON ;
DECLARE
V_VAR NUMBER;
BEGIN
V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
DBMS_OUTPUT.PUT_LINE(V_VAR);
END;
Here is a script which generates grant queries for a particular table. It omits owner's privileges.
SELECT
format (
'GRANT %s ON TABLE %I.%I TO %I%s;',
string_agg(tg.privilege_type, ', '),
tg.table_schema,
tg.table_name,
tg.grantee,
CASE
WHEN tg.is_grantable = 'YES'
THEN ' WITH GRANT OPTION'
ELSE ''
END
)
FROM information_schema.role_table_grants tg
JOIN pg_tables t ON t.schemaname = tg.table_schema AND t.tablename = tg.table_name
WHERE
tg.table_schema = 'myschema' AND
tg.table_name='mytable' AND
t.tableowner <> tg.grantee
GROUP BY tg.table_schema, tg.table_name, tg.grantee, tg.is_grantable;
You can simply use DataColumnCollection.IndexOf
So that you can get the index of the required column by name then use it with your row:
row[dt.Columns.IndexOf("ColumnName")] = columnValue;
Windows + Apache 2.4, for example:
uncomment ssl_module in your httpd.conf
file.
LoadModule ssl_module modules/mod_ssl.so
listen 443 port just like 80 port in your httpd.conf
file.
Listen 80
Listen 443
uncomment Include Virtual hosts in your httpd.conf
file.
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
add VirtualHost in your conf/extra/httpd-vhosts.conf
<VirtualHost _default_:443>
DocumentRoot "D:/www" #your site directory path
ServerName localhost
#ServerAlias localhost.com localhost2.com
SSLEngine on
SSLCertificateFile "${SRVROOT}/conf/ssl/server.crt"
SSLCertificateKeyFile "${SRVROOT}/conf/ssl/server.key"
<Directory "D:/www">
Options -Indexes +FollowSymLinks +ExecCGI
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
only the port number 443
and SSL......
lines are different from normal http config.
save you config file and restart apache service. then you can visit https://localhost/
The web browser will warn you that it's unsafe at the first time, just choose go on.
From TinyMCE, jQuery and Ajax forms:
TinyMCE Form Submission
When a textarea is replaced by TinyMCE, it's actually hidden and TinyMCE editor (an iframe) is displayed instead.
However, it's this textarea's contents which is sent when the form is submitted. Consequently its contents has to be updated before the form submission.
For a standard form submission , it's handled by TinyMCE . For an Ajax form submission, you have to do it manually, by calling (before the form is submitted):
tinyMCE.triggerSave();
$('form').bind('form-pre-serialize', function(e) {
tinyMCE.triggerSave();
});
You can use PHP to add a stylesheet for IE 10
Like:
if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10')) {
<link rel="stylesheet" type="text/css" href="../ie10.css" />
}
You can use JSON.stringify
like:
JSON.stringify(new_tweets);
Bootstrap 4 alpha, for margin-top: shorthand CSS class names mt-1, mt-2 ( mt-lg-5, mt-sm-2) same for the bottom, right, left, and you have also auto class ml-auto
<div class="mt-lg-1" ...>
Units are from 1
to 5
: in the variables.scss
which means if you set mt-1 it gives .25rem of margin top.
$spacers: (
0: (
x: 0,
y: 0
),
1: (
x: ($spacer-x * .25),
y: ($spacer-y * .25)
),
2: (
x: ($spacer-x * .5),
y: ($spacer-y * .5)
),
3: (
x: $spacer-x,
y: $spacer-y
),
4: (
x: ($spacer-x * 1.5),
y: ($spacer-y * 1.5)
),
5: (
x: ($spacer-x * 3),
y: ($spacer-y * 3)
)
) !default;
read-more here
https://v4-alpha.getbootstrap.com/utilities/spacing/#horizontal-centering
The version of JBoss should also be visible in the boot log file. Standard install would have that (for linux) in
/var/log/jboss/boot.log
$ head boot.log
08:30:07,477 INFO [Server] Starting JBoss (MX MicroKernel)...
08:30:07,478 INFO [Server] Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)
08:30:07,478 DEBUG [Server] Using config: org.jboss.system.server.ServerConfigImpl@4277158a
08:30:07,478 DEBUG [Server] Server type: class org.jboss.system.server.ServerImpl
08:30:07,478 DEBUG [Server] Server loaded through: org.jboss.system.server.NoAnnotationURLClassLoader
08:30:07,478 DEBUG [Server] Boot URLs:
so required info int the above case is
Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)
Use fmod()
from <cmath>
. If you do not want to include the C header file:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);
I'm not a big fan of using exceptions for control flow. This is an alternative approach that works in boto3:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
key = 'dootdoot.jpg'
objs = list(bucket.objects.filter(Prefix=key))
if any([w.key == path_s3 for w in objs]):
print("Exists!")
else:
print("Doesn't exist")
Building upon image72's excellent answer, you could actually have advanced CSS selectors like this:
<!--[if lt IE 7]><body class="IE IE7down IE8down IE9down IE10down"><![endif]-->
<!--[if IE 7]><body class="IE IE7 IE7down IE8down IE9down IE10down IE7up"><![endif]-->
<!--[if IE 8]><body class="IE IE8 IE8down IE9down IE10down IE7up IE8up"><![endif]-->
<!--[if IE 9]><body class="IE IE9 IE9down IE10down IE7up IE8up IE9up"><![endif]-->
<!--[if gte IE 10]><body class="IE IE10 IE10down IE7up IE8up IE9up IE10up"><![endif]-->
<!--[if !IE]>--><body class="notIE"><!--<![endif]-->
so that in your css you can do this:
.notIE .foo { color: blue; } /* Target all browsers except IE */
.IE9up .foo { color: green; } /* Taget IE equal or greater than 9 */
.IE8 .foo { color: orange; } /* Taget IE 8 only */
.IE7down .foo { color: red; } /* Target IE equal or less than 7 */
.IE8 .foo, .IE9 .foo {
font-size: 1.2em; /* Target IE8 & IE9 only */
}
.bar { background-color: gray; } /* Applies to all browsers, as usual */
/* Maybe show a message only to IE users? */
.notIE #betterBrowser { display: none; } /* Any browser except IE */
.IE #betterBrowser { display: block; } /* All versions of IE */
This is great because:
Use the CLIM function (equivalent to CAXIS function in MATLAB):
plt.pcolor(X, Y, v, cmap=cm)
plt.clim(-4,4) # identical to caxis([-4,4]) in MATLAB
plt.show()
alternatively you can set remote to http by using this command in the existing repo, and use this command git remote set-url origin https://gitlab.com/[username]/[repo-name].git
i think this add new property in desired type without having to set a primitive value, like when property defined in class definition
var x = new ExpandoObject();
x.NewProp = default(string)
Java 8
If you are using Java 8 in your project and comparing java.sql.Timestamp
, you could use the LocalDate
class:
sameDate = date1.toLocalDateTime().toLocalDate().equals(date2.toLocalDateTime().toLocalDate());
If you are using java.util.Date
, have a look at Istvan answer which is less ambiguous.
I would use the well-tested (millions of downloads per week) pify and async modules. If you are unfamiliar with the async module, I highly recommend you check out its docs. I've seen multiple devs waste time recreating its methods, or worse, making difficult-to-maintain async code when higher-order async methods would simplify code.
const async = require('async')_x000D_
const fs = require('fs-promise')_x000D_
const pify = require('pify')_x000D_
_x000D_
async function getFilePaths() {_x000D_
return Promise.resolve([_x000D_
'./package.json',_x000D_
'./package-lock.json',_x000D_
]);_x000D_
}_x000D_
_x000D_
async function printFiles () {_x000D_
const files = await getFilePaths()_x000D_
_x000D_
await pify(async.eachSeries)(files, async (file) => { // <-- run in series_x000D_
// await pify(async.each)(files, async (file) => { // <-- run in parallel_x000D_
const contents = await fs.readFile(file, 'utf8')_x000D_
console.log(contents)_x000D_
})_x000D_
console.log('HAMBONE')_x000D_
}_x000D_
_x000D_
printFiles().then(() => {_x000D_
console.log('HAMBUNNY')_x000D_
})_x000D_
// ORDER OF LOGS:_x000D_
// package.json contents_x000D_
// package-lock.json contents_x000D_
// HAMBONE_x000D_
// HAMBUNNY_x000D_
```
_x000D_
You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.
Sub deleteCol()
On Error Resume Next
Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer
Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
End If
Next i
End Sub
With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.
EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare)
change the "1" in Cells(1, i)
to whatever row your headers are in.
EDIT 2: Changed the For
section of the code to account for completely empty columns.
If the code you're testing is relatively simple then you can just create a regular Java project in the Package Explorer and copy the code across, run it and fix it there, then copy it back into your Android project.
The fact that System.out is redirected is pretty annoying for quickly testing simple methods, but that's the easiest solution I've found, rather than having to run the device emulator just to see if a regular expression works.
Resolved this issue by using http(s)
when accessing the endpoint. The route I was accessing was not available over http
. So I would say verify the protocols for which the route is available.
Fixed it with -no-pie
option in linker stage:
g++-8 -L"/home/pedro/workspace/project/lib" -no-pie ...
You can't do this without the WEB SERVER!!! Chrome sends XMLHttpRequest to the system that looks something like this
GET /myFile.txt HTTP/1.1
And the operating system is not listening on port 80 to receive this! And even if it is, it must implement HTTP protocol to communicate with the browser...
To get this working, you must have WEB SERVER installed on your system, that will listen on port 80 and make your files available through a HTTP connection, thus making your code runnable.
I don't know about yum, but rpm -ql
will list the files in a particular .rpm file. If you can find the package file on your system you should be good to go.
By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.
wget --user=username --ask-password https://xyz.com/changelog-6.40.txt
You cannot just put in a function to pause Javascript unfortunately.
You have to use setTimeout()
Example:
function startTimer () {
timer.start();
setTimeout(stopTimer,5000);
}
function stopTimer () {
timer.stop();
}
EDIT:
For your user generated countdown, it is just as simple.
HTML:
<input type="number" id="delay" min="1" max="5">
JS:
var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;
function startTimer () {
timer.start();
setTimeout(stopTimer,delayInMilliseconds);
}
function stopTimer () {
timer.stop;
}
Now you simply need to add a trigger for startTimer()
, such as onchange
.
The capitalization is wrong, and you have an extra argument.
Do this instead:
$('img#thumb').removeAttr('id');
For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.
There is the solution I used, which is based on Linus Borg answer and works fine with vue.js 2.0.
Vue.directive('click-outside', {
bind: function (el, binding, vnode) {
el.clickOutsideEvent = function (event) {
// here I check that click was outside the el and his children
if (!(el == event.target || el.contains(event.target))) {
// and if it did, call method provided in attribute value
vnode.context[binding.expression](event);
}
};
document.body.addEventListener('click', el.clickOutsideEvent)
},
unbind: function (el) {
document.body.removeEventListener('click', el.clickOutsideEvent)
},
});
You bind to it using v-click-outside
:
<div v-click-outside="doStuff">
You can find some more info about custom directives and what el, binding, vnode means in https://vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments
I hit the same problem and it turned out that reverse dns was not setup correct, it pointed to wrong hostname for the IP. After I correct reverse dns and restart httpd, the warning is gone. (if I don't correct reverse dns, adding ServerName did the trick for me as well)
The following code just declares a string variable that contains a MySQL query:
$sql = "INSERT INTO users (username, password, email)
VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";
It does not execute the query. In order to do that you need to use some functions but let me explain something else first.
NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET
or $_POST
) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here
To protect your script from such an attack you must use Prepared Statements. More on prepared statements here
Include prepared statements to your code like this:
$sql = "INSERT INTO users (username, password, email)
VALUES (?,?,?)";
Notice how the ?
are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare
:
$stmt = mysqli_prepare($sql);
Then start binding the input variables to the prepared statement:
$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);
And finally execute the prepared statements. (This is where the actual insertion takes place)
$stmt->execute();
NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash
to store a hash of the password
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
Use saveAs
on FileSaver.js github project.
FileSaver.js
implements the saveAs()
FileSaver interface in browsers that do not natively support it.
This:
doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));
should be:
doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));
LoadXml()
is for loading an XML string, not a file name.
UPDATE
In Android Studio AVD:
From the source code:
// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;
// SOME OTHER SUTFFF.......
/**
* Set the WebViewClient.
* @param client An implementation of WebViewClient.
*/
public void setWebViewClient(WebViewClient client) {
mWebViewClient = client;
}
/**
* Set the WebChromeClient.
* @param client An implementation of WebChromeClient.
*/
public void setWebChromeClient(WebChromeClient client) {
mWebChromeClient = client;
}
Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView
At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient
. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient
object and override the onReceivedIcon(WebView view, Bitmap icon)
.
Most of the times, if you don't want to worry about those things... you can just do this:
webView= (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
And your WebView will (in theory) have all features implemented (as the android native browser).
Invoke-Expression
should work perfectly, just make sure you are using it correctly. For your case it should look like this:
Invoke-Expression "$scriptPath $argumentList"
I tested this approach with Get-Service and seems to be working as expected.
Do your groupby, and use reset_index() to make it back into a DataFrame. Then sort.
grouped = df.groupby('mygroups').sum().reset_index()
grouped.sort_values('mygroups', ascending=False)
I was getting this problem with a remote repository on a Samba share; I pulled successfully from this remote, but failed when pushing to it.
The cause of the error was incorrect credentials in my ~/.smbcredentials
file.
YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".
save and open in excel, try refresh data and excel will be monit about parameters.
The cleanest way to achieve this in PHP is to simply use DESCRIBE statement.
if ( mysql_query( "DESCRIBE `my_table`" ) ) {
// my_table exists
}
I'm not sure why others are posting complicated queries for a such a straight forward problem.
Using PDO
// assuming you have already setup $pdo
$sh = $pdo->prepare( "DESCRIBE `my_table`");
if ( $sh->execute() ) {
// my_table exists
} else {
// my_table does not exist
}
A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form
Typically MethodNotAllowedHttpException
happens when
route method does not match.
Suppose you define POST
request route file, but you sending GET
request to the route.
try this Here is working Demo:
$(function() {
$('#btnSubmit').bind('click', function(){
var txtVal = $('#txtDate').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
});
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
//Checks for mm/dd/yyyy format.
dtMonth = dtArray[3];
dtDay= dtArray[5];
dtYear = dtArray[1];
if (dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay> 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if (dtDay> 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
});
changed regex is:
var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
Try this...
<a href="/path/to/image" download>
<img src="/path/to/image" />
</a>
It's now possible in modern browsers to position an element fixed relative to its container. An element that has a transform property acts as the viewport for any of its fixed position child elements.
Or as the CSS Transforms Module puts it:
For elements whose layout is governed by the CSS box model, any value other than none for the transform property also causes the element to establish a containing block for all descendants. Its padding box will be used to layout for all of its absolute-position descendants, fixed-position descendants, and descendant fixed background attachments.
.context {_x000D_
width: 300px;_x000D_
height: 250px;_x000D_
margin: 100px;_x000D_
transform: translateZ(0);_x000D_
}_x000D_
.viewport {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
border: 1px solid black;_x000D_
overflow: scroll;_x000D_
}_x000D_
.centered {_x000D_
position: fixed;_x000D_
left: 50%;_x000D_
bottom: 15px;_x000D_
transform: translateX(-50%);_x000D_
}
_x000D_
<div class="context">_x000D_
<div class="viewport">_x000D_
<div class="canvas">_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
<td>stuff</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<button class="centered">OK</button>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
I hope following program will solve your problem
String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
No, this is not possible. In documents that make use of CSS, an inline style
attribute can only contain property declarations; the same set of statements that appears in each ruleset in a stylesheet. From the Style Attributes spec:
The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces), whose formal grammar is given below in the terms and conventions of the CSS core grammar:
declaration-list : S* declaration? [ ';' S* declaration? ]* ;
Neither selectors (including pseudo-elements), nor at-rules, nor any other CSS construct are allowed.
Think of inline styles as the styles applied to some anonymous super-specific ID selector: those styles only apply to that one very element with the style
attribute. (They take precedence over an ID selector in a stylesheet too, if that element has that ID.) Technically it doesn't work like that; this is just to help you understand why the attribute doesn't support pseudo-class or pseudo-element styles (it has more to do with how pseudo-classes and pseudo-elements provide abstractions of the document tree that can't be expressed in the document language).
Note that inline styles participate in the same cascade as selectors in rule sets, and take highest precedence in the cascade (!important
notwithstanding). So they take precedence even over pseudo-class states. Allowing pseudo-classes or any other selectors in inline styles would possibly introduce a new cascade level, and with it a new set of complications.
Note also that very old revisions of the Style Attributes spec did originally propose allowing this, however it was scrapped, presumably for the reason given above, or because implementing it was not a viable option.
Open "localhost:8080" on your browser and see what is running on this port.
I did it and I just found Oracle 10g XE running on background, so I went to start->Services and stopped all oracle services. Then I redo mvnw spring-boot:run
on IntelliJ and it runs like magic.
High resolution is relative... I was looking at the examples and they mostly cater for milliseconds. However for me it is important to measure microseconds. I have not seen a platform independant solution for microseconds and thought something like the code below will be usefull. I was timing on windows only for the time being and will most likely add a gettimeofday() implementation when doing the same on AIX/Linux.
#ifdef WIN32
#ifndef PERFTIME
#include <windows.h>
#include <winbase.h>
#define PERFTIME_INIT unsigned __int64 freq; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq); unsigned __int64 startTime; unsigned __int64 endTime; double timeDifferenceInMilliseconds;
#define PERFTIME_START QueryPerformanceCounter((LARGE_INTEGER *)&startTime);
#define PERFTIME_END QueryPerformanceCounter((LARGE_INTEGER *)&endTime); timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency); printf("Timing %fms\n",timeDifferenceInMilliseconds);
#define PERFTIME(funct) {unsigned __int64 freq; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq); unsigned __int64 startTime; QueryPerformanceCounter((LARGE_INTEGER *)&startTime); unsigned __int64 endTime; funct; QueryPerformanceCounter((LARGE_INTEGER *)&endTime); double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency); printf("Timing %fms\n",timeDifferenceInMilliseconds);}
#endif
#else
//AIX/Linux gettimeofday() implementation here
#endif
Usage:
PERFTIME(ProcessIntenseFunction());
or
PERFTIME_INIT
PERFTIME_START
ProcessIntenseFunction()
PERFTIME_END
Date.now() returns a unix timestamp in milliseconds.
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
Try something like this:
public class test
{
public static void main(String a[])
{
long tmp = 1346524199000;
Date d = new Date(tmp);
System.out.println(d);
}
}
I am going to provide several solutions and you can choose the one that meets your needs:
1) If you are concerned with just the characters, i.e, same characters and having equal frequencies of each in both the strings, then use:
''.join(sorted(string1)).strip() == ''.join(sorted(string2)).strip()
2) If you are also concerned with the number of spaces (white space characters) in both strings, then simply use the following snippet:
sorted(string1) == sorted(string2)
3) If you are considering words but not their ordering and checking if both the strings have equal frequencies of words, regardless of their order/occurrence, then can use:
sorted(string1.split()) == sorted(string2.split())
4) Extending the above, if you are not concerned with the frequency count, but just need to make sure that both the strings contain the same set of words, then you can use the following:
set(string1.split()) == set(string2.split())
You could use Array.prototype.filter()
in combination with Array.prototype.some()
.
Here is an example (assuming your arrays are stored in the variables result1
and result2
):
//Find values that are in result1 but not in result2
var uniqueResultOne = result1.filter(function(obj) {
return !result2.some(function(obj2) {
return obj.value == obj2.value;
});
});
//Find values that are in result2 but not in result1
var uniqueResultTwo = result2.filter(function(obj) {
return !result1.some(function(obj2) {
return obj.value == obj2.value;
});
});
//Combine the two arrays of unique entries
var result = uniqueResultOne.concat(uniqueResultTwo);
Try something like this
PdfPCell cell;
PdfPTable tableHeader;
PdfPTable tmpTable;
PdfPTable table = new PdfPTable(10) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_LTR, ExtendLastRow = false };
// row 1 / cell 1 (merge)
PdfPCell _c = new PdfPCell(new Phrase("SER. No")) { Rotation = -90, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 2
_c = new PdfPCell(new Phrase("TYPE OF SHIPPING")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 3
_c = new PdfPCell(new Phrase("ORDER NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 4
_c = new PdfPCell(new Phrase("QTY.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 5
_c = new PdfPCell(new Phrase("DISCHARGE PPORT")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 6 (merge)
_c = new PdfPCell(new Phrase("DESCRIPTION OF GOODS")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 7
_c = new PdfPCell(new Phrase("LINE DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 8 (merge)
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 9 (merge)
_c = new PdfPCell(new Phrase("CLEARANCE DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 10 (merge)
_c = new PdfPCell(new Phrase("CUSTOM PERMIT NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 2 / cell 2
_c = new PdfPCell(new Phrase("AWB / BL NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 3
_c = new PdfPCell(new Phrase("COMPLEX NAME")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 4
_c = new PdfPCell(new Phrase("G.W Kgs.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 5
_c = new PdfPCell(new Phrase("DESTINATON")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 7
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
_doc.Add(table);
///////////////////////////////////////////////////////////
_doc.Close();
You might need to re-adjust slightly on the widths and borders but that is a one shot to do.
A table can have multiple candidate keys. Each candidate key is a column or set of columns that are UNIQUE, taken together, and also NOT NULL. Thus, specifying values for all the columns of any candidate key is enough to determine that there is one row that meets the criteria, or no rows at all.
Candidate keys are a fundamental concept in the relational data model.
It's common practice, if multiple keys are present in one table, to designate one of the candidate keys as the primary key. It's also common practice to cause any foreign keys to the table to reference the primary key, rather than any other candidate key.
I recommend these practices, but there is nothing in the relational model that requires selecting a primary key among the candidate keys.
I have a tsconfig.json
file that doesn't apply to any .ts files. It's in a separate folder. Instead I only use it as a base for other tsconfig files via "extends": "../Configs/tsconfig.json"
. As soon as I renamed the base config file to something else e.g. base-tsconfig.json
(and updated the extends
statements) the error went away and the extending still worked.
Try to think in terms of a model and what happens to that model when a checkbox is checked.
Assuming that each checkbox is bound to a field on the model with ng-model then the property on the model is changed whenever a checkbox is clicked:
<input type='checkbox' ng-model='fooSelected' />
<input type='checkbox' ng-model='baaSelected' />
and in the controller:
$scope.fooSelected = false;
$scope.baaSelected = false;
The next button should only be available under certain circumstances so add the ng-disabled directive to the button:
<button type='button' ng-disabled='nextButtonDisabled'></button>
Now the next button should only be available when either fooSelected is true or baaSelected is true and we need to watch any changes to these fields to make sure that the next button is made available or not:
$scope.$watch('[fooSelected,baaSelected]', function(){
$scope.nextButtonDisabled = !$scope.fooSelected && !scope.baaSelected;
}, true );
The above assumes that there are only a few checkboxes that affect the availability of the next button but it could be easily changed to work with a larger number of checkboxes and use $watchCollection to check for changes.
Well for me I had a complicated app startup in which I had created my own WebHostBuilder. This worked fine but failed when I tried the InProcess hosting mode. I assume there was something I missed calling in WebHostBuilder. So I made sure I always call WebHost.CreateDefaultBuilder(args), then make any extra changes - basically as the new app templates do.
Or for asp core 3.1 templates which use IHostBuilder (not IWebHostBuilder), call ConfigureWebHostDefaults
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
// add stuff here
webBuilder.UseStartup<Startup>();
});
They have nothing to do with each other.
Java is statically typed, compiles, runs on its own VM.
Javascript is dynamically typed, interpreted, and runs in a browser. It also has first-class functions and anonymous functions, which Java does not. It has direct access to web-page elements, which makes it useful for doing client-side processing.
They are also somewhat similar in syntax, but that's about it.
Persist and merge are for two different purposes (they aren't alternatives at all).
(edited to expand differences information)
persist:
merge:
persist() efficiency:
persist() semantics:
Example:
{
AnyEntity newEntity;
AnyEntity nonAttachedEntity;
AnyEntity attachedEntity;
// Create a new entity and persist it
newEntity = new AnyEntity();
em.persist(newEntity);
// Save 1 to the database at next flush
newEntity.setValue(1);
// Create a new entity with the same Id than the persisted one.
AnyEntity nonAttachedEntity = new AnyEntity();
nonAttachedEntity.setId(newEntity.getId());
// Save 2 to the database at next flush instead of 1!!!
nonAttachedEntity.setValue(2);
attachedEntity = em.merge(nonAttachedEntity);
// This condition returns true
// merge has found the already attached object (newEntity) and returns it.
if(attachedEntity==newEntity) {
System.out.print("They are the same object!");
}
// Set 3 to value
attachedEntity.setValue(3);
// Really, now both are the same object. Prints 3
System.out.println(newEntity.getValue());
// Modify the un attached object has no effect to the entity manager
// nor to the other objects
nonAttachedEntity.setValue(42);
}
This way only exists 1 attached object for any register in the entity manager.
merge() for an entity with an id is something like:
AnyEntity myMerge(AnyEntity entityToSave) {
AnyEntity attached = em.find(AnyEntity.class, entityToSave.getId());
if(attached==null) {
attached = new AnyEntity();
em.persist(attached);
}
BeanUtils.copyProperties(attached, entityToSave);
return attached;
}
Although if connected to MySQL merge() could be as efficient as persist() using a call to INSERT with ON DUPLICATE KEY UPDATE option, JPA is a very high level programming and you can't assume this is going to be the case everywhere.
In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.
If you guys see any issues with this please let me know and I'll fix it (etc. etc.)
Save it in a file called git-rm-ntb
(call it whatever) on PATH
and run:
git-rm-ntb <remote1:optional> <remote2:optional> ...
clean()
{
REMOTES="$@";
if [ -z "$REMOTES" ]; then
REMOTES=$(git remote);
fi
REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
RBRANCHES=()
while read REMOTE; do
CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
done < <(echo "$REMOTES" )
[[ $RBRANCHES ]] || exit
LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
for i in "${LBRANCHES[@]}"; do
skip=
for j in "${RBRANCHES[@]}"; do
[[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
done
[[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
done
}
clean $@
see there link was very nice and simple. its working fine... u don't want any library its working fine. click here
OnTouchListener gestureListener = new View.OnTouchListener() {
private int padding = 0;
private int initialx = 0;
private int currentx = 0;
private ViewHolder viewHolder;
public boolean onTouch(View v, MotionEvent event) {
if ( event.getAction() == MotionEvent.ACTION_DOWN) {
padding = 0;
initialx = (int) event.getX();
currentx = (int) event.getX();
viewHolder = ((ViewHolder) v.getTag());
}
if ( event.getAction() == MotionEvent.ACTION_MOVE) {
currentx = (int) event.getX();
padding = currentx - initialx;
}
if ( event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
padding = 0;
initialx = 0;
currentx = 0;
}
if(viewHolder != null) {
if(padding == 0) {
v.setBackgroundColor(0xFF000000 );
if(viewHolder.running)
v.setBackgroundColor(0xFF058805);
}
if(padding > 75) {
viewHolder.running = true;
v.setBackgroundColor(0xFF00FF00 );
viewHolder.icon.setImageResource(R.drawable.clock_running);
}
if(padding < -75) {
viewHolder.running = false;
v.setBackgroundColor(0xFFFF0000 );
}
v.setPadding(padding, 0,0, 0);
}
return true;
}
};
The ideal scenario is to have <add value="default.aspx" />
in config so the application can be deployed to any server without having to reconfigure. IMHO I think the implementation within IIS is poor.
We've used the following to make our default document setup more robust and as a result more SEO friendly by using canonical URL's:
<configuration>
<system.webServer>
<defaultDocument>
<files>
<remove value="default.aspx" />
<add value="default.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
Works OK for us.
Use Like This for HTML 4.01
<img src="image.gif" border="0">
A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work
$.each(object, function(index, value) {
console.log(value);
});
Another option would be to use vanilla Javascript using the Object.keys()
and the Array .map()
functions like this
Object.keys(object).map(function(objectKey, index) {
var value = object[objectKey];
console.log(value);
});
See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.
But usually, a for-loop doesn't work better than jQuery
or Object.keys().map()
. I'll go into two potential issues with using a plain for-loop below.
Right, so also pointed out in other answers, a plain Javascript alternative would be
for(var index in object) {
var attr = object[index];
}
There are two potential issues with this:
1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty
function like so
for(var index in object) {
if (object.hasOwnProperty(index)) {
var attr = object[index];
}
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.
The jQuery.each
and Object.keys
functions take care of this automatically.
2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log
like this:
<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>
var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) {
if (messagesByButtonId.hasOwnProperty(buttonId)) {
$('#'+buttonId).click(function() {
var message = messagesByButtonId[buttonId];
console.log(message);
});
}
}
If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId]
using the buttonId
variable at that moment. And since the loop has finished at that moment, the buttonId
variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId]
will be messagesByButtonId["button2"]
, i.e. "clicked last!".
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.
Again, jQuery.each
and Object.keys().map()
solve this problem automatically for us, because it provides us with a function(index, value)
(that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.