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 can literally convert it into float using:
float_value = float(integer_value)
Likewise, you can convert an integer back to float datatype with:
integer_value = int(float_value)
Hope it helped. I advice you to read "Build-In Functions of Python" at this link: https://docs.python.org/2/library/functions.html
This is most likely because you have multiple accounts, like one private, one for work with GitHub.
SOLUTION On Windows, go to Start > Credential Manager > Windows Credentials and remove GitHub creds, then try pulling or pushing again and you will be prompted to relogin into GitHub
SOLUTION OnMac, issue following on terminal:
git remote set-url origin https://[email protected]/username/repo-name.git
by replacing 'username' with your GitHub username in both places and providing your GitHub repo name.
The AtomicBoolean
class gives you a boolean value that you can update atomically. Use it when you have multiple threads accessing a boolean variable.
The java.util.concurrent.atomic package overview gives you a good high-level description of what the classes in this package do and when to use them. I'd also recommend the book Java Concurrency in Practice by Brian Goetz.
I got through the same error when I went on to the admin panel.
You ought to run this instead-: python manage.py migrate --run-syncdb
.
Don't forget to include migrate, I ran:
python manage.py make migrations
and then
python manage.py migrate
Still when the error persisted I tried it with the above suggested command.
I did it like this:
$missing = array();
foreach ($_POST as $key => $value) { if ($value == "") { array_push($missing, $key);}}
if (count($missing) > 0) {
echo "Required fields found empty: ";
foreach ($missing as $k => $v) { echo $v." ";}
} else {
unset($missing);
// do your stuff here with the $_POST
}
File -> Export -> Web -> WAR file
OR in Kepler follow as shown below :
Rotate by 90 degress around 0,0:
x' = -y
y' = x
Rotate by 90 degress around px,py:
x' = -(y - py) + px
y' = (x - px) + py
SET out_number=SQRT(input_number);
Instead of this write:
select SQRT(input_number);
Please don't write SET out_number
and your input parameter should be:
PROCEDURE `test`.`my_sqrt`(IN input_number INT, OUT out_number FLOAT)
You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts
Note: The category_name parameter needs to be a string, in this case, the category name.
TRY
/CATCH
error handling can take place either within or outside of a procedure (or both). The examples below demonstrate error handling in both cases.
If you want to experiment further, you can fork the query on Stack Exchange Data Explorer.
(This uses a temporary stored procedure... we can't create regular SP's on SEDE, but the functionality is the same.)
--our Stored Procedure
create procedure #myProc as --we can only create #temporary stored procedures on SEDE.
begin
BEGIN TRY
print 'This is our Stored Procedure.'
print 1/0 --<-- generate a "Divide By Zero" error.
print 'We are not going to make it to this line.'
END TRY
BEGIN CATCH
print 'This is the CATCH block within our Stored Procedure:'
+ ' Error Line #'+convert(varchar,ERROR_LINE())
+ ' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
--print 1/0 --<-- generate another "Divide By Zero" error.
-- uncomment the line above to cause error within the CATCH ¹
END CATCH
end
go
--our MAIN code block:
BEGIN TRY
print 'This is our MAIN Procedure.'
execute #myProc --execute the Stored Procedure
--print 1/0 --<-- generate another "Divide By Zero" error.
-- uncomment the line above to cause error within the MAIN Procedure ²
print 'Now our MAIN sql code block continues.'
END TRY
BEGIN CATCH
print 'This is the CATCH block for our MAIN sql code block:'
+ ' Error Line #'+convert(varchar,ERROR_LINE())
+ ' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
END CATCH
Here's the result of running the above sql as-is:
This is our MAIN Procedure.
This is our Stored Procedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
Now our MAIN sql code block continues.
¹ Uncommenting the "additional error line" from the Stored Procedure's CATCH block will produce:
This is our MAIN procedure.
This is our Stored Procedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
This is the CATCH block for our MAIN sql code block: Error Line #13 of procedure #myProc
² Uncommenting the "additional error line" from the MAIN procedure will produce:
This is our MAIN Procedure.
This is our Stored Pprocedure.
This is the CATCH block within our Stored Procedure: Error Line #5 of procedure #myProc
This is the CATCH block for our MAIN sql code block: Error Line #4 of procedure (Main)
On topic of stored procedures and error handling, it can be helpful (and tidier) to use a single, dynamic, stored procedure to handle errors for multiple other procedures or code sections.
Here's an example:
--our error handling procedure
create procedure #myErrorHandling as
begin
print ' Error #'+convert(varchar,ERROR_NUMBER())+': '+ERROR_MESSAGE()
print ' occurred on line #'+convert(varchar,ERROR_LINE())
+' of procedure '+isnull(ERROR_PROCEDURE(),'(Main)')
if ERROR_PROCEDURE() is null --check if error was in MAIN Procedure
print '*Execution cannot continue after an error in the MAIN Procedure.'
end
go
create procedure #myProc as --our test Stored Procedure
begin
BEGIN TRY
print 'This is our Stored Procedure.'
print 1/0 --generate a "Divide By Zero" error.
print 'We will not make it to this line.'
END TRY
BEGIN CATCH
execute #myErrorHandling
END CATCH
end
go
BEGIN TRY --our MAIN Procedure
print 'This is our MAIN Procedure.'
execute #myProc --execute the Stored Procedure
print '*The error halted the procedure, but our MAIN code can continue.'
print 1/0 --generate another "Divide By Zero" error.
print 'We will not make it to this line.'
END TRY
BEGIN CATCH
execute #myErrorHandling
END CATCH
This is our MAIN procedure.
This is our stored procedure.
Error #8134: Divide by zero error encountered.
occurred on line #5 of procedure #myProc
*The error halted the procedure, but our MAIN code can continue.
Error #8134: Divide by zero error encountered.
occurred on line #5 of procedure (Main)
*Execution cannot continue after an error in the MAIN procedure.
In the scope of a TRY
/CATCH
block, the following system functions can be used to obtain information about the error that caused the CATCH
block to be executed:
ERROR_NUMBER()
returns the number of the error. ERROR_SEVERITY()
returns the severity. ERROR_STATE()
returns the error state number. ERROR_PROCEDURE()
returns the name of the stored procedure or trigger where the error occurred. ERROR_LINE()
returns the line number inside the routine that caused the error. ERROR_MESSAGE()
returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times. (Source)
Note that there are two types of SQL errors: Terminal and Catchable. TRY
/CATCH
will [obviously] only catch the "Catchable" errors. This is one of a number of ways of learning more about your SQL errors, but it probably the most useful.
It's "better to fail now" (during development) compared to later because, as Homer says . . .
If you want it to display on your layout you should
For example:
activity_layout.XML file
<TextView
android:id="@+id/example_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
On the activity.java file
final TextView textView = findViewById(R.id.example_tv);
textView.setText(Integer.toString(yourNumberHere));
In the first line on the XML file you can see:
android:id="@+id/example_tv"
That's where you get the id to change in the .java file for the findViewById(R.id.example_tv)
Hope I made myself clear, I just went with this explanation because a lot of times people seem to know the ".setText()" method, they just can't change the text in the "UI".
EDIT Since this is a fairly old answer, and Kotlin is the preferred language for Android development, here's its counterpart.
With the same XML layout:
You can either use the findViewbyId()
or use Kotlin synthetic properties:
findViewById<TextView>(R.id.example_tv).text = yourNumberHere.toString()
// Or
example_tv?.text = yourNumberHere.toString()
The toString()
is from Kotlin's Any
object (comparable to the Java Object
):
The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.
There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0
tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
The closest link I could find to be useful for more information is this
Quote from above link:
What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.
From the Documentation for GetEXitCodeThread
Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.
My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.
If you don't have to come back on the page with keeping form's value, you can do that :
<form method="post" th:action="@{''}" th:object="${form}">
<input class="form-control"
type="text"
th:field="${client.name}"/>
It's some kind of magic :
If you matter keeping you form's input values, like a back on the page with an user input mistake, then you will have to do that :
<form method="post" th:action="@{''}" th:object="${form}">
<input class="form-control"
type="text"
th:name="name"
th:value="${form.name != null} ? ${form.name} : ${client.name}"/>
That means :
Without having to map your client bean to your form bean. And it works because once you submitted the form, the value arn't null but "" (empty)
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
For nearly all programming purposes, VBA and VB 6.0 are the same thing.
VBA cannot compile your program into an executable binary. You'll always need the host (a Word file and MS Word, for example) to contain and execute your project. You'll also not be able to create COM DLLs with VBA.
Apart from that, there is a difference in the IDE - the VB 6.0 IDE is more powerful in comparison. On the other hand, you have tight integration of the host application in VBA. Application-global objects (like "ActiveDocument") and events are available without declaration, so application-specific programming is straight-forward.
Still, nothing keeps you from firing up Word, loading the VBA IDE and solving a problem that has no relation to Word whatsoever. I'm not sure if there is anything that VB 6.0 can do (technically), and VBA cannot. I'm looking for a comparison sheet on the MSDN though.
If you want to select 100 records from 25th record:
select TOP 100 * from TableName
where PrimaryKeyField
NOT IN(Select TOP 24 PrimaryKeyField from TableName);
As Drew Taylor pointed out, branch deletion with -d only considers the current HEAD in determining if the branch is "fully merged". It will complain even if the branch is merged with some other branch. The error message could definitely be clearer in this regard... You can either checkout the merged branch before deleting, or just use git branch -D. The capital -D will override the check entirely.
There is a generic solution (for any type). Usability is good, but implementation should be improved: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/
This allows you to write very clean code like this:
string value = null;
int? x = value.ConvertOrDefault<int?>();
and also:
object obj = 1;
string value = null;
int x = 5;
if (value.TryConvert(out x))
Console.WriteLine("TryConvert example: " + x);
bool boolean = "false".ConvertOrDefault<bool>();
bool? nullableBoolean = "".ConvertOrDefault<bool?>();
int integer = obj.ConvertOrDefault<int>();
int negativeInteger = "-12123".ConvertOrDefault<int>();
int? nullableInteger = value.ConvertOrDefault<int?>();
MyEnum enumValue = "SecondValue".ConvertOrDefault<MyEnum>();
MyObjectBase myObject = new MyObjectClassA();
MyObjectClassA myObjectClassA = myObject.ConvertOrDefault<MyObjectClassA>();
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Here's a sample from wikipedia:
nonRecursivePostorder(rootNode)
nodeStack.push(rootNode)
while (! nodeStack.empty())
currNode = nodeStack.peek()
if ((currNode.left != null) and (currNode.left.visited == false))
nodeStack.push(currNode.left)
else
if ((currNode.right != null) and (currNode.right.visited == false))
nodeStack.push(currNode.right)
else
print currNode.value
currNode.visited := true
nodeStack.pop()
If your application is in foreground state, it means you are currently using the same app. So there is no need to show notification on the top generally.
But still if you want to show notification in that case you have to create your custom Alert View or Custom View like Toast or something else to show to the user that you have got a notification.
You can also show a badge on the top if you have such kind of feature in your app.
I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):
private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
if (updateSales == null) {
updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
}
updateSales.setInt(1, sales);
updateSales.setString(2, cof_name);
updateSales.executeUpdate();
}
At that point, it is then just a matter of calling:
updateSales(75, "Colombian");
Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...
Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.
char* c = new char[length]();
Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html
Steps to do update:
Under Custom properties select SQLCOMMAND and insert update command ex:
UPDATE table1 SET col1 = ?, col2 = ? where id = ?
map columns in exact order from source to output as in update command
I managed to do it myself. No need for any plugins. Check out my gist:
// Replace #fromA with your button/control and #toB with the target to which
// You wanna scroll to.
//
$("#fromA").click(function() {
$("html, body").animate({ scrollTop: $("#toB").offset().top }, 1500);
});
Use jQuery's IsNumeric method.
http://api.jquery.com/jQuery.isNumeric/
if ($.isNumeric(id)) {
//it's numeric
}
CORRECTION: that would not ensure an integer. This would:
if ( (id+"").match(/^\d+$/) ) {
//it's all digits
}
That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works
Couple of things to try:
settings.xml
file (at the following location {your home folder}/.m2/settings.xml
). Are you sure the local repo is where you think it is? (Yes, a mistake I've made in the past...)mvn -U dependency:resolve
should do it. The -U forces Maven to download no matter what your repository update policies are. Add -X
to get detailed debug logging.As a mobile developer, I was sad to find nothing native that supports auto resizing. My searches did not turn up anything that worked for me and in the end, I spent the better half of my weekend and created my own auto resize text view. I will post the code here and hopefully it will be useful for someone else.
This class uses a static layout with the text paint of the original text view to measure the height. From there, I step down by 2 font pixels and remeasure until I have a size that fits. At the end, if the text still does not fit, I append an ellipsis. I had requirements to animate the text and reuse views and this seems to work well on the devices I have and seems to run fast enough for me.
/**
* DO WHAT YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) 2004 Sam Hocevar <[email protected]>
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT YOU WANT TO.
*/
import android.content.Context;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
/**
* Text view that auto adjusts text size to fit within the view.
* If the text size equals the minimum text size and still does not
* fit, append with an ellipsis.
*
* @author Chase Colburn
* @since Apr 4, 2011
*/
public class AutoResizeTextView extends TextView {
// Minimum text size for this text view
public static final float MIN_TEXT_SIZE = 20;
// Interface for resize notifications
public interface OnTextResizeListener {
public void onTextResize(TextView textView, float oldSize, float newSize);
}
// Our ellipse string
private static final String mEllipsis = "...";
// Registered resize listener
private OnTextResizeListener mTextResizeListener;
// Flag for text and/or size changes to force a resize
private boolean mNeedsResize = false;
// Text size that is set from code. This acts as a starting point for resizing
private float mTextSize;
// Temporary upper bounds on the starting text size
private float mMaxTextSize = 0;
// Lower bounds for text size
private float mMinTextSize = MIN_TEXT_SIZE;
// Text view line spacing multiplier
private float mSpacingMult = 1.0f;
// Text view additional line spacing
private float mSpacingAdd = 0.0f;
// Add ellipsis to text that overflows at the smallest text size
private boolean mAddEllipsis = true;
// Default constructor override
public AutoResizeTextView(Context context) {
this(context, null);
}
// Default constructor when inflating from XML file
public AutoResizeTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
// Default constructor override
public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mTextSize = getTextSize();
}
/**
* When text changes, set the force resize flag to true and reset the text size.
*/
@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
mNeedsResize = true;
// Since this view may be reused, it is good to reset the text size
resetTextSize();
}
/**
* If the text view size changed, set the force resize flag to true
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw || h != oldh) {
mNeedsResize = true;
}
}
/**
* Register listener to receive resize notifications
* @param listener
*/
public void setOnResizeListener(OnTextResizeListener listener) {
mTextResizeListener = listener;
}
/**
* Override the set text size to update our internal reference values
*/
@Override
public void setTextSize(float size) {
super.setTextSize(size);
mTextSize = getTextSize();
}
/**
* Override the set text size to update our internal reference values
*/
@Override
public void setTextSize(int unit, float size) {
super.setTextSize(unit, size);
mTextSize = getTextSize();
}
/**
* Override the set line spacing to update our internal reference values
*/
@Override
public void setLineSpacing(float add, float mult) {
super.setLineSpacing(add, mult);
mSpacingMult = mult;
mSpacingAdd = add;
}
/**
* Set the upper text size limit and invalidate the view
* @param maxTextSize
*/
public void setMaxTextSize(float maxTextSize) {
mMaxTextSize = maxTextSize;
requestLayout();
invalidate();
}
/**
* Return upper text size limit
* @return
*/
public float getMaxTextSize() {
return mMaxTextSize;
}
/**
* Set the lower text size limit and invalidate the view
* @param minTextSize
*/
public void setMinTextSize(float minTextSize) {
mMinTextSize = minTextSize;
requestLayout();
invalidate();
}
/**
* Return lower text size limit
* @return
*/
public float getMinTextSize() {
return mMinTextSize;
}
/**
* Set flag to add ellipsis to text that overflows at the smallest text size
* @param addEllipsis
*/
public void setAddEllipsis(boolean addEllipsis) {
mAddEllipsis = addEllipsis;
}
/**
* Return flag to add ellipsis to text that overflows at the smallest text size
* @return
*/
public boolean getAddEllipsis() {
return mAddEllipsis;
}
/**
* Reset the text to the original size
*/
public void resetTextSize() {
if (mTextSize > 0) {
super.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
mMaxTextSize = mTextSize;
}
}
/**
* Resize text after measuring
*/
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (changed || mNeedsResize) {
int widthLimit = (right - left) - getCompoundPaddingLeft() - getCompoundPaddingRight();
int heightLimit = (bottom - top) - getCompoundPaddingBottom() - getCompoundPaddingTop();
resizeText(widthLimit, heightLimit);
}
super.onLayout(changed, left, top, right, bottom);
}
/**
* Resize the text size with default width and height
*/
public void resizeText() {
int heightLimit = getHeight() - getPaddingBottom() - getPaddingTop();
int widthLimit = getWidth() - getPaddingLeft() - getPaddingRight();
resizeText(widthLimit, heightLimit);
}
/**
* Resize the text size with specified width and height
* @param width
* @param height
*/
public void resizeText(int width, int height) {
CharSequence text = getText();
// Do not resize if the view does not have dimensions or there is no text
if (text == null || text.length() == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
return;
}
if (getTransformationMethod() != null) {
text = getTransformationMethod().getTransformation(text, this);
}
// Get the text view's paint object
TextPaint textPaint = getPaint();
// Store the current text size
float oldTextSize = textPaint.getTextSize();
// If there is a max text size set, use the lesser of that and the default text size
float targetTextSize = mMaxTextSize > 0 ? Math.min(mTextSize, mMaxTextSize) : mTextSize;
// Get the required text height
int textHeight = getTextHeight(text, textPaint, width, targetTextSize);
// Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
while (textHeight > height && targetTextSize > mMinTextSize) {
targetTextSize = Math.max(targetTextSize - 2, mMinTextSize);
textHeight = getTextHeight(text, textPaint, width, targetTextSize);
}
// If we had reached our minimum text size and still don't fit, append an ellipsis
if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) {
// Draw using a static layout
// modified: use a copy of TextPaint for measuring
TextPaint paint = new TextPaint(textPaint);
// Draw using a static layout
StaticLayout layout = new StaticLayout(text, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, false);
// Check that we have a least one line of rendered text
if (layout.getLineCount() > 0) {
// Since the line at the specific vertical position would be cut off,
// we must trim up to the previous line
int lastLine = layout.getLineForVertical(height) - 1;
// If the text would not even fit on a single line, clear it
if (lastLine < 0) {
setText("");
}
// Otherwise, trim to the previous line and add an ellipsis
else {
int start = layout.getLineStart(lastLine);
int end = layout.getLineEnd(lastLine);
float lineWidth = layout.getLineWidth(lastLine);
float ellipseWidth = textPaint.measureText(mEllipsis);
// Trim characters off until we have enough room to draw the ellipsis
while (width < lineWidth + ellipseWidth) {
lineWidth = textPaint.measureText(text.subSequence(start, --end + 1).toString());
}
setText(text.subSequence(0, end) + mEllipsis);
}
}
}
// Some devices try to auto adjust line spacing, so force default line spacing
// and invalidate the layout as a side effect
setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize);
setLineSpacing(mSpacingAdd, mSpacingMult);
// Notify the listener if registered
if (mTextResizeListener != null) {
mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
}
// Reset force resize flag
mNeedsResize = false;
}
// Set the text size of the text paint object and use a static layout to render text off screen before measuring
private int getTextHeight(CharSequence source, TextPaint paint, int width, float textSize) {
// modified: make a copy of the original TextPaint object for measuring
// (apparently the object gets modified while measuring, see also the
// docs for TextView.getPaint() (which states to access it read-only)
TextPaint paintCopy = new TextPaint(paint);
// Update the text paint object
paintCopy.setTextSize(textSize);
// Measure using a static layout
StaticLayout layout = new StaticLayout(source, paintCopy, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
return layout.getHeight();
}
}
Warning. There is an important fixed bug affecting Android 3.1 - 4.04 causing all AutoResizingTextView widgets not to work. Please read: https://stackoverflow.com/a/21851157/2075875
Try this code:
<select name="wgtmsr" id="wgtmsr">
<option value="kg">Kg</option>
<option value="gm">Gm</option>
<option value="pound">Pound</option>
<option value="MetricTon">Metric ton</option>
<option value="litre">Litre</option>
<option value="ounce">Ounce</option>
</select>
CSS:
#wgtmsr{
width:150px;
}
If you want to change the width of the option you can do this in your css:
#wgtmsr option{
width:150px;
}
Maybe you have a conflict in your css rules that override the width of your select
Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders })
, where orders
was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.
.where(`order.id IN (${orders})`);
All that's needed is: Start a new query and run:
SET SQL_SAFE_UPDATES = 0;
Then: Run the query that you were trying to run that wasn't previously working.
Wanted to add an example to funky-future's answer as I kept getting this error:
Uncaught TypeError: element.childNodes is not iterable
use like this:
replaceInText(document.body,"search term","replacement");
it didn't work for me with jQuery selectors.
to work this with unicode or fontawesome, you should add a span with class like below, because input tag not support pseudo classes like :after. this is not a direct solution
in html:
<span class="button1 search"></span>
<input name="username">
in css:
.button1 {
background-color: #B9D5AD;
border-radius: 0.2em 0 0 0.2em;
box-shadow: 1px 0 0 rgba(0, 0, 0, 0.5), 2px 0 0 rgba(255, 255, 255, 0.5);
pointer-events: none;
margin:1px 12px;
border-radius: 0.2em;
color: #333333;
cursor: pointer;
position: absolute;
padding: 3px;
text-decoration: none;
}
You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.
As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help
The high spike that you have is due to the DC (non-varying, i.e. freq = 0) portion of your signal. It's an issue of scale. If you want to see non-DC frequency content, for visualization, you may need to plot from the offset 1 not from offset 0 of the FFT of the signal.
Modifying the example given above by @PaulH
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = 10 + np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
plt.subplot(2, 1, 1)
plt.plot(xf, 2.0/N * np.abs(yf[0:N/2]))
plt.subplot(2, 1, 2)
plt.plot(xf[1:], 2.0/N * np.abs(yf[0:N/2])[1:])
The output plots:
Another way, is to visualize the data in log scale:
Using:
plt.semilogy(xf, 2.0/N * np.abs(yf[0:N/2]))
Will show:
Since ES2015, JavaScript has a notion of const
:
const MY_CONSTANT = "some-value";
This will work in pretty much all browsers except IE 8, 9 and 10. Some may also need strict mode enabled.
You can use var
with conventions like ALL_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code:
var MY_CONSTANT = "some-value";
Just use the -H
parameter several times:
curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
Surprisingly my solution is not yet given :) This is the simplest way for me. It doesn't need a function:
IFS=, eval 'joined="${foo[*]}"'
Note: This solution was observed to work well in non-POSIX mode. In POSIX mode, the elements are still joined properly, but IFS=,
becomes permanent.
you're comparing the result against a string ('false') not the built-in negative constant (false)
just use
if(ValidateForm() == false) {
or better yet
if(!ValidateForm()) {
also why are you calling validateForm twice?
Why use python at all? You might forget to remove it and check it into a repository. Just run your python command with && and another command to run to do the alerting.
python myscript.py &&
notify-send 'Alert' 'Your task is complete' &&
paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga
or drop a function into your .bashrc. I use apython here but you could override 'python'
function apython() {
/usr/bin/python $*
notify-send 'Alert' "python $* is complete"
paplay /usr/share/sounds/freedesktop/stereo/suspend-error.oga
}
on windows, the netstat option to get the pid's is -o and -p selects a protocol filter, ex.: netstat -a -p tcp -o
Using bootstrap multi select
Ajax
function() { $.ajax({
type : "get",
url : "OperatorController",
data : "input=" + $('#province').val(),
success : function(msg) {
var arrayOfObjects = eval(msg);
$("#operators").multiselect('dataprovider',
arrayOfObjects);
// $('#output').append(obj);
},
dataType : 'text'
});}
}
In Servlet
request.getParameter("input")
I have come to the conclusion that this is not possible without any plugins.
It appears that a number of people misunderstand what the differences between NULL, '\0' and 0 are. So, to explain, and in attempt to avoid repeating things said earlier:
A constant expression of type int
with the value 0, or an expression of this type, cast to type void *
is a null pointer constant, which if converted to a pointer becomes a null pointer. It is guaranteed by the standard to compare unequal to any pointer to any object or function.
NULL
is a macro, defined in as a null pointer constant.
\0
is a construction used to represent the null character, used to terminate a string.
A null character is a byte which has all its bits set to 0.
I would put decimal.MaxValue.ToString()
since this is the effective ceiling for the decmial type it is equivalent to not having an upper bound.
Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16)
comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413
does not allow.
Its not the gcc version alone, I has got something to with the distros
To insert tab space
between two words/sentences I usually use
 
and  
You can directly use hotkey from rich faces if you are using JSF.
<rich:hotKey key="backspace" onkeydown="if (event.keyCode == 8) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="f5" onkeydown="if (event.keyCode == 116) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+R" onkeydown="if (event.keyCode == 123) return false;" handler="return false;" disableInInput="true" />
<rich:hotKey key="ctrl+f5" onkeydown="if (event.keyCode == 154) return false;" handler="return false;" disableInInput="true" />
My wife suggested:
and all work!!!
<script type="text/javascript" src="http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js"></script>
Use ellipsize when you have fixed width, then it will automatically truncate the text & show the ellipsis at end,
it Won't work if you set layout_width as wrap_content & match_parent.
android:width="40dp"
android:ellipsize="end"
android:singleLine="true"
this.data
presumably contains all the data, so you would need to do something like this:
var stations = [];
var stationData = this.data.stations;
for (var i = 0; i < stationData.length; i++) {
stations.push(
<div key={stationData[i].call} className="station">
Call: {stationData[i].call}, Freq: {stationData[i].frequency}
</div>
)
}
render() {
return (
<div className="stations">{stations}</div>
)
}
Or you can use map
and arrow functions if you're using ES6:
const stations = this.data.stations.map(station =>
<div key={station.call} className="station">
Call: {station.call}, Freq: {station.frequency}
</div>
);
First create a DataGridTemplateColumn
to contain the button:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ShowHideDetails">Details</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
When the button is clicked, update the containing DataGridRow
's DetailsVisibility
:
void ShowHideDetails(object sender, RoutedEventArgs e)
{
for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
if (vis is DataGridRow)
{
var row = (DataGridRow)vis;
row.DetailsVisibility =
row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
break;
}
}
iReport does not work with java 8.
(you will find it here: iReport-x.x.x\etc\ )
change this line:
#jdkhome="/path/to/jdk"
to this (if not this is your java 7 install dir then replace the parameter value between ""s with your installed java 7's path):
jdkhome="C:\Program Files\Java\jdk1.7.0_67"
you must use import android.support.v7.app.ActionBarDrawerToggle;
and use the constructor
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout)
{
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}
and if the drawer toggle button becomes dark then you must use the supportActionBar provided in the support library.
You can implement supportActionbar from this link: http://developer.android.com/training/basics/actionbar/setting-up.html
This works for me.
<div style="position: relative;width:100%;">
<div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
This will be on the left
</div>
<div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
This will be on the right
</div>
</div>
There is a library which allows you to use HttpClient with strongly-typed callbacks.
The data and the error are available directly via these callbacks.
When you use HttpClient with Observable, you have to use .subscribe(x=>...) in the rest of your code.
This is because Observable<HttpResponse
<T
>> is tied to HttpResponse.
This tightly couples the http layer with the rest of your code.
This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.
With strongly-typed callbacks, you only have to deal with your Models in the rest of your code.
The library is called angular-extended-http-client.
angular-extended-http-client library on GitHub
angular-extended-http-client library on NPM
Very easy to use.
The strongly-typed callbacks are
Success:
T
>T
>Failure:
TError
>TError
>import { HttpClientExtModule } from 'angular-extended-http-client';
and in the @NgModule imports
imports: [
.
.
.
HttpClientExtModule
],
//Normal response returned by the API.
export class RacingResponse {
result: RacingItem[];
}
//Custom exception thrown by the API.
export class APIException {
className: string;
}
In your Service, you just create params with these callback types.
Then, pass them on to the HttpClientExt's get method.
import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.
@Injectable()
export class RacingService {
//Inject HttpClientExt component.
constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {
}
//Declare params of type IObservable<T> and IObservableError<TError>.
//These are the success and failure callbacks.
//The success callback will return the response objects returned by the underlying HttpClient call.
//The failure callback will return the error objects returned by the underlying HttpClient call.
getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
let url = this.config.apiEndpoint;
this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
}
}
In your Component, your Service is injected and the getRaceInfo API called as shown below.
ngOnInit() {
this.service.getRaceInfo(response => this.result = response.result,
error => this.errorMsg = error.className);
}
Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.
You only deal with your Models in these strongly-typed callbacks.
Hence, The rest of your code only knows about your Models.
Also, you can still use the traditional route and return Observable<HttpResponse<
T>
> from Service API.
Here's a more portable version (just for fun, it is not necessary in your case):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT
try:
from subprocess import DEVNULL # py3k
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
text = u"René Descartes"
p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(text.encode('utf-8'))
assert p.returncode == 0 # use appropriate for your program error handling here
iloc
df1 = datasX.iloc[:, :72]
df2 = datasX.iloc[:, 72:]
You need an additional library for code coverage, and you are going to be blown away by how powerful and easy istanbul is. Try the following, after you get your mocha tests to pass:
npm install nyc
Now, simply place the command nyc in front of your existing test command, for example:
{
"scripts": {
"test": "nyc mocha"
}
}
Another option:
=MID(A1,2,LEN(A1)-2)
Or this (for fun):
=RIGHT(LEFT(A1,LEN(A1)-1),LEN(LEFT(A1,LEN(A1)-1))-1)
The while increments the i. So you get:
data[1][0]
data[2][0]
data[3][0]
...
It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.
So, after After reviewing the code again, I found the error. I am wondering how no one notice that! In the above code I wrote
Post::create(request([ // <= the error is Here!!!
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]));
actually, there is no need for the request function warping the body of the create function.
// this is right
Post::create([
'body' => request('body'),
'title' => request('title'),
'user_id' => auth()->id()
]);
One of the first things that you should check is that the SQL Server (MSSQLSERVER) is started. You can go to the Services Console (services.msc) and look for SQL Server (MSSQLSERVER) to see that it is started. If not, then start the service.
You could also do this through an elevated command prompt by typing net start mssqlserver
.
Theta Join:
When you make a query for join using any operator,(e.g., =, <, >, >= etc.), then that join query comes under Theta join.
Equi Join:
When you make a query for join using equality operator only, then that join query comes under Equi join.
Example:
> SELECT * FROM Emp JOIN Dept ON Emp.DeptID = Dept.DeptID; > SELECT * FROM Emp INNER JOIN Dept USING(DeptID)
This will show: _________________________________________________ | Emp.Name | Emp.DeptID | Dept.Name | Dept.DeptID | | | | | |
Note: Equi join is also a theta join!
Natural Join:
a type of Equi Join which occurs implicitly by comparing all the same names columns in both tables.
Note: here, the join result has only one column for each pair of same named columns.
Example
SELECT * FROM Emp NATURAL JOIN Dept
This will show: _______________________________ | DeptID | Emp.Name | Dept.Name | | | | |
This works too. The below statement rounds to two decimal places.
SELECT ROUND(92.258,2) from dual;
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(foo);
foreach (PropertyDescriptor property in properties)
{
if (property.Name == "Name")
{
Console.WriteLine(property.DisplayName); // Something To Name
}
}
where foo
is an instance of Class1
I have no affiliation with this program, but if you are looking to open any of this in the finder SimPholders makes it incredibly easy.
Syntax:
$(selector).text()
content
: $(selector).text(content)
$(selector).text(function(index, curContent))
In order to determine the aspect ratio, you need to have a ratio to aim for.
function getHeight(length, ratio) {
var height = ((length)/(Math.sqrt((Math.pow(ratio, 2)+1))));
return Math.round(height);
}
function getWidth(length, ratio) {
var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
return Math.round(width);
}
In this example I use 16:10
since this the typical monitor aspect ratio.
var ratio = (16/10);
var height = getHeight(300,ratio);
var width = getWidth(height,ratio);
console.log(height);
console.log(width);
Results from above would be 147
and 300
I made a sample WebApp in May 2012 that uses JDO 3.0 & DataNucleus 3.0 - take a look how clean it is: https://github.com/TorbenVesterager/BadAssWebApp
Okay maybe it's a little bit too clean, because I use the POJOs both for the database and the JSON client, but it's fun :)
PS: Contains a few SuppressWarnings annotations (developed in IntelliJ 11)
Note that $(element).offset()
tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed
you can get unexpected results.
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled.
If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop()
value from the fixed element's offset().top
value. Example: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document, you want to read parseInt($.css('top'))
instead.
Try using an anonymous function instead:
expect( function(){ parser.parse(raw); } ).toThrow(new Error("Parsing is not possible"));
you should be passing a function into the expect(...)
call. Your incorrect code:
// incorrect:
expect(parser.parse(raw)).toThrow(new Error("Parsing is not possible"));
is trying to actually call parser.parse(raw)
in an attempt to pass the result into expect(...)
,
What you need (for tic-tac-toe or a far more difficult game like Chess) is the minimax algorithm, or its slightly more complicated variant, alpha-beta pruning. Ordinary naive minimax will do fine for a game with as small a search space as tic-tac-toe, though.
In a nutshell, what you want to do is not to search for the move that has the best possible outcome for you, but rather for the move where the worst possible outcome is as good as possible. If you assume your opponent is playing optimally, you have to assume they will take the move that is worst for you, and therefore you have to take the move that MINimises their MAXimum gain.
This makes it so if before there was a scrollbar then it makes it so the scrollbar has a display of none so you can't see it anymore. You can replace html to body or a class or ID. Hope it works for you :)
html::-webkit-scrollbar {
display: none;
}
$(".testClick").click(function () {
var value = $(this).attr("href");
alert(value );
});
When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.
Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).
I used 1.5 for the other server, so I waisted a lot of time on this.
Tricky issue.
Inspired by cyptus's answer I used
_dbContext.Database.CreateIfNotExists();
on EF6 before the first database contact (before DB seeding).
Struggled a bit with this one, but ended up with the following solution... maybe it will help someone.
HTML template:
<select (change)="onValueChanged($event.target)">
<option *ngFor="let option of uifOptions" [value]="option.value" [selected]="option == uifSelected ? true : false">{{option.text}}</option>
</select>
Component:
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
export class UifDropdownComponent implements OnInit {
@Input() uifOptions: {value: string, text: string}[];
@Input() uifSelectedValue: string = '';
@Output() uifSelectedValueChange:EventEmitter<string> = new EventEmitter<string>();
uifSelected: {value: string, text: string} = {'value':'', 'text':''};
constructor() { }
onValueChanged(target: HTMLSelectElement):void {
this.uifSelectedValue = target.value;
this.uifSelectedValueChange.emit(this.uifSelectedValue);
}
ngOnInit() {
this.uifSelected = this.uifOptions.filter(o => o.value ==
this.uifSelectedValue)[0];
}
}
Try
//book[title/@lang = 'it']
This reads:
book
elements
title
lang
"it"
You may find this helpful — it's an article entitled "XPath in Five Paragraphs" by Ronald Bourret.
But in all honesty, //book[title[@lang='it']]
and the above should be equivalent, unless your XPath engine has "issues." So it could be something in the code or sample XML that you're not showing us -- for example, your sample is an XML fragment. Could it be that the root element has a namespace, and you aren't counting for that in your query? And you only told us that it didn't work, but you didn't tell us what results you did get.
public mySentences:Array<Object> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Or rather,
export interface type{
id:number;
text:string;
}
public mySentences:type[] = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
The correct script for postgres (Ubuntu) is:
COPY (SELECT * FROM tbl) TO '/var/lib/postgres/myfile1.csv';
a = " ".join(str(i) for i in range(10, 0, -1))
print (a)
Here's one way to do it with Awk that's relatively easy to understand:
awk '{print substr($0, index($0, $3))}'
This is a simple awk command with no pattern, so action inside {}
is run for every input line.
The action is to simply prints the substring starting with the position of the 3rd field.
$0
: the whole input line$3
: 3rd fieldindex(in, find)
: returns the position of find
in string in
substr(string, start)
: return a substring starting at index start
If you want to use a different delimiter, such as comma, you can specify it with the -F option:
awk -F"," '{print substr($0, index($0, $3))}'
You can also operate this on a subset of the input lines by specifying a pattern before the action in {}
. Only lines matching the pattern will have the action run.
awk 'pattern{print substr($0, index($0, $3))}'
Where pattern can be something such as:
/abcdef/
: use regular expression, operates on $0 by default.$1 ~ /abcdef/
: operate on a specific field.$1 == blabla
: use string comparisonNR > 1
: use record/line numberNF > 0
: use field/column numbertry this code its very simple and usefull
public boolean isMockLocationEnabled() {
boolean isMockLocation = false;
try {
//if marshmallow
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AppOpsManager opsManager = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
isMockLocation = (opsManager.checkOp(AppOpsManager.OPSTR_MOCK_LOCATION, android.os.Process.myUid(), BuildConfig.APPLICATION_ID)== AppOpsManager.MODE_ALLOWED);
} else {
// in marshmallow this will always return true
isMockLocation = !android.provider.Settings.Secure.getString(getApplicationContext().getContentResolver(), "mock_location").equals("0");
}
} catch (Exception e) {
return isMockLocation;
}
return isMockLocation;
}
HttpContext.Current.Request.QueryString.Get("id");
It is not possible to prevent software piracy completely. You can prevent casual piracy and that's what all licensing solutions out their do.
Node (machine) locked licensing is best if you want to prevent reuse of license keys. I have been using Cryptlex for about a year now for my software. It has a free plan also, so if you don't expect too many customers you can use it for free.
Here's what I use:
#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
// Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
// Unix
#elif __linux__
// linux
#elif __APPLE__
// Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif
EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.
I use a short method to do the trick, I recommend you to do the same as it could save some hours & give you more visibility
Just add the following snippet into your .bashrc (.bashprofile on macos).
git-cleaner() { git fetch --all --prune && git branch --merged | grep -v -E "\bmaster|preprod|dmz\b" | xargs -n 1 git branch -d ;};
- Fetch all remotes
- Get only merged branches from git
- Remove from this list the "protected / important" branches
- Remove the rest (e.g, clean and merged branches)
You'll have to edit the grep regex in order to fit to your needs (here, it prevent master, preprod and dmz from deletion)
What you're doing there is not recursing into directories. It is only listing the modules in the root directory of the @INC
directory.
The module XML::Simple
will live in one of the @INC
paths under XML/Simple.pm
.
What he said above to find specific modules.
CPAN
explains how to find all modules here, see How to find installed modules.
Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME)
:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
int id();
}
As in your example, the fit_start_time
is not later than the fit_end_time
.
Try it the other way round:
var fit_start_time = $("#fit_start_time").val(); //2013-09-5
var fit_end_time = $("#fit_end_time").val(); //2013-09-10
if(Date.parse(fit_start_time) <= Date.parse(fit_end_time)){
alert("Please select a different End Date.");
}
Update
Your code implies that you want to see the alert
with the current variables you have. If this is the case then the above code is correct. If you're intention (as per the implication of the alert message
) is to make sure their fit_start_time
variable is a date that is before the fit_end_time
, then your original code is fine, but the data you're getting from the jQuery .val()
methods is not parsing correctly. It would help if you gave us the actual HTML which the selector is sniffing at.
I'm not really sure of your question, but if all you really want is list currently opened screen session, try:
screen -ls
Here is how my code looks like. It also shows an example of how to use query parameters using a dictionary. It works on using Python 3.6:
import cx_Oracle
CONN_INFO = {
'host': 'xxx.xx.xxx.x',
'port': 12345,
'user': 'SOME_SCHEMA',
'psw': 'SECRETE',
'service': 'service.server.com'
}
CONN_STR = '{user}/{psw}@{host}:{port}/{service}'.format(**CONN_INFO)
QUERY = '''
SELECT
*
FROM
USER
WHERE
NAME = :name
'''
class DB:
def __init__(self):
self.conn = cx_Oracle.connect(CONN_STR)
def query(self, query, params=None):
cursor = self.conn.cursor()
result = cursor.execute(query, params).fetchall()
cursor.close()
return result
db = DB()
result = db.query(QUERY, {'name': 'happy'})
I always do input prompts, like this:
<input style="color: #C0C0C0;" value="[email protected]"
onfocus="this.value=''; this.style.color='#000000'">
Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:
<script language = "text/Javascript">
cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
function clearField(t){ //declaring the array outside of the
if(! cleared[t.id]){ // function makes it static and global
cleared[t.id] = 1; // you could use true and false, but that's more typing
t.value=''; // with more chance of typos
t.style.color='#000000';
}
}
</script>
Your <input> field then looks like this:
<input id = 0; style="color: #C0C0C0;" value="[email protected]"
onfocus=clearField(this)>
There is a function strtobool
in Python's standard library: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool
You can use it to check user's input and transform it to True
or False
value.
I was creating a form in which the user enters an email address used by another macro to email a specific cell group to the address entered. I patched together this simple code from several sites and my limited knowledge of VBA. This simply watches for one cell (In my case K22) to be updated and then kills any hyperlink in that cell.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("K22")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
Range("K22").Select
Selection.Hyperlinks.Delete
End If
End Sub
Example
<div ng-controller="ExampleController">
<form name="myform">
Name: <input type="text" ng-model="user.name" /><br>
Email: <input type="email" ng-model="user.email" /><br>
</form>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
//if form is not valid then return the form.
if(!$scope.myform.$valid) {
return;
}
}]);
</script>
As others have mentioned... A depth first search will solve it. In general depth first search takes O(V + E) but in this case you know the graph has at most O(V) edges. So you can simply run a DFS and once you see a new edge increase a counter. When the counter has reached V you don't have to continue because the graph has certainly a cycle. Obviously this takes O(v).
By using the ref
keyword with reference types you are effectively passing a reference to the reference. In many ways it's the same as using the out
keyword but with the minor difference that there's no guarantee that the method will actually assign anything to the ref
'ed parameter.
The fix for the heartbleed
vulnerability has been backported to 1.0.1e-16
by Red Hat for Enterprise Linux see, and this is therefore the official fix that CentOS ships.
Replacing OpenSSL with the latest version from upstream (i.e. 1.0.1g) runs the risk of introducing functionality changes which may break compatibility with applications/clients in unpredictable ways, causes your system to diverge from RHEL, and puts you on the hook for personally maintaining future updates to that package. By replacing openssl using a simple make config && make && make install means that you also lose the ability to use rpm to manage that package and perform queries on it (e.g. verifying all the files are present and haven't been modified or had permissions changed without also updating the RPM database).
I'd also caution that crypto software can be extremely sensitive to seemingly minor things like compiler options, and if you don't know what you're doing, you could introduce vulnerabilities in your local installation.
This option comes in curl 7.73.0:
curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg
This variant -
<a title="Some "text"">Hover me</a>
_x000D_
Is correct and it works as expected - you see normal quotes in rendered page.
It probably works with Javascript. When you click the link, nothing happens because it points to the current site. The javascript will then load a window or an url. It's used a lot in AJAX web apps.
Here's one way:
create table #work
(
something decimal(8,3) not null
)
insert #work values ( 0 )
insert #work values ( 12345.6789 )
insert #work values ( 3.1415926 )
insert #work values ( 45 )
insert #work values ( 9876.123456 )
insert #work values ( -12.5678 )
select convert(varchar,convert(decimal(8,2),something))
from #work
if you want it right-aligned, something like this should do you:
select str(something,8,2) from #work
If you would like to ignore case you could use the following:
String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
//-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
// strings are equal.
}
Install the extension "Code Runner". Check if you can compile your program with csc
(ex.: csc hello.cs
). The command csc
is shipped with Mono. Then add this to your VS Code user settings:
"code-runner.executorMap": {
"csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
// "csharp": "echo '# calling dotnet run\n' && dotnet run"
}
Open your C# file and use the execution key of Code Runner.
Edit: also added dotnet run
, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console
, dotnet restore
).
you can check length of items
ng-show="items.length"
I find this one-line code as most efficient and useful:
File file = new File(ClassLoader.getSystemResource("com/path/to/file.txt").getFile());
Works like a charm.
I wanted to add something new because of the following:
At a first attemp I failed to beat
std::ostringstream
's operator<<
efficiency, but with more attemps I was able to make a StringBuilder that is faster in some cases.
Everytime I append a string I just store a reference to it somewhere and increase the counter of the total size.
The real way I finally implemented it (Horror!) is to use a opaque buffer(std::vector < char > ):
for byte [ ]
for moved strings (strings appended with std::move
)
std::string
object (we have ownership)for strings
std::string
object (no ownership)There's also one small optimization, if last inserted string was mov'd in, it checks for free reserved but unused bytes and store further bytes in there instead of using the opaque buffer (this is to save some memory, it actually make it slightly slower, maybe depend also on the CPU, and it is rare to see strings with extra reserved space anyway)
This was finally slightly faster than std::ostringstream
but it has few downsides:
ostringstream
conclusion? use
std::ostringstream
It already fix the biggest bottleneck while ganing few % points in speed with mine implementation is not worth the downsides.
You don't need andorid for this. You can just do it in simple java.
Have you tried a simple java example and see if this returns the right sha1.
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class AeSimpleSHA1 {
private static String convertToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (byte b : data) {
int halfbyte = (b >>> 4) & 0x0F;
int two_halfs = 0;
do {
buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
halfbyte = b & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] textBytes = text.getBytes("iso-8859-1");
md.update(textBytes, 0, textBytes.length);
byte[] sha1hash = md.digest();
return convertToHex(sha1hash);
}
}
Also share what your expected sha1 should be. Maybe ObjectC is doing it wrong.
$(document).ready(function(){
$("#dateFrom").datepicker({
todayBtn: 1,
autoclose: true,
}).on('changeDate', function (selected) {
var minDate = new Date(selected.date.valueOf());
$('#dateTo').datepicker('setStartDate', minDate);
});
$("#dateTo").datepicker({
todayBtn: 1,
autoclose: true,}) ;
});
if input == 'a':
for char in 'abc':
if char in some_list:
some_list.remove(char)
Without purisms, I think that the best way to emulate scalar argument by reference in JavaScript is using object, like previous an answer tells.
However, I do a little bit different:
I've made the object assignment inside function call, so one can see the reference parameters near the function call. It increases the source readability.
In function declaration, I put the properties like a comment, for the very same reason: readability.
var r;
funcWithRefScalars(r = {amount:200, message:null} );
console.log(r.amount + " - " + r.message);
function funcWithRefScalars(o) { // o(amount, message)
o.amount *= 1.2;
o.message = "20% increase";
}
In the above example, null
indicates clearly an output reference parameter.
The exit:
240 - 20% Increase
On the client-side, console.log
should be replaced by alert
.
? ? ?
Another method that can be even more readable:
var amount, message;
funcWithRefScalars(amount = [200], message = [null] );
console.log(amount[0] + " - " + message[0]);
function funcWithRefScalars(amount, message) { // o(amount, message)
amount[0] *= 1.2;
message[0] = "20% increase";
}
Here you don't even need to create new dummy names, like r
above.
This issue has been recently fixed (Nov 2010) by Google, see https://code.google.com/p/analytics-issues/issues/detail?id=671. But be aware that as a good fix it brings more bugs :)
You will also have to follow the initialisation method listed here: https://developers.google.com/analytics/devguides/collection/ios/v2.
The latest instructions are going to give you a headache because it references utilities not included in the pod. Below will fail with the cocoapod
// Configure tracker from GoogleService-Info.plist.
NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);
DATE_FORMAT(FROM_UNIXTIME(`orderdate`), '%Y-%m-%d %H:%i:%s') as "Date" FROM `orders`
This is the ultimate solution if the given date is in encoded format like 1300464000
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
If you want to trigger the keypress or keydown event then all you have to do is:
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);
If you need to increase MySQL Connections without MySQL restart do like below
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 100 |
+-----------------+-------+
1 row in set (0.00 sec)
mysql> SET GLOBAL max_connections = 150;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 150 |
+-----------------+-------+
1 row in set (0.00 sec)
These settings will change at MySQL Restart.
For permanent changes add below line in my.cnf and restart MySQL
max_connections = 150
An example I found somewhere here in the past. Might be of some help:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class Form1 : Form
{
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
//Mouse actions
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
public Form1()
{
}
public void DoMouseClick()
{
//Call the imported function with the cursor's current position
uint X = (uint)Cursor.Position.X;
uint Y = (uint)Cursor.Position.Y;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
}
//...other code needed for the application
}
iOS 9 onwards :
As statusBarHidden
method was Deprecated from iOS9 you need to add two values in plist as below :
<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
or by User Interface Please refre below image :
As statusBarHidden
is Deprecated from iOS9 :
@property(readwrite, nonatomic,getter=isStatusBarHidden) BOOL statusBarHidden NS_DEPRECATED_IOS(2_0, 9_0, "Use -[UIViewController prefersStatusBarHidden]") __TVOS_PROHIBITED;
I created a ~/.wgetrc
file with the following content (obtained from askapache.com but with a newer user agent, because otherwise it didn’t work always):
header = Accept-Language: en-us,en;q=0.5
header = Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
header = Connection: keep-alive
user_agent = Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0
referer = /
robots = off
Now I’m able to download from most (all?) file-sharing (streaming video) sites.
Since you haven't posted any code, it's difficult to know exactly which problems you're encountering. However, the blog post you link to does seem to work pretty decently... aside from the extra comma in each call to CCCrypt()
which caused compile errors.
A later comment on that post includes this adapted code, which works for me, and seems a bit more straightforward. If you include their code for the NSData category, you can write something like this: (Note: The printf()
calls are only for demonstrating the state of the data at various points — in a real application, it wouldn't make sense to print such values.)
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *key = @"my password";
NSString *secret = @"text to encrypt";
NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [plain AES256EncryptWithKey:key];
printf("%s\n", [[cipher description] UTF8String]);
plain = [cipher AES256DecryptWithKey:key];
printf("%s\n", [[plain description] UTF8String]);
printf("%s\n", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] UTF8String]);
[pool drain];
return 0;
}
Given this code, and the fact that encrypted data will not always translate nicely into an NSString, it may be more convenient to write two methods that wrap the functionality you need, in forward and reverse...
- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}
- (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
return [[[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
encoding:NSUTF8StringEncoding] autorelease];
}
This definitely works on Snow Leopard, and @Boz reports that CommonCrypto is part of the Core OS on the iPhone. Both 10.4 and 10.5 have /usr/include/CommonCrypto
, although 10.5 has a man page for CCCryptor.3cc
and 10.4 doesn't, so YMMV.
EDIT: See this follow-up question on using Base64 encoding for representing encrypted data bytes as a string (if desired) using safe, lossless conversions.
You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.
#git submodule [--quiet] add [-b branch] [-f|--force]
git submodule add /var/Node-repo.git common
You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.
#!/bin/sh
#clone git repo
git clone your-repo.git
For this example you really should just use an outer join.
declare
begin
FOR attr_rec IN (
select attr
from USER_TABLE u
left outer join attribute_table a
on ( u.USERTYPE = 'X' and a.user_id = u.id )
) LOOP
<process records>
<if primary key of attribute_table is null
then the attribute does not exist for this user.>
END LOOP;
END;
There are 6 types of string concatenations:
+
) symbol.string.Concat()
.string.Join()
.string.Format()
.string.Append()
.StringBuilder
.In an experiment, it has been proved that string.Concat()
is the best way to approach if the words are less than 1000(approximately) and if the words are more than 1000 then StringBuilder
should be used.
For more information, check this site.
string.Join() vs string.Concat()
The string.Concat method here is equivalent to the string.Join method invocation with an empty separator. Appending an empty string is fast, but not doing so is even faster, so the string.Concat method would be superior here.
The query component is indicated by the first ?
in a URI. "Query string" might be a synonym (this term is not used in the URI standard).
Some examples for HTTP URIs with query components:
http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b
(list of allowed characters in the query component)
The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b
.
Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.
Example URI with parameters in the path, the query, and the fragment:
http://example.com/foo;key1=value1?key2=value2#key3=value3
¹ The URI standard says about the query component:
[…] query components are often used to carry identifying information in the form of "key=value" pairs […]
² The URI standard says about the path component:
[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.
The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:
Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.
Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.
To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark
was used.
require_relative 'base'
require 'benchmark'
class LargeDOM < Base
LOCATORS = {
nested_sibling_traversal: {
css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
},
nested_sibling_traversal_by_class: {
css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
},
table_header_id_and_class: {
css: "table#large-table thead .column-50",
xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
},
table_header_id_class_and_direct_desc: {
css: "table#large-table > thead .column-50",
xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
},
table_header_traversing: {
css: "table#large-table thead tr th:nth-of-type(50)",
xpath: "//table[@id='large-table']//thead//tr//th[50]"
},
table_header_traversing_and_direct_desc: {
css: "table#large-table > thead > tr > th:nth-of-type(50)",
xpath: "//table[@id='large-table']/thead/tr/th[50]"
},
table_cell_id_and_class: {
css: "table#large-table tbody .column-50",
xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
},
table_cell_id_class_and_direct_desc: {
css: "table#large-table > tbody .column-50",
xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
},
table_cell_traversing: {
css: "table#large-table tbody tr td:nth-of-type(50)",
xpath: "//table[@id='large-table']//tbody//tr//td[50]"
},
table_cell_traversing_and_direct_desc: {
css: "table#large-table > tbody > tr > td:nth-of-type(50)",
xpath: "//table[@id='large-table']/tbody/tr/td[50]"
}
}
attr_reader :driver
def initialize(driver)
@driver = driver
visit '/large'
is_displayed?(id: 'siblings')
super
end
# The benchmarking approach was borrowed from
# http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
def benchmark
Benchmark.bmbm(27) do |bm|
LOCATORS.each do |example, data|
data.each do |strategy, locator|
bm.report(example.to_s + " using " + strategy.to_s) do
begin
ENV['iterations'].to_i.times do |count|
find(strategy => locator)
end
rescue Selenium::WebDriver::Error::NoSuchElementError => error
puts "( 0.0 )"
end
end
end
end
end
end
end
NOTE: The output is in seconds, and the results are for the total run time of 100 executions.
In Table Form:
In Chart Form:
You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.
System.Net.WebUtility.HtmlDecode
I might be a bit late to the game, but this worked for me when calling open
in another module without having to create a new file.
test.py
import unittest
from mock import Mock, patch, mock_open
from MyObj import MyObj
class TestObj(unittest.TestCase):
open_ = mock_open()
with patch.object(__builtin__, "open", open_):
ref = MyObj()
ref.save("myfile.txt")
assert open_.call_args_list == [call("myfile.txt", "wb")]
MyObj.py
class MyObj(object):
def save(self, filename):
with open(filename, "wb") as f:
f.write("sample text")
By patching the open
function inside the __builtin__
module to my mock_open()
, I can mock writing to a file without creating one.
Note: If you are using a module that uses cython, or your program depends on cython in any way, you will need to import cython's __builtin__
module by including import __builtin__
at the top of your file. You will not be able to mock the universal __builtin__
if you are using cython.
You can call view.setVisibility(View.GONE)
if you want to remove it from the layout.
Or view.setVisibility(View.INVISIBLE)
if you just want to hide it.
From Android Docs:
INVISIBLE
This view is invisible, but it still takes up space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.GONE
This view is invisible, and it doesn't take any space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.
Put very simple ::
is the scoping operator, .
is the access operator (I forget what the actual name is?), and ->
is the dereference arrow.
::
- Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static
function.
.
- This allows access to a member function on an already created object. For instance, Foo x; x.bar()
calls the method bar()
on instantiated object x
which has type Foo
. You can also use this to access public class variables.
->
- Essentially the same thing as .
except this works on pointer types. In essence it dereferences the pointer, than calls .
. Using this is equivalent to (*ptr).method()
If you don't have an insert key, and you're using Visual Studio 2019, then double-clicking the OVR text in the bottom right corner does not work. You'll have to use an on-screen keyboard, if you have one of those, or figure out what your insert key is mapped to. For me, on my mac keyboard hooked up to windows 10, it is the 0 key on the keypad.
df.insert(loc, column_name, value)
This will work if there is no other column with the same name. If a column, with your provided name already exists in the dataframe, it will raise a ValueError.
You can pass an optional parameter allow_duplicates
with True
value to create a new column with already existing column name.
Here is an example:
>>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
>>> df
b c
0 1 3
1 2 4
>>> df.insert(0, 'a', -1)
>>> df
a b c
0 -1 1 3
1 -1 2 4
>>> df.insert(0, 'a', -2)
Traceback (most recent call last):
File "", line 1, in
File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
raise ValueError(f"cannot insert {item}, already exists")
ValueError: cannot insert a, already exists
>>> df.insert(0, 'a', -2, allow_duplicates = True)
>>> df
a a b c
0 -2 -1 1 3
1 -2 -1 2 4
in bootstrap use .list-inline
css class
<ul class="list-inline">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h
If the modulus is a power of 2 then you can use a bitmask:
int i = -1 & ~-2; // -1 MOD 2 is 1
By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y
is x - (x DIV y) * y
where x DIV y
is TRUNC(x / y)
) and MOD requires a positive denominator and returns a positive result.
Had a similar problem to yours. What we had to do is use the document.domain solution found here:
Ways to circumvent the same-origin policy
We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:
You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:
.col {
padding-right:7px;
padding-left:7px;
}
Demo: http://bootply.com/93473
EDIT If you only want the spacing between columns you can select all cols except first and last like this..
.col:not(:first-child,:last-child) {
padding-right:7px;
padding-left:7px;
}
For Bootstrap 4 see: Remove gutter space for a specific div only
I'm assuming you figured this out already but:
Technical Reference for Log Files in Configuration Manager
That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs
AppEnforce.log
will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)
This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.
I agree with posters listing OpenOffice as a high-fidelity import/export facility of word / pdf docs with a Java API and it also works across platforms. OpenOffice import/export filters are pretty powerful and preserve most formatting during conversion to various formats including PDF. Docmosis and JODReports value-add to make life easier than learning the OpenOffice API directly which can be challenging because of the style of the UNO api and the crash-related bugs.
I'm not entirely sure what visual end result you're after, but here's an easy way to blur an image's edge: place a div with the image inside another div with the blurred image.
Working example here: http://jsfiddle.net/ZY5hn/1/
HTML:
<div class="placeholder">
<!-- blurred background image for blurred edge -->
<div class="bg-image-blur"></div>
<!-- same image, no blur -->
<div class="bg-image"></div>
<!-- content -->
<div class="content">Blurred Image Edges</div>
</div>
CSS:
.placeholder {
margin-right: auto;
margin-left:auto;
margin-top: 20px;
width: 200px;
height: 200px;
position: relative;
/* this is the only relevant part for the example */
}
/* both DIVs have the same image */
.bg-image-blur, .bg-image {
background-image: url('http://lorempixel.com/200/200/city/9');
position:absolute;
top:0;
left:0;
width: 100%;
height:100%;
}
/* blur the background, to make blurred edges that overflow the unblurred image that is on top */
.bg-image-blur {
-webkit-filter: blur(20px);
-moz-filter: blur(20px);
-o-filter: blur(20px);
-ms-filter: blur(20px);
filter: blur(20px);
}
/* I added this DIV in case you need to place content inside */
.content {
position: absolute;
top:0;
left:0;
width: 100%;
height: 100%;
color: #fff;
text-shadow: 0 0 3px #000;
text-align: center;
font-size: 30px;
}
Notice the blurred effect is using the image, so it changes with the image color.
I hope this helps.
Most of the time the value that we want to check is string or number, so here is function that i use:
const isNumber = (n: string | number): boolean =>
!isNaN(parseFloat(String(n))) && isFinite(Number(n));
const willBeTrue = [0.1, '1', '-1', 1, -1, 0, -0, '0', "-0", 2e2, 1e23, 1.1, -0.1, '0.1', '2e2', '1e23', '-0.1', ' 898', '080']
const willBeFalse = ['9BX46B6A', "+''", '', '-0,1', [], '123a', 'a', 'NaN', 1e10000, undefined, null, NaN, Infinity, () => {}]
One way to do that is to make all your users' devices subscribe to a topic. That way when you target a message to a specific topic, all devices will get it. I think this how the Notifications section in the Firebase console does it.
For Windows/WSL/Cygwin etc users:
Make sure that your line endings are standard Unix line feeds, i.e. \n
(LF) only.
Using Windows line endings \r\n
(CRLF) line endings will break the command line break.
This is because having \
at the end of a line with Windows line ending translates to
\
\r
\n
.
As Mark correctly explains above:
The line-continuation will fail if you have whitespace after the backslash and before the newline.
This includes not just space () or tabs (
\t
) but also the carriage return (\r
).
You can do it by putting your images on a fixed path (for example: /var/images, or c:\images), add a setting in your application settings (represented in my example by the Settings.class), and load them like that, in a HttpServlet
of yours:
String filename = Settings.getValue("images.path") + request.getParameter("imageName")
FileInputStream fis = new FileInputStream(filename);
int b = 0;
while ((b = fis.read()) != -1) {
response.getOutputStream().write(b);
}
Or if you want to manipulate the image:
String filename = Settings.getValue("images.path") + request.getParameter("imageName")
File imageFile = new File(filename);
BufferedImage image = ImageIO.read(imageFile);
ImageIO.write(image, "image/png", response.getOutputStream());
then the html code would be <img src="imageServlet?imageName=myimage.png" />
Of course you should think of serving different content types - "image/jpeg", for example based on the file extension. Also you should provide some caching.
In addition you could use this servlet for quality rescaling of your images, by providing width and height parameters as arguments, and using image.getScaledInstance(w, h, Image.SCALE_SMOOTH
), considering performance, of course.
pcolor()
with the vmin
, vmax
parameters.It is detailed in this answer: https://stackoverflow.com/a/3376734/21974
May help to someone:
I'm sending data from react
application to golang
server.
Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*")
. Error has fixed.
React form submit function:
async handleSubmit(e) {
e.preventDefault();
const headers = {
'Content-Type': 'text/plain'
};
await axios.post(
'http://localhost:3001/login',
{
user_name: this.state.user_name,
password: this.state.password,
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
Go server got Router,
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", Login.Login).Methods("POST")
log.Fatal(http.ListenAndServe(":3001", router))
}
Login.go,
func Login(w http.ResponseWriter, r *http.Request) {
var user = Models.User{}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
err := json.Unmarshal(data, &user)
if err == nil {
user = Postgres.GetUser(user.UserName, user.Password)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(user)
}
}
}
This is how you can change the color of Action Bar.
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
public class ActivityUtils {
public static void setActionBarColor(AppCompatActivity appCompatActivity, int colorId){
ActionBar actionBar = appCompatActivity.getSupportActionBar();
ColorDrawable colorDrawable = new ColorDrawable(getColor(appCompatActivity, colorId));
actionBar.setBackgroundDrawable(colorDrawable);
}
public static final int getColor(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 23) {
return ContextCompat.getColor(context, id);
} else {
return context.getResources().getColor(id);
}
}
}
From your MainActivity.java change the action bar color like this
ActivityUtils.setActionBarColor(this, R.color.green_00c1c1);
If you want to read multiple CSV files starting from line 2, this works like a charm
for files in csv_file_list:
with open(files, 'r') as r:
next(r) #skip headers
rr = csv.reader(r)
for row in rr:
#do something
(this is part of Parfait's answer to a different question)
If your input file is in.txt, you can use freopen to set stdin file as in.txt
freopen("in.txt","r",stdin);
if you want to do the same with your output:
freopen("out.txt","w",stdout);
this will work for std::cin (if using c++), printf, etc...
This will also help you in debugging your code in clion, vscode
Older IE and Firefox browsers attach the scrollbar to the documentElement
, or what would be the <html>
tag in HTML.
All other browsers attach the scrollbar to document.body
, or what would be the <body>
tag in HTML.
The correct solution would be to check which one to use, depending on browser
var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s = $(doc).scrollTop();
jQuery does make this a little easier, when passing in either window
or document
jQuery's scrollTop
does a similar check and figures it out, so either of these should work cross-browser
var s = $(document).scrollTop();
or
var s = $(window).scrollTop();
Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
...nothing that works for my div, just the full page
If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount
$('div').scrollTop();
If you need to get the elements distance from the top of the document, you can also do
$('div').offset().top
mylist = ['a', 'ab', 'abc']
assert 'ab' in mylist
Use the title
attribute while alt
is important for SEO stuff.
For posterity: Like AxeEffect said... if you have no typos check to see if you have ridiculous characters in your local branch name, like commas or apostrophes. Exactly that happened to me just now.
If you look at the chain of exceptions, the problem is
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property salt in class backend.Account
The problem is that the method Account.setSalt() works fine when you create an instance but not when you retrieve an instance from the database. This is because you don't want to create a new salt each time you load an Account.
To fix this, create a method setSalt(long) with visibility private and Hibernate will be able to set the value (just a note, I think it works with Private, but you might need to make it package or protected).
Leading from answers from @Bozho and @aioobe, lexicographic comparisons are similar to the ordering that one might find in a dictionary.
The Java String class provides the .compareTo ()
method in order to lexicographically compare Strings. It is used like this "apple".compareTo ("banana")
.
The return of this method is an int
which can be interpreted as follows:
compareTo
method is lexicographically first.More specifically, the method provides the first non-zero difference in ASCII values.
Thus "computer".compareTo ("comparison")
will return a value of (int) 'u' - (int) 'a'
(20). Since this is a positive result, the parameter ("comparison"
) is lexicographically first.
There is also a variant .compareToIgnoreCase ()
which will return 0
for "a".compareToIgnoreCase ("A");
for example.
This is full degree image rotation code. I recommend you to check the below example app in the jsfiddle.
https://jsfiddle.net/casamia743/xqh48gno/
The process flow of this example app is
function init() {
...
image.onload = function() {
app.boundaryRad = Math.atan(image.width / image.height);
}
...
}
/**
* NOTE : When source rect is rotated at some rad or degrees,
* it's original width and height is no longer usable in the rendered page.
* So, calculate projected rect size, that each edge are sum of the
* width projection and height projection of the original rect.
*/
function calcProjectedRectSizeOfRotatedRect(size, rad) {
const { width, height } = size;
const rectProjectedWidth = Math.abs(width * Math.cos(rad)) + Math.abs(height * Math.sin(rad));
const rectProjectedHeight = Math.abs(width * Math.sin(rad)) + Math.abs(height * Math.cos(rad));
return { width: rectProjectedWidth, height: rectProjectedHeight };
}
/**
* @callback rotatedImageCallback
* @param {DOMString} dataURL - return value of canvas.toDataURL()
*/
/**
* @param {HTMLImageElement} image
* @param {object} angle
* @property {number} angle.degree
* @property {number} angle.rad
* @param {rotatedImageCallback} cb
*
*/
function getRotatedImage(image, angle, cb) {
const canvas = document.createElement('canvas');
const { degree, rad: _rad } = angle;
const rad = _rad || degree * Math.PI / 180 || 0;
debug('rad', rad);
const { width, height } = calcProjectedRectSizeOfRotatedRect(
{ width: image.width, height: image.height }, rad
);
debug('image size', image.width, image.height);
debug('projected size', width, height);
canvas.width = Math.ceil(width);
canvas.height = Math.ceil(height);
const ctx = canvas.getContext('2d');
ctx.save();
const sin_Height = image.height * Math.abs(Math.sin(rad))
const cos_Height = image.height * Math.abs(Math.cos(rad))
const cos_Width = image.width * Math.abs(Math.cos(rad))
const sin_Width = image.width * Math.abs(Math.sin(rad))
debug('sin_Height, cos_Width', sin_Height, cos_Width);
debug('cos_Height, sin_Width', cos_Height, sin_Width);
let xOrigin, yOrigin;
if (rad < app.boundaryRad) {
debug('case1');
xOrigin = Math.min(sin_Height, cos_Width);
yOrigin = 0;
} else if (rad < Math.PI / 2) {
debug('case2');
xOrigin = Math.max(sin_Height, cos_Width);
yOrigin = 0;
} else if (rad < Math.PI / 2 + app.boundaryRad) {
debug('case3');
xOrigin = width;
yOrigin = Math.min(cos_Height, sin_Width);
} else if (rad < Math.PI) {
debug('case4');
xOrigin = width;
yOrigin = Math.max(cos_Height, sin_Width);
} else if (rad < Math.PI + app.boundaryRad) {
debug('case5');
xOrigin = Math.max(sin_Height, cos_Width);
yOrigin = height;
} else if (rad < Math.PI / 2 * 3) {
debug('case6');
xOrigin = Math.min(sin_Height, cos_Width);
yOrigin = height;
} else if (rad < Math.PI / 2 * 3 + app.boundaryRad) {
debug('case7');
xOrigin = 0;
yOrigin = Math.max(cos_Height, sin_Width);
} else if (rad < Math.PI * 2) {
debug('case8');
xOrigin = 0;
yOrigin = Math.min(cos_Height, sin_Width);
}
debug('xOrigin, yOrigin', xOrigin, yOrigin)
ctx.translate(xOrigin, yOrigin)
ctx.rotate(rad);
ctx.drawImage(image, 0, 0);
if (DEBUG) drawMarker(ctx, 'red');
ctx.restore();
const dataURL = canvas.toDataURL('image/jpg');
cb(dataURL);
}
function render() {
getRotatedImage(app.image, {degree: app.degree}, renderResultImage)
}
A SOAP request is an XML file consisting of the parameters you are sending to the server.
The SOAP response is equally an XML file, but now with everything the service wants to give you.
Basically the WSDL is a XML file that explains the structure of those two XML.
To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
http://www.webservicex.net/uszip.asmx?op=GetInfoByCity
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
String soapAction = "http://www.webserviceX.NET/GetInfoByCity";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "http://www.webserviceX.NET";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:GetInfoByCity>
<myNamespace:USCity>New York</myNamespace:USCity>
</myNamespace:GetInfoByCity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
soapBodyElem1.addTextNode("New York");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
This problem happens as a result of calling a method without brackets. Take a look at the example below:
class SomeClass(object):
def __init__(self):
print 'I am starting'
def some_meth(self):
print 'I am a method()'
x = SomeClass()
''' Not adding the bracket after the method call would result in method bound error '''
print x.some_meth
''' However this is how it should be called and it does solve it '''
x.some_meth()
This is a good way of counting entries within .pivot_table
:
df2.pivot_table(values='X', index=['Y','Z'], columns='X', aggfunc='count')
X1 X2
Y Z
Y1 Z1 1 1
Z2 1 NaN
Y2 Z3 1 NaN
Does git log --oneline
do what you want?
If you need good, easy GIT server than you must try GitBlit. Also i use gitolite but it only server, with GitBlit you get all in one, server, admin, repos. manager ... URL: http://gitblit.com/
this.props.children
should either be a ReactElement or an array of ReactElement, but not components.
To get the DOM nodes of the children elements, you need to clone them and assign them a new ref.
render() {
return (
<div>
{React.Children.map(this.props.children, (element, idx) => {
return React.cloneElement(element, { ref: idx });
})}
</div>
);
}
You can then access the child components via this.refs[childIdx]
, and retrieve their DOM nodes via ReactDOM.findDOMNode(this.refs[childIdx])
.
I have found a solution. It is just a workaround to my problem but currently the only solution.
ViewPager PagerAdapter not updating the View
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Does anyone know whether this is a bug or not?
Follow this pattern if you browsing for image files:
dialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
Hi the problem is in FileDownloader class
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.
Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)
Attaching the working code with screenshots.
MainActivity.java
package com.example.downloadread;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
FileDownloader.java
package com.example.downloadread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadread"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.downloadread.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
The SignTool is available as part of the Windows SDK (which comes with Visual Studio Community 2015). Make sure to select the "ClickOnce Publishing Tools" from the feature list during the installation of Visual Studio 2015 to get the SignTool.
Once Visual Studio is installed you can run the signtool
command from the Visual Studio Command Prompt. By default (on Windows 10) the SignTool will be installed at C:\Program Files (x86)\Windows Kits\10\bin\x86\signtool.exe
.
ClickOnce Publishing Tools Installation:
SignTool Location:
SEARCH
does not return 0
if there is no match, it returns #VALUE!
. So you have to wrap calls to SEARCH
with IFERROR
.
For example...
=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")
or
=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))
Here, IFERROR
returns the value from SEARCH
when it works; the given value of 0
otherwise.
You are calling a non-static method :
public function foobarfunc() {
return $this->foo();
}
Using a static-call :
foobar::foobarfunc();
When using a static-call, the function will be called (even if not declared as static
), but, as there is no instance of an object, there is no $this
.
So :
Here, the methods of your class are using the current instance of the class, as they need to access the $foo
property of the class.
This means your methods need an instance of the class -- which means they cannot be static.
This means you shouldn't use static calls : you should instanciate the class, and use the object to call the methods, like you did in your last portion of code :
$foobar = new foobar();
$foobar->foobarfunc();
For more informations, don't hesitate to read, in the PHP manual :
Also note that you probably don't need this line in your __construct
method :
global $foo;
Using the global
keyword will make the $foo
variable, declared outside of all functions and classes, visibile from inside that method... And you probably don't have such a $foo
variable.
To access the $foo
class-property, you only need to use $this->foo
, like you did.
In an ASP.Net 5 project this can now be set for each launch profile.
Open the file launchsettings.json under the Startup Project Properties folder and add "launchBrowser": false
to the profile you are configuring, such as in:
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": false,
"environmentVariables": {
"Hosting:Environment": "Development"
}
}
}
In the START menu type "regedit" to open the Registry editor
Go to "HKEY_LOCAL_MACHINE" on the left-hand side registry explorer/tree menu
Click "SOFTWARE" within the "HKEY_LOCAL_MACHINE" registries
Click "JavaSoft" within the "SOFTWARE" registries
Click "Java Runtime Environment" within the "JavaSoft" list of registries here you can see different versions of installed java
Click "Java Runtime Environment"- On right hand side you will get 4-5 rows . Please select "CurrentVersion" and right Click( select modify option) Change version to "1.7"
Now the magic has been completed
Simply put, you need to rewrite all of your database connections and queries.
You are using mysql_*
functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.
A basic example of using PDO (without error handling):
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>
A basic example of using MySQLi (without error handling):
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.
some times the solution up doesn't work so you d have properly to remove the in class and add the css display:none manually .
$("#modal").removeClass("in");
$("#modal").css("display","none");
In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n
to pre-allocate the length you want.
Slides available as PPT or via Google
The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
AffineTransformOp
offers the additional flexibility of choosing the interpolation type.
BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
AffineTransformOp scaleOp =
new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);
The fragment shown illustrates resampling, not cropping; this related answer addresses the issue; some related examples are examined here.
Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.
However, if you want to stick to the standard, you can write something like this:
#include <stdio.h>
#include <stdlib.h>
FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); /* same as rewind(f); */
char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);
string[fsize] = 0;
Here string
will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)
If you are looking for a very extensible option or have a specific problem domain you could consider rolling your own using the Java Object Oriented Neural Engine. Another JOONE reference.
I used it successfully in a personal project to identify the letter from an image such as this, you can find all the source for the OCR component of my application on github, here.
FileInputStream fis = new FileInputStream(new File("C:/Test.xlsx"));
//create workbook instance
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrieve the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//to evaluate cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for(Row row : sheet)
{
for(Cell cell : row)
{
switch(formulaEvaluator.evaluateInCell(cell).getCellTypeEnum())
{
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
default:
break;
}
}
System.out.println();
}
This code will work fine. Use getCellTypeEnum()
and to compare use just NUMERIC
or STRING
.
You have two solutions for your problem. The quick one is to lower targetApi to 22 (build.gradle file). Second is to use new and wonderful ask-for-permission model:
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
Sniplet found here: https://developer.android.com/training/permissions/requesting.html
Solutions 2: If it does not work try this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION);
return;
}
and then in callback
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
} else {
// User refused to grant permission.
}
}
}
that is from comments. thanks
It's extremely unlikely that an if/else or a switch is going to be the source of your performance woes. If you're having performance problems, you should do a performance profiling analysis first to determine where the slow spots are. Premature optimization is the root of all evil!
Nevertheless, it's possible to talk about the relative performance of switch vs. if/else with the Java compiler optimizations. First note that in Java, switch statements operate on a very limited domain -- integers. In general, you can view a switch statement as follows:
switch (<condition>) {
case c_0: ...
case c_1: ...
...
case c_n: ...
default: ...
}
where c_0
, c_1
, ..., and c_N
are integral numbers that are targets of the switch statement, and <condition>
must resolve to an integer expression.
If this set is "dense" -- that is, (max(ci) + 1 - min(ci)) / n > α, where 0 < k < α < 1, where k
is larger than some empirical value, a jump table can be generated, which is highly efficient.
If this set is not very dense, but n >= β, a binary search tree can find the target in O(2 * log(n)) which is still efficient too.
For all other cases, a switch statement is exactly as efficient as the equivalent series of if/else statements. The precise values of α and β depend on a number of factors and are determined by the compiler's code-optimization module.
Finally, of course, if the domain of <condition>
is not the integers, a switch
statement is completely useless.
calculate workdays between two dates including holidays and custom workweek
The answer is not that trivial - thus my suggestion would be to use a class where you can configure more than relying on simplistic function (or assuming a fixed locale and culture). To get the date after a certain number of workdays you'll:
Functional Approach
/**
* @param days, int
* @param $format, string: dateformat (if format defined OTHERWISE int: timestamp)
* @param start, int: timestamp (mktime) default: time() //now
* @param $wk, bit[]: flags for each workday (0=SUN, 6=SAT) 1=workday, 0=day off
* @param $holiday, string[]: list of dates, YYYY-MM-DD, MM-DD
*/
function working_days($days, $format='', $start=null, $week=[0,1,1,1,1,1,0], $holiday=[])
{
if(is_null($start)) $start = time();
if($days <= 0) return $start;
if(count($week) != 7) trigger_error('workweek must contain bit-flags for 7 days');
if(array_sum($week) == 0) trigger_error('workweek must contain at least one workday');
$wd = date('w', $start);//0=sun, 6=sat
$time = $start;
while($days)
{
if(
$week[$wd]
&& !in_array(date('Y-m-d', $time), $holiday)
&& !in_array(date('m-d', $time), $holiday)
) --$days; //decrement on workdays
$wd = date('w', $time += 86400); //add one day in seconds
}
$time -= 86400;//include today
return $format ? date($format, $time): $time;
}
//simple usage
$ten_days = working_days(10, 'D F d Y');
echo '<br>ten workingdays (MON-FRI) disregarding holidays: ',$ten_days;
//work on saturdays and add new years day as holiday
$ten_days = working_days(10, 'D F d Y', null, [0,1,1,1,1,1,1], ['01-01']);
echo '<br>ten workingdays (MON-SAT) disregarding holidays: ',$ten_days;
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist",
"sourceMap": true,
"declaration": false,
"module": "esnext",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": ["node_modules/@types"],
"lib": ["es2018", "dom"]
}
}
GRV.DataSource = Class1.DataTable;
GRV.DataBind();
Class1.GRV.Rows[e.RowIndex].Delete();
GRV.DataSource = Class1.DataTable;
GRV.DataBind();
Try using p:ajax with event attribute,
I've added yet another JavaScript serializer repo to GitHub.
Rather than take the approach of serializing and deserializing JavaScript objects to an internal format the approach here is to serialize JavaScript objects out to native JavaScript. This has the advantage that the format is totally agnostic from the serializer, and the object can be recreated simply by calling eval().
$array = range('a', 'z');
I ran a quick benchmark comparing the two base
approaches and it turns out that x[!is.na(x)]
is faster than na.omit
. User qwr
suggested I try purrr::dicard
also - this turned out to be massively slower (though I'll happily take comments on my implementation & test!)
microbenchmark::microbenchmark(
purrr::map(airquality,function(x) {x[!is.na(x)]}),
purrr::map(airquality,na.omit),
purrr::map(airquality, ~purrr::discard(.x, .p = is.na)),
times = 1e6)
Unit: microseconds
expr min lq mean median uq max neval cld
purrr::map(airquality, function(x) { x[!is.na(x)] }) 66.8 75.9 130.5643 86.2 131.80 541125.5 1e+06 a
purrr::map(airquality, na.omit) 95.7 107.4 185.5108 129.3 190.50 534795.5 1e+06 b
purrr::map(airquality, ~purrr::discard(.x, .p = is.na)) 3391.7 3648.6 5615.8965 4079.7 6486.45 1121975.4 1e+06 c
For reference, here's the original test of x[!is.na(x)]
vs na.omit
:
microbenchmark::microbenchmark(
purrr::map(airquality,function(x) {x[!is.na(x)]}),
purrr::map(airquality,na.omit),
times = 1000000)
Unit: microseconds
expr min lq mean median uq max neval cld
map(airquality, function(x) { x[!is.na(x)] }) 53.0 56.6 86.48231 58.1 64.8 414195.2 1e+06 a
map(airquality, na.omit) 85.3 90.4 134.49964 92.5 104.9 348352.8 1e+06 b
An abstract Interface is not as redundant as everyone seems to be saying, in theory at least.
An Interface can be extended, just as a Class can. If you design an Interface hierarchy for your application you may well have a 'Base' Interface, you extend other Interfaces from but do not want as an Object in itself.
Example:
public abstract interface MyBaseInterface {
public String getName();
}
public interface MyBoat extends MyBaseInterface {
public String getMastSize();
}
public interface MyDog extends MyBaseInterface {
public long tinsOfFoodPerDay();
}
You do not want a Class to implement the MyBaseInterface, only the other two, MMyDog and MyBoat, but both interfaces share the MyBaseInterface interface, so have a 'name' property.
I know its kinda academic, but I thought some might find it interesting. :-)
It is really just a 'marker' in this case, to signal to implementors of the interface it wasn't designed to be implemented on its own. I should point out a compiler (At least the sun/ora 1.6 I tried it with) compiles a class that implements an abstract interface.
In your case use data==null
(which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)
function test(data) {_x000D_
if (data != null) {_x000D_
console.log('Data: ', data);_x000D_
}_x000D_
}_x000D_
_x000D_
test(); // the data=undefined_x000D_
test(null); // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
_x000D_
test(0); _x000D_
test(false); _x000D_
test('something');
_x000D_
Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
Use
print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
like this:
>>> my_string = "deadbeef"
>>> print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
0xde 0xad 0xbe 0xef
>>>
On an unrelated side note ... using string
as a variable name even as an example variable name is very bad practice.
d5d "cuts" five lines
I usually just throw the number in the middle like:
d7l = delete 7 letters
This Works For me !!!
Call a Function without Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers();
});
Call a Function with Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers($(e1.target).val());
});
Create the below function
Alter FUNCTION InitialCap(@String VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @Position INT;
SELECT @String = STUFF(LOWER(@String),1,1,UPPER(LEFT(@String,1))) COLLATE Latin1_General_Bin,
@Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);
WHILE @Position > 0
SELECT @String = STUFF(@String,@Position,2,UPPER(SUBSTRING(@String,@Position,2))) COLLATE Latin1_General_Bin,
@Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);
RETURN @String;
END ;
Then call it like
select dbo.InitialCap(columnname) from yourtable
I haven't seen the Gas assembler specifically, but in general the stack is "implemented" by maintaining a reference to the location in memory where the top of the stack resides. The memory location is stored in a register, which has different names for different architectures, but can be thought of as the stack pointer register.
The pop and push commands are implemented in most architectures for you by building upon micro instructions. However, some "Educational Architectures" require you implement them your self. Functionally, push would be implemented somewhat like this:
load the address in the stack pointer register to a gen. purpose register x
store data y at the location x
increment stack pointer register by size of y
Also, some architectures store the last used memory address as the Stack Pointer. Some store the next available address.
For me this works well with IE10, Chrome, Firefox and Safari:
#MyDiv>*
{
zoom: 50%;
-moz-transform: scale(0.5);
-webkit-transform: scale(1.0);
}
This zooms all content in to 50%.