Ensure you have included the different abiFilters, this enables Gradle know what ABI libraries to package into your apk.
defaultConfig {
ndk {
abiFilters "armeabi-v7a", "x86", "armeabi", "mips"
}
}
If you storing your jni libs in a different directory, or also using externally linked jni libs, Include them on the different source sets of the app.
sourceSets {
main {
jni.srcDirs = ['src/main/jniLibs']
jniLibs.srcDir 'src/main/jniLibs'
}
}
You have to sink "output" and "message" separately (the sink
function only looks at the first element of type
)
Now if you want the input to be logged too, then put it in a script:
script.R
1:5 + 1:3 # prints and gives a warning
stop("foo") # an error
And at the prompt:
con <- file("test.log")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")
# This will echo all input and not truncate 150+ character lines...
source("script.R", echo=TRUE, max.deparse.length=10000)
# Restore output to console
sink()
sink(type="message")
# And look at the log...
cat(readLines("test.log"), sep="\n")
I think you are using the machine-name instead of the ip of the host.
I got the same error when i tried with machine's name. Because, It is allowed only when both the client and host are under same network and they have the same Operating system installed.
Simple ways to check an empty dict are below:
a= {}
1. if a == {}:
print ('empty dict')
2. if not a:
print ('empty dict')
Although method 1st is more strict as when a = None, method 1 will provide correct result but method 2 will give an incorrect result.
Bottom right hand corner on the status bar, click Spaces: N
(or Tab Width: N
, where N is an integer), ensure it says Tab Width: 4
for converting from four spaces, and then select Convert Indentation to Tabs
from the contextual menu that will appear from the initial click.
Similarly, if you want to do the opposite, click the Spaces
or Tab Width
text on the status bar and select from the same menu.
When the servlet container (like Apache Tomcat) starts up, it will read from the web.xml file (only one per application) if anything goes wrong or shows up an error at container side console, otherwise, it will deploy and load all web applications by using web.xml (so named it as deployment descriptor).
During instantiation phase of the servlet, servlet instance is ready but it cannot serve the client request because it is missing with two pieces of information:
1: context information
2: initial configuration information
Servlet engine creates servletConfig interface object encapsulating the above missing information into it servlet engine calls init() of the servlet by supplying servletConfig object references as an argument. Once init() is completely executed servlet is ready to serve the client request.
A)only once (for every client request a new thread is created) only one instance of the servlet serves any number of the client request ie, after serving one client request server does not die. It waits for other client requests ie what CGI (for every client request a new process is created) limitation is overcome with the servlet (internally servlet engine creates the thread).
A)whenever getSession() is called on HttpServletRequest object
Step 1: request object is evaluated for incoming session ID.
Step 2: if ID not available a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to the servlet (doGet/doPost).
Step 3: if ID available brand new session object is not created session ID is picked up from the request object search is made in the collection of sessions by using session ID as the key.
Once the search is successful session ID is stored into HttpServletResponse and the existing session object references are returned to the doGet() or doPost() of UserDefineservlet.
1)when control leaves from servlet code to client don't forget that session object is being held by servlet container ie, the servlet engine
2)multithreading is left to servlet developers people for implementing ie., handle the multiple requests of client nothing to bother about multithread code
A servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting) when the servlet is instantiated, the init() method of the servlet is called then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet when the application is undeployed (the servlet container stops), the destroy() method is called.
(Assuming you are looking at the reports in the Crystal Report Designer...)
Your menu options might be a little different depending on the version of Crystal Reports you're using, but you can either:
Here is how I would write a validator for MaxValue
public class MaxValueAttribute : ValidationAttribute
{
private readonly int _maxValue;
public MaxValueAttribute(int maxValue)
{
_maxValue = maxValue;
}
public override bool IsValid(object value)
{
return (int) value <= _maxValue;
}
}
The MinValue Attribute should be fairly the same
The Best way is do not use any pairing code.
Instead of onClick
go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.
or see this link for better understanding
Below is code for the same:
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
// **add this 2 line code**
Intent myIntent = new Intent(view.getContext(), Connect.class);
startActivityForResult(myIntent, 0);
finish();
}
};
Connect.java file is :
public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
private InputStream in;
byte[] arrayOfByte = new byte[4096];
int bytes;
public BluetoothDevice mDevice;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
try {
setup();
} catch (ZeoMessageException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ZeoMessageParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setup() throws ZeoMessageException, ZeoMessageParseException {
// TODO Auto-generated method stub
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("**:**:**:**:**:**");// add device mac adress
try {
sock = zee.createRfcommSocketToServiceRecord(
UUID.fromString("*******************")); // use unique UUID
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connecting");
try {
sock.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connected");
try {
in = sock.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Listening...");
while (true) {
try {
bytes = in.read(arrayOfByte);
Log.d(TAG, "++++ Read "+ bytes +" bytes");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Done: test()");
}}
private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
public static class LogBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
Log.d("ZeoReceiver", paramAnonymousIntent.toString());
Bundle extras = paramAnonymousIntent.getExtras();
for (String k : extras.keySet()) {
Log.d("ZeoReceiver", " Extra: "+ extras.get(k).toString());
}
}
};
private BluetoothSocket sock;
@Override
public void onDestroy() {
getApplicationContext().unregisterReceiver(receiver);
if (sock != null) {
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
}
In my case, the problem was more severe: turns out asp.net was not correctly registered.
simply ran the following command at the command prompt
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
If I had been on a 32 bit system, it would have looked like the following:
%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i
I ran into a same problem. I was running portable version of android studio so downloaded a package from https://developer.android.com/studio/#downloads and installed it, and like that, done!
As MDN Window.history() describes :
For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.
For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.
There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.
So there is no Javascript method to clear the session history, instead, if you want to block navigating back to a certain page, you can use the location.replace() method, and pass the page link as parameter, which will not push the page to the browser's session history list. For example, there are three pages:
a.html:
<!doctype html>
<html>
<head>
<title>a.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">a.html</code> page ! Go to <a href="b.html">b.html</a> page !</p>
</body>
</html>
b.html:
<!doctype html>
<html>
<head>
<title>b.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">b.html</code> page ! Go to <a id="jumper" href="c.html">c.html</a> page !</p>
<script type="text/javascript">
var jumper = document.getElementById("jumper");
jumper.onclick = function(event) {
var e = event || window.event ;
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = true ;
}
location.replace(this.href);
jumper = null;
}
</script>
</body>
c.html:
<!doctype html>
<html>
<head>
<title>c.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">c.html</code> page</p>
</body>
</html>
With href link, we can navigate from a.html to b.html to c.html. In b.html, we use the location.replace(c.html)
method to navigate from b.html to c.html. Finally, we go to c.html*, and if we click the back button in the browser, we will jump to **a.html.
So this is it! Hope it helps.
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
Set is another way we can solve this
a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}
As @kirbyfan64sos notes in a comment, /home
is NOT your home directory (a.k.a. home folder):
The fact that /home
is an absolute, literal path that has no user-specific component provides a clue.
While /home
happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users
.
What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:
cd
with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
cd # changes to home dir; e.g., '/home/jdoe'
~
by itself / unquoted ~/
at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash
)
echo ~ # outputs, e.g., '/home/jdoe'
$HOME
- as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME
is a predefined, user-specific environment variable:
cd "$HOME/tmp" # changes to your personal folder for temp. files
Thus, to create the desired folder, you could use:
mkdir "$HOME/bin" # same as: mkdir ~/bin
Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied
error.
While pip install might work. Please check the project structure and see if there is no virtual environment already (It is a good practice to have one) created in the project. If there is, activate it with source <name_of_virtual_env>/bin/activate
(for MacOS) and venv\Scripts\Activate.ps1
(for Windows powershell) or venv\Scripts\activate.bat
(for Windows cmd). then pip install selenium into the environment.
If it isn't,
check if you have a virtual environment with virtualenv --version
If it displays an error, install it with pip install virtualenv
then create a virtual environment with
virtualenv <name_of_virtual_env>
(Both Windows and MacOS)or
python -m venv <name_of_virtual_env>
(Windows Only)
then activate the virtual environment
with
source <name_of_virtual_env>/bin/activate
(for MacOS) and
venv\Scripts\Activate.ps1
(for Windows powershell) or
venv\Scripts\activate.bat
(for Windows cmd).
then install selenium with pip install -U selenium (it will install the latest version).
If it doesn't display an error, just create a virtual environment in the project, activate it and install selenium inside of it.
You need to define MyMessageBox before User -- because User include object of MyMessageBox by value (and so compiler should know its size).
Also you'll need to forward declare User befor MyMessageBox -- because MyMessageBox include member of User* type.
I was running into the exact same problem that Saurav described, but I really needed to find a solution that did not require anything other than Route 53 and S3. I created a how-to guide for my blog detailing what I did.
Here is what I came up with.
Using only the tools available in Amazon S3 and Amazon Route 53, create a URL Redirect that automatically forwards http://url-redirect-example.vivekmchawla.com to the AWS Console sign-in page aliased to "MyAccount", located at https://myaccount.signin.aws.amazon.com/console/ .
This guide will teach you set up URL forwarding to any URL, not just ones from Amazon. You will learn how to set up forwarding to specific folders (like "/console" in my example), and how to change the protocol of the redirect from HTTP to HTTPS (or vice versa).
Open the S3 management console and click "Create Bucket".
Choose a Bucket Name. This step is really important! You must name the bucket EXACTLY the same as the URL you want to set up for forwarding. For this guide, I'll use the name "url-redirect-example.vivekmchawla.com".
Select whatever region works best for you. If you don't know, keep the default.
Don't worry about setting up logging. Just click the "Create" button when you're ready.
Paste the following XML snippet in it's entirety.
<RoutingRules>
<RoutingRule>
<Redirect>
<Protocol>https</Protocol>
<HostName>myaccount.signin.aws.amazon.com</HostName>
<ReplaceKeyPrefixWith>console/</ReplaceKeyPrefixWith>
<HttpRedirectCode>301</HttpRedirectCode>
</Redirect>
</RoutingRule>
</RoutingRules>
If you're curious about what the above XML is doing, visit the AWM Documentation for "Syntax for Specifying Routing Rules". A bonus technique (not covered here) is forwarding to specific pages at the destination host, for example http://redirect-destination.com/console/special-page.html
. Read about the <ReplaceKeyWith>
element if you need this functionality.
Make note of the Static Website Hosting "endpoint" that Amazon automatically created for this bucket. You'll need this for later, so highlight the entire URL, then copy and paste it to notepad.
CAUTION! At this point you can actually click this link to check to see if your Redirection Rules were entered correctly, but be careful! Here's why...
Let's say you entered the wrong value inside the <Hostname>
tags in your Redirection Rules. Maybe you accidentally typed myaccount.amazon.com
, instead of myaccount.signin.aws.amazon.com
. If you click the link to test the Endpoint URL, AWS will happily redirect your browser to the wrong address!
After noticing your mistake, you will probably edit the <Hostname>
in your Redirection Rules to fix the error. Unfortunately, when you try to click the link again, you'll most likely end up being redirected back to the wrong address! Even though you fixed the <Hostname>
entry, your browser is caching the previous (incorrect!) entry. This happens because we're using an HTTP 301 (permanent) redirect, which browsers like Chrome and Firefox will cache by default.
If you copy and paste the Endpoint URL to a different browser (or clear the cache in your current one), you'll get another chance to see if your updated <Hostname>
entry is finally the correct one.
To be safe, if you want to test your Endpoint URL and Redirect Rules, you should open a private browsing session, like "Incognito Mode" in Chrome. Copy, paste, and test the Endpoint URL in Incognito Mode and anything cached will go away once you close the session.
Clicking "Create Record Set" will open up the Create Record Set window on the right side of the Route53 Management Console.
In the Name field, enter the hostname portion of the URL that you used when naming your S3 bucket. The "hostname portion" of the URL is everything to the LEFT of your Hosted Zone's name. I named my S3 bucket "url-redirect-example.vivekmchawla.com", and my Hosted Zone is "vivekmchawla.com", so the hostname portion I need to enter is "url-redirect-example".
Select "CNAME - Canonical name" for the Type of this Record Set.
For the Value, paste in the Endpoint URL of the S3 bucket we created back in Step 3.
Click the "Create Record Set" button. Assuming there are no errors, you'll now be able to see a new CNAME record in your Hosted Zone's list of Record Sets.
Open up a new browser tab and type in the URL that we just set up. For me, that's http://url-redirect-example.vivekmchawla.com. If everything worked right, you should be sent directly to an AWS sign-in page.
Because we used the myaccount.signin.aws.amazon.com
alias as our redirect's destination URL, Amazon knows exactly which account we're trying to access, and takes us directly there. This can be very handy if you want to give a short, clean, branded AWS login link to employees or contractors.
I personally love the various AWS services, but if you've decided to migrate DNS management to Amazon Route 53, the lack of easy URL forwarding can be frustrating. I hope this guide helped make setting up URL forwarding for your Hosted Zones a bit easier.
If you'd like to learn more, please take a look at the following pages from the AWS Documentation site.
Cheers!
Try it, it will work for any number of substrings
<?php
$string = 'bcadef abcdef';
$substr = 'a';
$attachment = '+++';
//$position = strpos($string, 'a');
$newstring = str_replace($substr, $substr.$attachment, $string);
// bca+++def a+++bcdef
?>
If it supports standard regex...
find:
^.*#RedirectMatch Permanent.*$
replace:
Replace with nothing.
You don't have to simulate it. The second argument to res.send
I believe is the status code. Just pass 404 to that argument.
Let me clarify that: Per the documentation on expressjs.org it seems as though any number passed to res.send()
will be interpreted as the status code. So technically you could get away with:
res.send(404);
Edit: My bad, I meant res
instead of req
. It should be called on the response
Edit: As of Express 4, the send(status)
method has been deprecated. If you're using Express 4 or later, use: res.sendStatus(404)
instead. (Thanks @badcc for the tip in the comments)
I got the same issue and after a lot of time spent on the search I found the solution
Just change your method especially // DownloadsProvider part
getpath()
to
@SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// This is for checking Main Memory
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return Environment.getExternalStorageDirectory() + "/";
}
// This is for checking SD Card
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
String fileName = getFilePath(context, uri);
if (fileName != null) {
return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
}
String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
id = id.replaceFirst("raw:", "");
File file = new File(id);
if (file.exists())
return id;
}
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
For more solution click on the link here
https://gist.github.com/HBiSoft/15899990b8cd0723c3a894c1636550a8
I hope will do the same for you!
Guava also provides such function which will return an Optional
if an enum cannot be found.
Enums.getIfPresent(MyEnum.class, id).toJavaUtil()
.orElseThrow(()-> new RuntimeException("Invalid enum blah blah blah.....")))
-SurfacePro3-
It's kind of offtopic, but i come here from googling the same error. For me this error appeared when i was selecting datetime field from mssql database and than using it later in php-script. like this:
$SQL="SELECT Created
FROM test_table";
$stmt = sqlsrv_query($con, $SQL);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$Row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC);
$SQL="INSERT INTO another_test_table (datetime_field) VALUES ('".$Row['Created']."')";
$stmt = sqlsrv_query($con, $SQL);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
the INSERT statement was giving error: Object of class DateTime could not be converted to string
I realized that you CAN'T just select the datetime from database:
SELECT Created FROM test_table
BUT you have to use CONVERT for this field:
SELECT CONVERT(varchar(24),Created) as Created FROM test_table
There's little need to set all the variables you're setting. CMake sets them to reasonable defaults. You should definitely not modify CMAKE_BINARY_DIR
or CMAKE_CACHEFILE_DIR
. Treat these as read-only.
First remove the existing problematic cache file from the src directory:
cd src
rm CMakeCache.txt
cd ..
Then remove all the set()
commands and do:
cd Compile && rm -rf *
cmake ../src
As long as you're outside of the source directory when running CMake, it will not modify the source directory unless your CMakeList explicitly tells it to do so.
Once you have this working, you can look at where CMake puts things by default, and only if you're not satisfied with the default locations (such as the default value of EXECUTABLE_OUTPUT_PATH
), modify only those you need. And try to express them relative to CMAKE_BINARY_DIR
, CMAKE_CURRENT_BINARY_DIR
, PROJECT_BINARY_DIR
etc.
If you look at CMake documentation, you'll see variables partitioned into semantic sections. Except for very special circumstances, you should treat all those listed under "Variables that Provide Information" as read-only inside CMakeLists.
It is in the dist folder inside of the project, but only if "Compress WAR File" in the project settings dialog ( build / packaging) ist checked. Before I checked this checkbox there was no dist folder.
I think your document must be having enough space in the window to display its contents. That means there is no need to scroll down to see any more part of the document. In that case, document height would be equal to the window height.
Some people may find an async
example useful:
var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited
json()
converts the response's body from a ReadableStream
to a json object.
The await
statements must be wrapped in an async
function, however you can run await
statements directly in the console of Chrome (as of version 62).
This also works
SELECT *
FROM tableB
WHERE ID NOT IN (
SELECT ID FROM tableA
);
First, you should install "platformio-ide-terminal": Open "Preferences ?," >> Click "+ Install" >> In "Search packages" type "platformio-ide-terminal" >> Click "Install".
And answering exactly the question. If you have previously installed, just use:
ctrl-`
or Option+Command+T (??T)$data_arr = array('hello', 'developer', 'laravel' );
// We Have to remove Value "hello" from the array
// Check if the value is exists in the array
if (array_search('hello', $data_arr ) !== false) {
$key = array_search('hello', $data_arr );
unset( $data_arr[$key] );
}
# output:
// It will Return unsorted Indexed array
print( $data_arr )
// To Sort Array index use this
$data_arr = array_values( $data_arr );
// Now the array key is sorted
Latest findings...
https://gist.github.com/luislavena/f064211759ee0f806c88
Most importantly...download https://raw.githubusercontent.com/rubygems/rubygems/master/lib/rubygems/ssl_certs/rubygems.org/AddTrustExternalCARoot-2048.pem
Figure out where to stick it
C:\>gem which rubygems
C:/Ruby21/lib/ruby/2.1.0/rubygems.rb
Then just copy the .pem file in ../2.1.0/rubygems/ssl_certs/ and go on about your business.
That is the textarea
's job - for multiline text input. The input
won't do it; it wasn't designed to do it.
So use a textarea
. Besides their visual differences, they are accessed via JavaScript the same way (use value
property).
You can prevent newlines being entered via the input
event and simply using a replace(/\n/g, '')
.
Just to clarify things, you don't/can't "execute it within the HTML body".
You can modify the contents of the HTML using javascript.
You decide at what point you want the javascript to be executed.
For example, here is the contents of a html file, including javascript, that does what you want.
<html>
<head>
<script>
// The next line document.addEventListener....
// tells the browser to execute the javascript in the function after
// the DOMContentLoaded event is complete, i.e. the browser has
// finished loading the full webpage
document.addEventListener("DOMContentLoaded", function(event) {
var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below $500.00" ];
var col2 = ["None", "None", "$8.00"];
var TheInnerHTML ="";
for (var j = 0; j < col1.length; j++) {
TheInnerHTML += "<tr><td>"+col1[j]+"</td><td>"+col2[j]+"</td></tr>";
}
document.getElementById("TheBody").innerHTML = TheInnerHTML;});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Balance</th>
<th>Fee</th>
</tr>
</thead>
<tbody id="TheBody">
</tbody>
</table>
</body>
Enjoy !
You need install pysocks , my version is 1.0 and the code works for me:
import socket
import socks
import requests
ip='localhost' # change your proxy's ip
port = 0000 # change your proxy's port
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, port)
socket.socket = socks.socksocket
url = u'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=inurl%E8%A2%8B'
print(requests.get(url).text)
You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));
Element root = document.getDocumentElement();
for (Server newServer : Collection<Server> bunchOfNewServers){
Element server = Document.createElement("server");
/* create and setup the server node...*/
root.appendChild(server);
}
/* use whatever method to output DOM to XML (for example, using transformer like you did).*/
I had a similar problem in .NET
app in Internet Explorer.
I solved the problem adding the certificate (VeriSign Class 3 certificate in my case) to trusted editors certificates.
Go to Internet Options-> Content -> Publishers and import it
You can get the certificate if you export it from:
Internet Options-> Content -> Certificates -> Intermediate Certification Authorities -> VeriSign Class 3 Public Primary Certification Authority - G5
thanks
I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.
var test_obj = from d in repository.DbPricing
join d1 in repository.DbOfficeProducts on d.OfficeProductId equals d1.Id
join d2 in repository.DbOfficeProductDetails on d1.ProductDetailsId equals d2.Id
select new
{
PricingId = d.Id,
LetterColor = d2.LetterColor,
LetterPaperWeight = d2.LetterPaperWeight
};
http://www.cybertechquestions.com/select-across-multiple-tables-in-entity-framework-resulting-in-a-generic-iqueryable_222801.html
Like this:
my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both
Use this:
SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM
(SELECT DISTINCT id FROM table WHERE fid = 64) Base
and put the "output" of a query as the "input" of another.
Using CTE:
; WITH Base AS (
SELECT DISTINCT id FROM table WHERE fid = 64
)
SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM Base
The two queries should be equivalent.
Technically you could
SELECT DISTINCT id, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) AS RowNum
FROM table
WHERE fid = 64
but if you increase the number of DISTINCT fields, you have to put all these fields in the PARTITION BY
, so for example
SELECT DISTINCT id, description,
ROW_NUMBER() OVER (PARTITION BY id, description ORDER BY id) AS RowNum
FROM table
WHERE fid = 64
I even hope you comprehend that you are going against standard naming conventions here, id
should probably be a primary key, so unique by definition, so a DISTINCT
would be useless on it, unless you coupled the query with some JOIN
s/UNION ALL
...
One option is to use the delete method as follows:
StringBuffer sb = new StringBuffer();
for (int n = 0; n < 10; n++) {
sb.append("a");
// This will clear the buffer
sb.delete(0, sb.length());
}
Another option (bit cleaner) uses setLength(int len):
sb.setLength(0);
See Javadoc for more info:
In my case it worked after the connection to the wsdl, use the function __setLocation()
to define the location again because the call fails with the error:
Could not connect to the host
This happens if the WSDL is different to the one specified in SoapClient::SoapClient
.
You need to add some style for span6
, smthg like that:
.row-fluid .span6 {
display: table-cell;
vertical-align: bottom;
float: none;
}
and this is your fiddle: http://jsfiddle.net/sgB3T/
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now
"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "
class Foo {
const BAR = 'baz';
}
echo Foo::BAR;
This is the only way to make class constants. These constants are always globally accessible via Foo::BAR
, but they're not accessible via just BAR
.
To achieve a syntax like Foo::baz()->BAR
, you would need to return an object from the function baz()
of class Foo
that has a property BAR
. That's not a constant though. Any constant you define is always globally accessible from anywhere and can't be restricted to function call results.
I believe SET
is ANSI standard whereas the SELECT
is not. Also note the different behavior of SET
vs. SELECT
in the example below when a value is not found.
declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */
set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */
Web Browser control might work. http://ryanfarley.com/blog/archive/2004/12/23/1330.aspx
Also a bunch of pdf open source c# projects here http://csharp-source.net/open-source/pdf-libraries
For your problem use like this:
ListViewItem row = new ListViewItem();
row.SubItems.Add(value.ToString());
listview1.Items.Add(row);
I run into this problem on a regular basis and often use the "add a method" solution. However, there are definitely cases where "add a method" or "compute it in the view" don't work (or don't work well). E.g. when you are caching template fragments and need some non-trivial DB computation to produce it. You don't want to do the DB work unless you need to, but you won't know if you need to until you are deep in the template logic.
Some other possible solutions:
Use the {% expr <expression> as <var_name> %} template tag found at http://www.djangosnippets.org/snippets/9/ The expression is any legal Python expression with your template's Context as your local scope.
Change your template processor. Jinja2 (http://jinja.pocoo.org/2/) has syntax that is almost identical to the Django template language, but with full Python power available. It's also faster. You can do this wholesale, or you might limit its use to templates that you are working on, but use Django's "safer" templates for designer-maintained pages.
It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split()
can do the correct tokenization for args (I'm using Blender's example of the call):
import shlex
from subprocess import Popen, PIPE
command = shlex.split('swfdump /tmp/filename.swf/ -d')
process = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
You could try something like:
var Title = $('<textarea />').html("Chris' corner").text();_x000D_
console.log(Title);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
A more interactive version:
$('form').submit(function() {_x000D_
var theString = $('#string').val();_x000D_
var varTitle = $('<textarea />').html(theString).text();_x000D_
$('#output').text(varTitle);_x000D_
return false;_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="#" method="post">_x000D_
<fieldset>_x000D_
<label for="string">Enter a html-encoded string to decode</label>_x000D_
<input type="text" name="string" id="string" />_x000D_
</fieldset>_x000D_
<fieldset>_x000D_
<input type="submit" value="decode" />_x000D_
</fieldset>_x000D_
</form>_x000D_
_x000D_
<div id="output"></div>
_x000D_
This query will help you:
select *
from XXXX
where datepart(YYYY,create_date)>=2013
and DATEPART(YYYY,create_date)<=2014
Aapt2, included in the Android SDK build tools can do this - no third party tools needed.
$(ANDROID_SDK)/build-tools/28.0.3/aapt2 d --file AndroidManifest.xml app-foo-release.apk
Starting with build-tools v29 you have to add the command xmltree
:
$(ANDROID_SDK)/build-tools/29.0.3/aapt2 d xmltree --file AndroidManifest.xml app-foo-release.apk
Toad for MySQL by Quest is free for non-commercial use. I really like the interface and it's quite powerful if you have several databases to work with (for example development, test and production servers).
From the website:
Toad® for MySQL is a freeware development tool that enables you to rapidly create and execute queries, automate database object management, and develop SQL code more efficiently. It provides utilities to compare, extract, and search for objects; manage projects; import/export data; and administer the database. Toad for MySQL dramatically increases productivity and provides access to an active user community.
I think double quotes works too:
SELECT "Business Name","Other Name" FROM your_Table
But I only tested on SQL Server NOT mySQL in case someone work with MS SQL Server.
It's simple, follow these steps
File > New > Folder > Assets Folder
Note : App must be selected before creating folder.
This answer support the @ macrocosme suggestion.
I am using heat map as hist2d plot. Additionally I use cmin=0.5 for no count value and cmap for color, r represent the reverse of given color.
# np.arange(data.min(), data.max()+binwidth, binwidth)
bin_x = np.arange(0.6, 7 + 0.3, 0.3)
bin_y = np.arange(12, 58 + 3, 3)
plt.hist2d(data=fuel_econ, x='displ', y='comb', cmin=0.5, cmap='viridis_r', bins=[bin_x, bin_y]);
plt.xlabel('Dispalcement (1)');
plt.ylabel('Combine fuel efficiency (mpg)');
plt.colorbar();
The capitalization is wrong, and you have an extra argument.
Do this instead:
$('img#thumb').removeAttr('id');
For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.
The solutions so far don't work because the POST data is stored in the headers. A redirect solves this issue according this this post.
How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?
try this:
SELECT * FROM TableA
JOIN TableB ON TableA.primary_key = TableB.foreign_key
JOIN TableB ON TableB.foreign_key = TableC.foreign_key
In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.
The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.
DECLARE
PROD_ROW_ID VARCHAR (10) := NULL;
VIS_ROW_ID NUMBER;
DSC VARCHAR (512);
BEGIN
SELECT ROW_ID
INTO VIS_ROW_ID
FROM SIEBEL.S_PROD_INT
WHERE PART_NUM = 'S0146404';
BEGIN
SELECT RTRIM (VIS.SERIAL_NUM)
|| ','
|| RTRIM (PLANID.DESC_TEXT)
|| ','
|| CASE
WHEN PLANID.HIGH = 'TEST123'
THEN
CASE
WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
THEN
'Y'
ELSE
'N'
END
ELSE
'N'
END
|| ','
|| 'GB'
|| ','
|| RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
INTO DSC
FROM SIEBEL.S_LST_OF_VAL PLANID
INNER JOIN SIEBEL.S_PROD_INT PROD
ON PROD.PART_NUM = PLANID.VAL
INNER JOIN SIEBEL.S_ASSET NETFLIX
ON PROD.PROD_ID = PROD.ROW_ID
INNER JOIN SIEBEL.S_ASSET VIS
ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
INNER JOIN SIEBEL.S_PROD_INT VISPROD
ON VIS.PROD_ID = VISPROD.ROW_ID
WHERE PLANID.TYPE = 'Test Plan'
AND PLANID.ACTIVE_FLG = 'Y'
AND VISPROD.PART_NUM = VIS_ROW_ID
AND PROD.STATUS_CD = 'Active'
AND VIS.SERIAL_NUM IS NOT NULL;
END;
END;
/
References
http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/
Skype is usually the culprit because it uses port 80 by default. Just close it or uncheck "Use port 80 and 443 as alternatives for incoming connections" under tools > options... > advanced > connection and then restart Skype.
You can try this cool app available in play store called Html Page Source https://play.google.com/store/apps/details?id=com.scintillar.hps
This gives accurate results, when checking on a scrollable element (i.e. not window
):
// `element` is a native JS HTMLElement
if ( element.scrollTop == (element.scrollHeight - element.offsetHeight) )
// Element scrolled to bottom
offsetHeight
should give the actual visible height of an element (including padding, margin, and scrollbars), and scrollHeight
is the entire height of an element including invisible (overflowed) areas.
jQuery
's .outerHeight()
should give similar result to JS's .offsetHeight
--
the documentation in MDN for offsetHeight
is unclear about its cross-browser support. To cover more options, this is more complete:
var offsetHeight = ( container.offsetHeight ? container.offsetHeight : $(container).outerHeight() );
if ( container.scrollTop == (container.scrollHeight - offsetHeight) ) {
// scrolled to bottom
}
I like to start with a class like this class settings { public int X {get;set;} public string Y { get; set; } // repeat as necessary
public settings()
{
this.X = defaultForX;
this.Y = defaultForY;
// repeat ...
}
public void Parse(Uri uri)
{
// parse values from query string.
// if you need to distinguish from default vs. specified, add an appropriate property
}
This has worked well on 100's of projects. You can use one of the many other parsing solutions to parse values.
With xc8 you have to be careful about declaring a variable
as the same type in each file as you could , erroneously,
declare something an int
in one file and a char
say in another.
This could lead to corruption of variables.
This problem was elegantly solved in a microchip forum some 15 years ago /* See "http:www.htsoft.com" / / "forum/all/showflat.php/Cat/0/Number/18766/an/0/page/0#18766"
But this link seems to no longer work...
So I;ll quickly try to explain it; make a file called global.h.
In it declare the following
#ifdef MAIN_C
#define GLOBAL
/* #warning COMPILING MAIN.C */
#else
#define GLOBAL extern
#endif
GLOBAL unsigned char testing_mode; // example var used in several C files
Now in the file main.c
#define MAIN_C 1
#include "global.h"
#undef MAIN_C
This means in main.c the variable will be declared as an unsigned char
.
Now in other files simply including global.h will have it declared as an extern for that file.
extern unsigned char testing_mode;
But it will be correctly declared as an unsigned char
.
The old forum post probably explained this a bit more clearly.
But this is a real potential gotcha
when using a compiler
that allows you to declare a variable in one file and then declare it extern as a different type in another. The problems associated with
that are if you say declared testing_mode as an int in another file
it would think it was a 16 bit var and overwrite some other part of ram, potentially corrupting another variable. Difficult to debug!
Had this error too, the cause was simple, but not obvious: incorrect password. Not sure why I didn't get just "Login failed" from freshly installed SQL 2016 server.
Open below file C:\xampp\htdocs\project\common\config\params-local.php
Before your code:
<?php
return [
];
after your code:
<?php
yii::setAlias('@path1', 'localhost/foodbam/backend/web');
return [
];
I would suggest you have to use a Reader to convert your InputStream in.
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
new JSONObject(responseStrBuilder.toString());
I tried in.toString() but it returns:
getClass().getName() + '@' + Integer.toHexString(hashCode())
(like documentation says it derives to toString from Object)
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
This is the behavior of ln
if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx
to be the symlink, you should remove that directory first and run that same command.
Use the Date
object provided by javascript. It's not unique or special to Google's scripting environment.
You can simply use DataColumnCollection.IndexOf
So that you can get the index of the required column by name then use it with your row:
row[dt.Columns.IndexOf("ColumnName")] = columnValue;
For one-way data binding from parent to child, use the @Input
decorator (as recommended by the style guide) to specify an input property on the child component
@Input() model: any; // instead of any, specify your type
and use template property binding in the parent template
<child [model]="parentModel"></child>
Since you are passing an object (a JavaScript reference type) any changes you make to object properties in the parent or the child component will be reflected in the other component, since both components have a reference to the same object. I show this in the Plunker.
If you reassign the object in the parent component
this.model = someNewModel;
Angular will propagate the new object reference to the child component (automatically, as part of change detection).
The only thing you shouldn't do is reassign the object in the child component. If you do this, the parent will still reference the original object. (If you do need two-way data binding, see https://stackoverflow.com/a/34616530/215945).
@Component({
selector: 'child',
template: `<h3>child</h3>
<div>{{model.prop1}}</div>
<button (click)="updateModel()">update model</button>`
})
class Child {
@Input() model: any; // instead of any, specify your type
updateModel() {
this.model.prop1 += ' child';
}
}
@Component({
selector: 'my-app',
directives: [Child],
template: `
<h3>Parent</h3>
<div>{{parentModel.prop1}}</div>
<button (click)="updateModel()">update model</button>
<child [model]="parentModel"></child>`
})
export class AppComponent {
parentModel = { prop1: '1st prop', prop2: '2nd prop' };
constructor() {}
updateModel() { this.parentModel.prop1 += ' parent'; }
}
Plunker - Angular RC.2
If you have access to SRV Records, you can use them to get what you want :)
E.G
A Records
Name: mc1.domain.com
Value: <yourIP>
Name: mc2.domain.com
Value: <yourIP>
SRV Records
Name: _minecraft._tcp.mc1.domain.com
Priority: 5
Weight: 5
Port: 25565
Value: mc1.domain.com
Name: _minecraft._tcp.mc2.domain.com
Priority: 5
Weight: 5
Port: 25566
Value: mc2.domain.com
then in minecraft you can use
mc1.domain.com which will sign you into server 1 using port 25565
and
mc2.domain.com which will sign you into server 2 using port 25566
then on your router you can have it point 25565 and 25566 to the machine with both servers on and Voilà !
Source: This works for me running 2 minecraft servers on the same machine with ports 50500 and 50501
If you need to list all rows where all the column values are NULL
, then i'd use the COLLATE
function. This takes a list of values and returns the first non-null value. If you add all the column names to the list, then use IS NULL
, you should get all the rows containing only nulls.
SELECT * FROM MyTable WHERE COLLATE(Col1, Col2, Col3, Col4......) IS NULL
You shouldn't really have any tables with ALL the columns
null, as this means you don't have a primary key
(not allowed to be null
). Not having a primary key is something to be avoided; this breaks the first normal form.
Try using tqdm.notebook.tqdm
instead of tqdm
, as outlined here.
This could be as simple as changing your import to:
from tqdm.notebook import tqdm
Good luck!
EDIT: After testing, it seems that tqdm
actually works fine in 'text mode' in Jupyter notebook. It's hard to tell because you haven't provided a minimal example, but it looks like your problem is caused by a print statement in each iteration. The print statement is outputting a number (~0.89) in between each status bar update, which is messing up the output. Try removing the print statement.
Get textarea text with JavaScript:
<!DOCTYPE html>
<body>
<form id="form1">
<div>
<textarea id="area1" rows="5">Yes</textarea>
<input type="button" value="get txt" onclick="go()" />
<br />
<p id="as">Now what</p>
</div>
</form>
</body>
function go() {
var c1 = document.getElementById('area1').value;
var d1 = document.getElementById('as');
d1.innerHTML = c1;
}
I used to prefer '
, especially for '''docstrings'''
, as I find """this creates some fluff"""
. Also, '
can be typed without the Shift key on my Swiss German keyboard.
I have since changed to using triple quotes for """docstrings"""
, to conform to PEP 257.
I believe this is much simpler;
dynamic obj = JObject.Parse(jsonString);
string results = obj.results;
foreach(string result in result.Split('))
{
//Todo
}
For SEO reason:
<div itemscope itemtype="https://schema.org/Organization">
<p id="logo"><a href="/"><span itemprop="Brand">Your business</span> <span class="icon fa-stg"></span> - <span itemprop="makesOffer">sell staff</span></a></p>
</div>
<h1>Your awesome title</h1>
Use this in your batch file:
%~dp0\bin\Iris.exe
%~dp0
resolves to the full path of the folder in which the batch script resides.
You can access the src property of the iframe but that will only give you the initially loaded URL. If the user is navigating around in the iframe via you'll need to use an HTA to solve the security problem.
http://msdn.microsoft.com/en-us/library/ms536474(VS.85).aspx
Check out the link, using an HTA and setting the "application" property of an iframe will allow you to access the document.href property and parse out all of the information you want, including DOM elements and their values if you so choose.
According to the official documentation:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
console.log(message);
/*]]>*/
</script>
The easiest way is to use PyHive.
To install you'll need these libraries:
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive
After installation, you can connect to Hive like this:
from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")
Now that you have the hive connection, you have options how to use it. You can just straight-up query:
cursor = conn.cursor()
cursor.execute("SELECT cool_stuff FROM hive_table")
for result in cursor.fetchall():
use_result(result)
...or to use the connection to make a Pandas dataframe:
import pandas as pd
df = pd.read_sql("SELECT cool_stuff FROM hive_table", conn)
You can put your (len/2)
test in the for loop:
for(i = 0,k=len-1 ; i < (len/2); i++,k--)
{
temp = str[k];
str[k] = str[i];
str[i] = temp;
}
Try doing this:
py -m pip install pipwin
py -m pipwin install PyAudio
There is also var_export and print_r more commonly known for printing debug output but both functions can take an optional argument to return a string instead.
Using the example from the question as data.
$array = ["item1"=>"object1", "item2"=>"object2","item-n"=>"object-n"];
print_r
to turn the array into a stringThis will output a human readable representation of the variable.
$string = print_r($array, true);
echo $string;
Will output:
Array
(
[item1] => object1
[item2] => object2
[item-n] => object-n
)
var_export
to turn the array into a stringWhich will output a php string representation of the variable.
$string = var_export($array, true);
echo $string;
Will output:
array (
'item1' => 'object1',
'item2' => 'object2',
'item-n' => 'object-n',
)
Because it is valid php we can evaluate it.
eval('$array2 = ' . var_export($array, true) . ';');
var_dump($array2 === $array);
Outputs:
bool(true)
@geedoubleya answer is my favorite.
However, I do prefer this
if [[ -f diff.txt && -s diff.txt ]]
then
rm -f empty.txt
touch full.txt
elif [[ -f diff.txt && ! -s diff.txt ]]
then
rm -f full.txt
touch empty.txt
else
echo "File diff.txt does not exist"
fi
Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).
Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:
Dynamic Search Conditions in T-SQL by by Erland Sommarskog
The Curse and Blessings of Dynamic SQL by Erland Sommarskog
If you have the proper SQL Server 2008 version (SQL 2008 SP1 CU5 (10.0.2746) and later), you can use this little trick to actually use an index:
Add OPTION (RECOMPILE)
onto your query, see Erland's article, and SQL Server will resolve the OR
from within (@LastName IS NULL OR LastName= @LastName)
before the query plan is created based on the runtime values of the local variables, and an index can be used.
This will work for any SQL Server version (return proper results), but only include the OPTION(RECOMPILE) if you are on SQL 2008 SP1 CU5 (10.0.2746) and later. The OPTION(RECOMPILE) will recompile your query, only the verison listed will recompile it based on the current run time values of the local variables, which will give you the best performance. If not on that version of SQL Server 2008, just leave that line off.
CREATE PROCEDURE spDoSearch
@FirstName varchar(25) = null,
@LastName varchar(25) = null,
@Title varchar(25) = null
AS
BEGIN
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
(@FirstName IS NULL OR (FirstName = @FirstName))
AND (@LastName IS NULL OR (LastName = @LastName ))
AND (@Title IS NULL OR (Title = @Title ))
OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later
END
old question, new verb in tidyverse:
library(tidyr) # version >= 0.8.0
df <- data.frame(var1=c('a', 'b', 'c'), var2=c('d', 'e', 'f'), freq=1:3)
df %>%
uncount(freq)
var1 var2
1 a d
2 b e
2.1 b e
3 c f
3.1 c f
3.2 c f
Never give borderRadius to your <Text />
always wrap that <Text />
inside your <View />
or in your <TouchableOpacity/>
.
borderRadius on <Text />
will work perfectly on Android devices. But on IOS devices it won't work.
So keep this in your practice to wrap your <Text/>
inside your <View/>
or on <TouchableOpacity/>
and then give the borderRadius to that <View />
or <TouchableOpacity />
so that it will work on both Android as well as on IOS devices.
For example:-
<TouchableOpacity style={{borderRadius: 15}}>
<Text>Button Text</Text>
</TouchableOpacity>
-Thanks
You need to create another migration file - and place it in there:
Run
Laravel 4: php artisan migrate:make rename_stnk_column
Laravel 5: php artisan make:migration rename_stnk_column
Then inside the new migration file place:
class RenameStnkColumn extends Migration
{
public function up()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id', 'id_stnk');
});
}
public function down()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id_stnk', 'id');
});
}
}
You can invoke MySQL show status command
show status like 'Conn%';
For more info read Show open database connections
I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):
For loop
LinkedList<String> linkedList = new LinkedList<>();
System.out.println("==> For Loop Example.");
for (int i = 0; i < linkedList.size(); i++) {
System.out.println(linkedList.get(i));
}
Enhanced for loop
for (String temp : linkedList) {
System.out.println(temp);
}
While loop
int i = 0;
while (i < linkedList.size()) {
System.out.println(linkedList.get(i));
i++;
}
Iterator
Iterator<String> iterator = linkedList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
collection stream() util (Java 8)
linkedList.forEach((temp) -> {
System.out.println(temp);
});
One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i)
operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
I was getting this error in IntelliJ, and none of these answers helped me. So here's how I solved it.
Somehow one of my sub-modules added a .git
directory. All git functionality returned after I deleted it.
Using numpy pack/unpackbits, they are your best friends.
Examples
--------
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
[ 7],
[23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
.NET DDD Sample from Domain-Driven Design Book by Eric Evans can be found here: http://dddsamplenet.codeplex.com
Cheers,
Jakub G
Use the directions API.
Make an ajax call i.e.
https://maps.googleapis.com/maps/api/directions/json?parameters
and then parse the responce
$product->get_categories()
is deprecated since version 3.0! Use wc_get_product_category_list
instead.
https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html
If a module was installed with the global (-g
) flag, you can get the parent location by running:
npm get prefix
or
npm ls -g --depth=0
which will print the location along with the list of installed modules.
Take care with some of the examples; $0 may include some leading path as well as the name of the program. Eg save this two line script as ./mytry.sh and the execute it.
#!/bin/bash
echo "parameter 0 --> $0" ; exit 0
Output:
parameter 0 --> ./mytry.sh
This is on a current (year 2016) version of Bash, via Slackware 14.2
Adding another version. This one tries to iterate over userdata as well.
function inspect(o,indent)
if indent == nil then indent = 0 end
local indent_str = string.rep(" ", indent)
local output_it = function(str)
print(indent_str..str)
end
local length = 0
local fu = function(k, v)
length = length + 1
if type(v) == "userdata" or type(v) == 'table' then
output_it(indent_str.."["..k.."]")
inspect(v, indent+1)
else
output_it(indent_str.."["..k.."] "..tostring(v))
end
end
local loop_pairs = function()
for k,v in pairs(o) do fu(k,v) end
end
local loop_metatable_pairs = function()
for k,v in pairs(getmetatable(o)) do fu(k,v) end
end
if not pcall(loop_pairs) and not pcall(loop_metatable_pairs) then
output_it(indent_str.."[[??]]")
else
if length == 0 then
output_it(indent_str.."{}")
end
end
end
In my case new File()
doesn't work, it causes a FileNotFoundException
when run in a Jenkins pipeline job. The following code solved this, and is even easier in my opinion:
def fileContents = readFile "path/to/file"
I still don't understand this difference completely, but maybe it'll help anyone else with the same trouble. Possibly the exception was caused because new File()
creates a file on the system which executes the groovy code, which was a different system than the one that contains the file I wanted to read.
If it wasn't, which constructor should be used if there are more than one?
There is more information on the initialization and execution of Java programs available in the Java Language Specification.
The package broom
comes in handy here (it uses the "tidy" format).
tidy(mg)
will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).
Example from broom
's github repo:
lmfit <- lm(mpg ~ wt, mtcars)
require(broom)
tidy(lmfit)
term estimate std.error statistic p.value
1 (Intercept) 37.285 1.8776 19.858 8.242e-19
2 wt -5.344 0.5591 -9.559 1.294e-10
is.data.frame(tidy(lmfit))
[1] TRUE
Also:
func getTime() -> (hour: Int, minute: Int,second: Int) {
let hour = 1
let minute = 2
let second = 3
return ( hour, minute, second)
}
Then it's invoked as:
let time = getTime()
print("hour: \(time.hour), minute: \(time.minute), second: \(time.second)")
This is the standard way how to use it in the book The Swift Programming Language written by Apple.
or just like:
let time = getTime()
print("hour: \(time.0), minute: \(time.1), second: \(time.2)")
it's the same but less clearly.
1. Final • Final is used to apply restrictions on class, method and variable. • Final class can't be inherited, final method can't be overridden and final variable value can't be changed. • Final variables are initialized at the time of creation except in case of blank final variable which is initialized in Constructor. • Final is a keyword.
2. Finally • Finally is used for exception handling along with try and catch. • It will be executed whether exception is handled or not. • This block is used to close the resources like database connection, I/O resources. • Finally is a block.
3. Finalize • Finalize is called by Garbage collection thread just before collecting eligible objects to perform clean up processing. • This is the last chance for object to perform any clean-up but since it’s not guaranteed that whether finalize () will be called, its bad practice to keep resource till finalize call. • Finalize is a method.
"The linear time bound of build Heap, can be shown by computing the sum of the heights of all the nodes in the heap, which is the maximum number of dashed lines. For the perfect binary tree of height h containing N = 2^(h+1) – 1 nodes, the sum of the heights of the nodes is N – H – 1. Thus it is O(N)."
STORE PROCEDURE FUNCTION (USER DEFINED FUNCTION)
* Procedure can return 0, single or | * Function can return only single value
multiple values. |
|
* Procedure can have input, output | * Function can have only input
parameters. | parameters.
|
* Procedure cannot be called from | * Functions can be called from
function. | procedure.
|
* Procedure allows select as well as | * Function allows only select statement
DML statement in it. | in it.
|
* Exception can be handled by | * Try-catch block cannot be used in a
try-catch block in a procedure. | function.
|
* We can go for transaction management| * We can not go for transaction
in procedure. | management in function.
|
* Procedure cannot be utilized in a | * Function can be embedded in a select
select statement | statement.
|
* Procedure can affect the state | * Function can not affect the state
of database means it can perform | of database means it can not
CRUD operation on database. | perform CRUD operation on
| database.
|
* Procedure can use temporary tables. | * Function can not use
| temporary tables.
|
* Procedure can alter the server | * Function can not alter the
environment parameters. | environment parameters.
|
* Procedure can use when we want | * Function can use when we want
instead is to group a possibly- | to compute and return a value
complex set of SQL statements. | for use in other SQL
| statements.
This will be compiled into:
React.createElement(Modal, { ...this.props, title: "Modal heading", animation: false }, child0, child1, child2, ...)
where it gives more two properties title
& animation
beyond the props
the host element has.
...
is the ES6 operator called Spread.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
You can use List as a classifier for many fields, but you need wrap null values into Optional:
Function<String, List> classifier = (item) -> List.of(
item.getFieldA(),
item.getFieldB(),
Optional.ofNullable(item.getFieldC())
);
Map<List, List<Item>> grouped = items.stream()
.collect(Collectors.groupingBy(classifier));
To reflect the status as of 2015:
Behaviorally both 400 and 422 response codes will be treated the same by clients and intermediaries, so it actually doesn't make a concrete difference which you use.
However I would expect to see 400 currently used more widely, and furthermore the clarifications that the HTTPbis spec provides make it the more appropriate of the two status codes:
For context, HTTPbis is a revision of the HTTP/1.1 spec that attempts to clarify areas that were unclear or inconsistent. Once it has reached approved status it will supersede RFC2616.
you seem to have not created an main method, which should probably look something like this (i am not sure)
class RunThis
{
public static void main(String[] args)
{
Calculate answer = new Calculate();
answer.getNumber1();
answer.getNumber2();
answer.setNumber(answer.getNumber1() , answer.getNumber2());
answer.getOper();
answer.setOper(answer.getOper());
answer.getAnswer();
}
}
the point is you should have created a main method under some class and after compiling you should run the .class file containing main method. In this case the main method is under RunThis i.e RunThis.class.
I am new to java this may or may not be the right answer, correct me if i am wrong
Try this:
concat(left(datefield,10),left(timefield,8))
10 char on date field based on full date yyyy-MM-dd
.
8 char on time field based on full time hh:mm:ss
.
It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.
Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.
The general idea is to sweep the function across. You have many options, one is apply()
:
R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269
R>
Here's how to do this with java.nio
operations:
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
// previous code: destination.transferFrom(source, 0, source.size());
// to avoid infinite loops, should be:
long count = 0;
long size = source.size();
while((count += destination.transferFrom(source, count, size-count))<size);
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
If you are able to use org.apache.commons.lang.StringUtils, I suggest using the following:
String container = "aBcDeFg";
String content = "dE";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);
Codehaus Jackson - I have been this awesome API since 2012 for my RESTful webservice and JUnit tests. With their API, you can:
(1) Convert JSON String to Java bean
public static String beanToJSONString(Object myJavaBean) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.writeValueAsString(myJavaBean);
}
(2) Convert JSON String to JSON object (JsonNode)
public static JsonNode stringToJSONObject(String jsonString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readTree(jsonString);
}
//Example:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JsonNode jsonNode = stringToJSONObject(jsonString);
Assert.assertEquals("Phonetype value not legit!", "N95", jsonNode.get("phonetype").getTextValue());
Assert.assertEquals("Cat value is tragic!", "WP", jsonNode.get("cat").getTextValue());
(3) Convert Java bean to JSON String
public static Object JSONStringToBean(Class myBeanClass, String JSONString) throws Exception {
ObjectMapper jacksonObjMapper = new ObjectMapper();
return jacksonObjMapper.readValue(JSONString, beanClass);
}
REFS:
JsonNode API - How to use, navigate, parse and evaluate values from a JsonNode object
Tutorial - Simple tutorial how to use Jackson to convert JSON string to JsonNode
The problem for me was that I had .rnd in my home directory but it was owned by root. Deleting it and reissuing the openssl command fixed this.
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
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>
Similar to another suggestion, except will not obliterate actual zero:
if (ltrim($str, '0') != '') {
$str = ltrim($str, '0');
} else {
$str = '0';
}
Or as was suggested (as of PHP 5.3), shorthand ternary operator can be used:
$str = ltrim($str, '0') ?: '0';
You can insert new data into table by two ways.
Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString()
it:
Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z
Don't want the T and Z? (Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):
instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763
Want milliseconds instead of nanoseconds? (So you can plop it into a sql query):
instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664
etc.
OK. After trying out some error handling, I figured out how to solve the issue I was having.
Here's an example of how to make this work (let me know if there's something I'm missing) :
SET XACT_ABORT OFF ; -- > really important to set that to OFF
BEGIN
DECLARE @Any_error int
DECLARE @SSQL varchar(4000)
BEGIN TRANSACTION
INSERT INTO Table1(Value1) VALUES('Value1')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
INSERT INTO Table1(Value1) VALUES('Value1')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
INSERT INTO Table1(Value1) VALUES('Value2')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
ErrorHandler:
IF @Any_error = 0 OR @Any_error=2627
BEGIN
PRINT @ssql
COMMIT TRAN
END
ELSE
BEGIN
PRINT @ssql
ROLLBACK TRAN
END
END
As a result of the above Transaction, Table1 will have the following values Value1, Value2.
2627 is the error code for Duplicate Key by the way.
Thank you all for the prompt reply and helpful suggestions.
Add your application's package in "Filter Name" by clicking on "+" button on left top corner in logcat.
fsspec is a great option for this, it offers a filesystem like implementation of sftp.
from fsspec.implementations.sftp import SFTPFileSystem
fs = SFTPFileSystem(host=host, username=username, password=password)
# list a directory
fs.ls("/")
# open a file
with fs.open(file_name) as file:
content = file.read()
Also worth noting that fsspec uses paramiko in the implementation.
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
Github recently released a cli utility called github-cli. After installing it, you can checkout a pull request's branch locally by using its id (ref)
e.g: gh pr checkout 2267
This works with forks as well but if you then need to push back to the fork, you'll need to add the remote repository and use traditional git push
(until this ticket gets implemented in gh utility)
I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.
Another option is to search the XML as a string by converting it to a string and then using LIKE. However as a computed column can't be part of a WHERE clause you need to wrap it in another SELECT like this:
SELECT * FROM
(SELECT *, CONVERT(varchar(MAX), [COLUMNA]) as [XMLDataString] FROM TABLE) x
WHERE [XMLDataString] like '%Test%'
Tensorflow upgrade -Python3
>> pip3 install --upgrade tensorflow --user
if you got this
"ERROR: tensorboard 2.0.2 has requirement grpcio>=1.24.3, but you'll have grpcio 1.22.0 which is incompatible."
Upgrade grpcio
>> pip3 install --upgrade grpcio --user
there is a limited alternative you can use
header:
class std_int_vector;
class A{
std_int_vector* vector;
public:
A();
virtual ~A();
};
cpp:
#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}
A::A() : vector(new std_int_vector()) {}
[...]
not tested in real programs, so expect it to be non-perfect.
its simple let us assume you have made an state full class by extending Component which contains following
class DisableButton extends Components
{
constructor()
{
super();
// now set the initial state of button enable and disable to be false
this.state = {isEnable: false }
}
// this function checks the length and make button to be enable by updating the state
handleButtonEnable(event)
{
const value = this.target.value;
if(value.length > 0 )
{
// set the state of isEnable to be true to make the button to be enable
this.setState({isEnable : true})
}
}
// in render you having button and input
render()
{
return (
<div>
<input
placeholder={"ANY_PLACEHOLDER"}
onChange={this.handleChangePassword}
/>
<button
onClick ={this.someFunction}
disabled = {this.state.isEnable}
/>
<div/>
)
}
}
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
You can loop the array with a for loop and the object properties with for-in loops.
for (var i=0; i<result.length; i++)
for (var name in result[i]) {
console.log("Item name: "+name);
console.log("Source: "+result[i][name].sourceUuid);
console.log("Target: "+result[i][name].targetUuid);
}
To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance
> python python_script.py var1 var2
To access these variables within python you will need
import sys
print sys.argv[0] # prints python_script.py
print sys.argv[1] # prints var1
print sys.argv[2] # prints var2
Wouldn't something akin to this be better, security-wise?:
sqlplus -s /nolog << EOF
CONNECT admin/password;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
@pl_script_1.sql
@pl_script_2.sql
exit;
EOF
You need to give the WebClient object the credentials. Something like this...
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
You can use the split()
function to break input on the basis of line break.
yourString.split("\n")
You can also refine Hash::each
so it will support recursive enumeration. Here is my version of Hash::each
(Hash::each_pair
) with block and enumerator support:
module HashRecursive
refine Hash do
def each(recursive=false, &block)
if recursive
Enumerator.new do |yielder|
self.map do |key, value|
value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
yielder << [[key], value]
end
end.entries.each(&block)
else
super(&block)
end
end
alias_method(:each_pair, :each)
end
end
using HashRecursive
Here are usage examples of Hash::each
with and without recursive
flag:
hash = {
:a => {
:b => {
:c => 1,
:d => [2, 3, 4]
},
:e => 5
},
:f => 6
}
p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2
p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6
hash.each do |key, value|
puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6
hash.each(true) do |key, value|
puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6
hash.each_pair(recursive=true) do |key, value|
puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6
Here is example from the question itself:
hash = {
1 => ["a", "b"],
2 => ["c"],
3 => ["a", "d", "f", "g"],
4 => ["q"]
}
hash.each(recursive=false) do |key, value|
puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]
Also take a look at my recursive version of Hash::merge
(Hash::merge!
) here.
Yes the function is not in sql 2008. You can use the cast operation to do that.
For example we have employee
table and you want name
with applydate
.
so you can use
Select cast(name as varchar) + cast(applydate as varchar) from employee
It will work where concat function is not working.
Without eval:
Your original string was not an actual string.
jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"
The easiest way to to wrap it all with a single quote.
jsonObj = '"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"'
Then you can combine two steps to parse it to JSON:
$.parseJSON(jsonObj.slice(1,-1))
Here we can use urllib's Legacy interface in Python3:
The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.
Example (2 lines code):
import urllib.request
url = 'https://www.python.org/static/img/python-logo.png'
urllib.request.urlretrieve(url, "logo.png")
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.
A very simple solution:
resize = () => this.forceUpdate()
componentDidMount() {
window.addEventListener('resize', this.resize)
}
componentWillUnmount() {
window.removeEventListener('resize', this.resize)
}
Some years later, looking for the same requirement, I found a CSS option using background-size.
It is supposed to work in modern browsers (IE9+).
<div id="container" style="background-image:url(myimage.png)">
</div>
And the style:
#container
{
width: 100px; /*or 70%, or what you want*/
height: 200px; /*or 70%, or what you want*/
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
The reference: http://www.w3schools.com/cssref/css3_pr_background-size.asp
And the demo: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size
None of these options worked for me on Ubuntu 12.10 (yeah, I need to upgrade). However, I found an easy solution. Download the source from here: https://github.com/miracle2k/android-platform_sdk/blob/master/emulator/mksdcard/mksdcard.c. Then simply compile with "gcc mksdcard.c -o mksdcard". Backup mksdcard in the SDK tools subfolder and replace with the newly compiled one. Android Studio will now be happy with your SDK.
I know it's been a looong time since the question was made, but I found an easy solution and thought someone could use it (sorry about the poor english). Here it goes:
CSS
.main, .sidebar {
float: none;
padding: 20px;
vertical-align: top;
}
.container {
display: table;
}
.main {
width: 400px;
background-color: LightSlateGrey;
display: table-cell;
}
.sidebar {
width: 200px;
display: table-cell;
background-color: Tomato;
}
HTML
<div class="container clearfix">
<div class="sidebar">
simple text here
</div>
<div class="main">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam congue, tortor in mattis mattis, arcu erat pharetra orci, at vestibulum lorem ante a felis. Integer sit amet est ac elit vulputate lobortis. Vestibulum in ipsum nulla. Aenean erat elit, lacinia sit amet adipiscing quis, aliquet at erat. Vivamus massa sem, cursus vel semper non, dictum vitae mi. Donec sed bibendum ante.
</div>
</div>
Simple example. Note that you can turn into responsiveness.
Use
var jsDate = $('#your_datepicker_id').datepicker('getDate');
if (jsDate !== null) { // if any date selected in datepicker
jsDate instanceof Date; // -> true
jsDate.getDate();
jsDate.getMonth();
jsDate.getFullYear();
}
If you work in MVC 4, you can watch this solution, it worked for me.
Add the following Application_Error method to my Global.asax
:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
The controller itself is really simple:
public class ErrorController : Controller
{
public ActionResult Index(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
return View();
}
}
Check the full source code of Mvc4CustomErrorPage at GitHub.
Just utilize toString
or toLocaleString
I'd say. So:
var page_number:number = 3;
window.location.hash = page_number.toLocaleString();
These throw an error if page_number
is null
or undefined
. If you don't want that you can choose the fix appropriate for your situation:
// Fix 1:
window.location.hash = (page_number || 1).toLocaleString();
// Fix 2a:
window.location.hash = !page_number ? "1" page_number.toLocaleString();
// Fix 2b (allows page_number to be zero):
window.location.hash = (page_number !== 0 && !page_number) ? "1" page_number.toLocaleString();
Use the following command to solve this issue
RESTORE DATABASE [DatabaseName] WITH RECOVERY
Actually, You can achieve this with current typescript:
type Grow<T, A extends Array<T>> = ((x: T, ...xs: A) => void) extends ((...a: infer X) => void) ? X : never;
type GrowToSize<T, A extends Array<T>, N extends number> = { 0: A, 1: GrowToSize<T, Grow<T, A>, N> }[A['length'] extends N ? 0 : 1];
export type FixedArray<T, N extends number> = GrowToSize<T, [], N>;
Examples:
// OK
const fixedArr3: FixedArray<string, 3> = ['a', 'b', 'c'];
// Error:
// Type '[string, string, string]' is not assignable to type '[string, string]'.
// Types of property 'length' are incompatible.
// Type '3' is not assignable to type '2'.ts(2322)
const fixedArr2: FixedArray<string, 2> = ['a', 'b', 'c'];
// Error:
// Property '3' is missing in type '[string, string, string]' but required in type
// '[string, string, string, string]'.ts(2741)
const fixedArr4: FixedArray<string, 4> = ['a', 'b', 'c'];
EDIT (after a long time)
This should handle bigger sizes (as basically it grows array exponentially until we get to closest power of two):
type Shift<A extends Array<any>> = ((...args: A) => void) extends ((...args: [A[0], ...infer R]) => void) ? R : never;
type GrowExpRev<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
0: GrowExpRev<[...A, ...P[0]], N, P>,
1: GrowExpRev<A, N, Shift<P>>
}[[...A, ...P[0]][N] extends undefined ? 0 : 1];
type GrowExp<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
0: GrowExp<[...A, ...A], N, [A, ...P]>,
1: GrowExpRev<A, N, P>
}[[...A, ...A][N] extends undefined ? 0 : 1];
export type FixedSizeArray<T, N extends number> = N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T, T], N, [[T]]>;
This error raises if your js files where you have bounded the select2 with select box is loading before select2 js files. Please make sure files should be in this order like..
The accepted solution of modifying a Run Configuration wasn't ideal for me as I have a few different run configurations and could easily forget to do this when adding further ones in future. Also I wanted the setting to apply whenever running anything, e.g. when running JUnit tests by right-clicking and selecting "Run As" -> "JUnit Test".
The above can be achieved by modifying the JRE/JDK settings instead:-
-Xms512m -Xmx4G -XX:MaxPermSize=256M
You can compare class tokens to each other, so you could use value.getClass() == Integer.class
. However, the simpler and more canonical way is to use instanceof
:
if (value instanceof Integer) {
System.out.println("This is an Integer");
} else if(value instanceof String) {
System.out.println("This is a String");
} else if(value instanceof Float) {
System.out.println("This is a Float");
}
Notes:
instanceof C
matches for subclasses of C
too. However, in this case all the classes listed are final
, so they have no subclasses. Thus instanceof
is probably fine here.as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.
System.out.println("This is a(n) " + value.getClass().getSimpleName());
I know this is an old post but maybe someone down the line can use this.
// use document.form["form-name"] to reference the form
const ccForm = document.forms["ccform"];
// bind the onsubmit property to a function to do some logic
ccForm.onsubmit = function(e) {
// access the desired input through the var we setup
let ccSelection = ccForm.ccselect.value;
console.log(ccSelection);
e.preventDefault();
}
_x000D_
<form name="ccform">
<select name="ccselect">
<option value="card1">Card 1</option>
<option value="card2">Card 2</option>
<option value="card3">Card 3</option>
</select>
<button type="submit">Enter</button>
</form>
_x000D_
You can use basename()
and $_SERVER['PHP_SELF']
to get current page file name
echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */
While this is possible, you should not use the Flask dev server in production. The Flask dev server is not designed to be particularly secure, stable, or efficient. See the docs on deploying for correct solutions.
Add a parameter to your app.run()
. By default it runs on localhost
, change it to app.run(host= '0.0.0.0')
to run on all your machine's IP addresses. 0.0.0.0
is a special value, you'll need to navigate to the actual IP address.
Documented on the Flask site under "Externally Visible Server" on the Quickstart page:
Externally Visible Server
If you run the server you will notice that the server is only available from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have debug disabled or trust the users on your network, you can make the server publicly available.
Just change the call of the
run()
method to look like this:
app.run(host='0.0.0.0')
This tells your operating system to listen on a public IP.
If you're using #
as an operator, consider defining a new operator for it:
\newcommand{\pound}{\operatornamewithlimits{\#}}
You can then write things like \pound_{n = 1}^N
and get:
I think this highlights a serious deficiency in Windows. We have a (techincal) user account that we use for our system consisting of a windows service and websites, with the app pools configured to run as this user.
Our company has a security policy that after 5 bad passwords, it locks the account out.
Now finding out what locks out the account is practically impossible in a enterprise. When the account is locked out, the AD server should log from what process and what server caused the lock out.
I've looked into it and it (lock out tools) and it doesnt do this. only possible thing is a tool but you have to run it on the server and wait to see if any process is doing it. But in a enterprise with 1000s of servers thats impossible, you have to guess. Its crazy.
None of these answers were working for me. A couple of them would indeed print all the columns, but it would look sloppy. As in all the information was there, but it wasn't formatted correctly. I'm using a terminal inside of Neovim so I suspect that to be the reason.
This mini function does exactly what I need, just change df_data
in the two places it is for your dataframe name (col_range
is set to what pandas naturally shows, for me it is 5 but it could be bigger or smaller for you).
import math
col_range = 5
for _ in range(int(math.ceil(len(df_data.columns)/col_range))):
idx1 = _*col_range
idx2 = idx1+col_range
print(df_data.iloc[:, idx1:idx2].describe())
A minor modification like below worked for me when using it from within perl and system() call:
sftp {user}@{host} <<< $'put {local_file_path} {remote_file_path}'
Going with what you've started:
row = [[]]
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
tmp = []
for element in line[0:-1].split(','):
tmp.append(element)
row.append(tmp)
This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates
which is more suitable than distinct
for certain queries.
Suppose you have this DataFrame:
+-------+-------------+
|country| continent|
+-------+-------------+
| china| asia|
| brazil|south america|
| france| europe|
| china| asia|
+-------+-------------+
Here's how to take all the distinct countries and run a transformation:
df
.select("country")
.distinct
.withColumn("country", concat(col("country"), lit(" is fun!")))
.show()
+--------------+
| country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+
You can use dropDuplicates
instead of distinct
if you don't want to lose the continent
information:
df
.dropDuplicates("country")
.withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
.show(false)
+-------+-------------+------------------------------------+
|country|continent |description |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe |france is a country in europe |
|china |asia |china is a country in asia |
+-------+-------------+------------------------------------+
See here for more information about filtering DataFrames and here for more information on dropping duplicates.
Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.
You seem to misuse vim, but that's likely due to not being very familiar with it.
The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.
Here's a couple of use-cases:
But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.
I Thing you can Try this Code, It's Run for my Case:
<?php_x000D_
_x000D_
$con = mysqli_connect('localhost', 'root', 'NOTSHOWN', 'test');_x000D_
_x000D_
$filename = 'dbbackupmember.sql';_x000D_
$handle = fopen($filename, 'r+');_x000D_
$contents = fread($handle, filesize($filename));_x000D_
_x000D_
$sql = explode(";", $contents);_x000D_
foreach ($sql as $query) {_x000D_
$result = mysqli_query($con, $query);_x000D_
if ($result) {_x000D_
echo "<tr><td><br></td></tr>";_x000D_
echo "<tr><td>".$query."</td></tr>";_x000D_
echo "<tr><td><br></td></tr>";_x000D_
}_x000D_
}_x000D_
_x000D_
fclose($handle);_x000D_
echo "success";_x000D_
_x000D_
_x000D_
?>
_x000D_
Since you want the trailing string from the input, you can use %n
(number of characters consumed thus far) to get the position at which the trailing string starts. This avoids memory copies and buffer sizing issues, but comes at the cost that you may need to do them explicitly if you wanted a copy.
const char *input = "19 cool kid";
int age;
int nameStart = 0;
sscanf(input, "%d %n", &age, &nameStart);
printf("%s is %d years old\n", input + nameStart, age);
outputs:
cool kid is 19 years old
For simple input, like two prompts and two corresponding fixed responses, you could also use a "here document", the syntax of which looks like this:
test.sh <<!
y
pasword
!
The << prefixes a pattern, in this case '!'. Everything up to a line beginning with that pattern is interpreted as standard input. This approach is similar to the suggestion to pipe a multi-line echo into ssh, except that it saves the fork/exec of the echo command and I find it a bit more readable. The other advantage is that it uses built-in shell functionality so it doesn't depend on expect.
The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print
statement you can see that each file is found:
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print os.path.join(subdir, file)
If you still get errors when running the above, please provide the error message.
Updated for Python3
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
One way is using a template function in your directive:
...
template: function(tElem, tAttrs){
return '<div ng-include="' + tAttrs.template + '" />';
}
...
Check out the COPY command of Postgres:
It is probably worth adding that an insert iterator of any kind (std::back_insert_iterator
, std::front_insert_iterator
, std::insert_iterator
) is guaranteed to remain valid as long as all insertions are performed through this iterator and no other independent iterator-invalidating event occurs.
For example, when you are performing a series of insertion operations into a std::vector
by using std::insert_iterator
it is quite possible that these insertions will trigger vector reallocation, which will invalidate all iterators that "point" into that vector. However, the insert iterator in question is guaranteed to remain valid, i.e. you can safely continue the sequence of insertions. There's no need to worry about triggering vector reallocation at all.
This, again, applies only to insertions performed through the insert iterator itself. If iterator-invalidating event is triggered by some independent action on the container, then the insert iterator becomes invalidated as well in accordance with the general rules.
For example, this code
std::vector<int> v(10);
std::vector<int>::iterator it = v.begin() + 5;
std::insert_iterator<std::vector<int> > it_ins(v, it);
for (unsigned n = 20; n > 0; --n)
*it_ins++ = rand();
is guaranteed to perform a valid sequence of insertions into the vector, even if the vector "decides" to reallocate somewhere in the middle of this process. Iterator it
will obviously become invalid, but it_ins
will continue to remain valid.
Mr. Alien's answer is perfect, but anyway I don't recommend to use <div class="clear"></div>
because it just a hack which makes your markup dirty. This is useless empty div
in terms of bad structure and semantic, this also makes your code not flexible. In some browsers this div causes additional height and you have to add height: 0;
which even worse. But real troubles begin when you want to add background or border around your floated elements - it just will collapse because web was designed badly. I do recommend to wrap floated elements into container which has clearfix CSS rule. This is hack as well, but beautiful, more flexible to use and readable for human and SEO robots.
try{
if( driver.findElement(By.xpath("//div***")).isDisplayed()){
System.out.println("Element is Visible");
}
}
catch(NoSuchElementException e){
else{
System.out.println("Element is InVisible");
}
}
I don't why you would put a<p>
element there.
But another way of removing spaces in between the paragraphs is by declaring only one paragraph
<ul>
<p><li>HI THERE</li>
<br>
<li>ME</li>
</p>
</ul>
You can't, and you shouldn't.
Every other approach / alternative will only cause really bad user engagement.
That's my opinion.
Here is what worked for me (Angular 7):
First import HttpClientModule in your app.module.ts if you didn't:
import { HttpClientModule } from '@angular/common/http';
...
imports: [
HttpClientModule
],
Then change your service
@Injectable()
export class FooService {
to
@Injectable({
providedIn: 'root'
})
export class FooService {
Hope it helps.
Edit:
providedIn
Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:
'root' : The application-level injector in most apps.
'platform' : A special singleton platform injector shared by all applications on the page.
'any' : Provides a unique instance in every module (including lazy modules) that injects the token.
Be careful platform
is available only since Angular 9 (https://blog.angular.io/version-9-of-angular-now-available-project-ivy-has-arrived-23c97b63cfa3)
Read more about Injectable here: https://angular.io/api/core/Injectable
You can use it without doing anything special. If you have a local image called blah
you can do FROM blah
. If you do FROM blah
in your Dockerfile, but don't have a local image called blah
, then Docker will try to pull it from the registry.
In other words, if a Dockerfile does FROM ubuntu
, but you have a local image called ubuntu
different from the official one, your image will override it.
Here's yet another implementation that builds on some of the tips in here as well as the code from the Android developer site.
MainActivity.java
public class MainActivity extends Activity {
private ShakeDetector mShakeDetector;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ShakeDetector initialization
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector(new OnShakeListener() {
@Override
public void onShake() {
// Do stuff!
}
});
}
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onPause() {
mSensorManager.unregisterListener(mShakeDetector);
super.onPause();
}
}
ShakeDetector.java
package com.example.test;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
public class ShakeDetector implements SensorEventListener {
// Minimum acceleration needed to count as a shake movement
private static final int MIN_SHAKE_ACCELERATION = 5;
// Minimum number of movements to register a shake
private static final int MIN_MOVEMENTS = 2;
// Maximum time (in milliseconds) for the whole shake to occur
private static final int MAX_SHAKE_DURATION = 500;
// Arrays to store gravity and linear acceleration values
private float[] mGravity = { 0.0f, 0.0f, 0.0f };
private float[] mLinearAcceleration = { 0.0f, 0.0f, 0.0f };
// Indexes for x, y, and z values
private static final int X = 0;
private static final int Y = 1;
private static final int Z = 2;
// OnShakeListener that will be notified when the shake is detected
private OnShakeListener mShakeListener;
// Start time for the shake detection
long startTime = 0;
// Counter for shake movements
int moveCount = 0;
// Constructor that sets the shake listener
public ShakeDetector(OnShakeListener shakeListener) {
mShakeListener = shakeListener;
}
@Override
public void onSensorChanged(SensorEvent event) {
// This method will be called when the accelerometer detects a change.
// Call a helper method that wraps code from the Android developer site
setCurrentAcceleration(event);
// Get the max linear acceleration in any direction
float maxLinearAcceleration = getMaxCurrentLinearAcceleration();
// Check if the acceleration is greater than our minimum threshold
if (maxLinearAcceleration > MIN_SHAKE_ACCELERATION) {
long now = System.currentTimeMillis();
// Set the startTime if it was reset to zero
if (startTime == 0) {
startTime = now;
}
long elapsedTime = now - startTime;
// Check if we're still in the shake window we defined
if (elapsedTime > MAX_SHAKE_DURATION) {
// Too much time has passed. Start over!
resetShakeDetection();
}
else {
// Keep track of all the movements
moveCount++;
// Check if enough movements have been made to qualify as a shake
if (moveCount > MIN_MOVEMENTS) {
// It's a shake! Notify the listener.
mShakeListener.onShake();
// Reset for the next one!
resetShakeDetection();
}
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Intentionally blank
}
private void setCurrentAcceleration(SensorEvent event) {
/*
* BEGIN SECTION from Android developer site. This code accounts for
* gravity using a high-pass filter
*/
// alpha is calculated as t / (t + dT)
// with t, the low-pass filter's time-constant
// and dT, the event delivery rate
final float alpha = 0.8f;
// Gravity components of x, y, and z acceleration
mGravity[X] = alpha * mGravity[X] + (1 - alpha) * event.values[X];
mGravity[Y] = alpha * mGravity[Y] + (1 - alpha) * event.values[Y];
mGravity[Z] = alpha * mGravity[Z] + (1 - alpha) * event.values[Z];
// Linear acceleration along the x, y, and z axes (gravity effects removed)
mLinearAcceleration[X] = event.values[X] - mGravity[X];
mLinearAcceleration[Y] = event.values[Y] - mGravity[Y];
mLinearAcceleration[Z] = event.values[Z] - mGravity[Z];
/*
* END SECTION from Android developer site
*/
}
private float getMaxCurrentLinearAcceleration() {
// Start by setting the value to the x value
float maxLinearAcceleration = mLinearAcceleration[X];
// Check if the y value is greater
if (mLinearAcceleration[Y] > maxLinearAcceleration) {
maxLinearAcceleration = mLinearAcceleration[Y];
}
// Check if the z value is greater
if (mLinearAcceleration[Z] > maxLinearAcceleration) {
maxLinearAcceleration = mLinearAcceleration[Z];
}
// Return the greatest value
return maxLinearAcceleration;
}
private void resetShakeDetection() {
startTime = 0;
moveCount = 0;
}
// (I'd normally put this definition in it's own .java file)
public interface OnShakeListener {
public void onShake();
}
}
The ExtJS javascript library has a great class called Ext.util.TextMetrics that "provides precise pixel measurements for blocks of text so that you can determine exactly how high and wide, in pixels, a given block of text will be". You can either use it directly or view its source to code to see how this is done.
http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html
for simple Scroll, use following style
height: 200px; overflow: scroll;
and use this style class which div or section you want to show scroll
If you have (or create) a single string, you can use np.fromstring:
import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )
Note, x = ','.join(x)
transforms the x array to string '1.1, 2.2, 3.2'
. If you read a line from a txt file, each line will be already a string.
var res = (from element in list)
.OrderBy(x => x.F2).AsEnumerable()
.GroupBy(x => x.F1)
.Select()
Use .AsEnumerable() after OrderBy()
I also had same problem in past. All had happend after moving database files to new location and after updating mysql server. All tables with InnoDB engine disappeared from my database. I was trying to recreate them, but mysql told me 1146: Table 'xxx' doesn't exist
all the time until I had recreated my database and restarted mysql service.
I think there's a need to read about InnoDB table binaries.
Try this:
Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A2:L" & Lastrow).Select
Let's pretend that the value of Lastrow
is 50. When you use the following:
Range("A2:L2" & Lastrow).Select
Then it is selecting a range from A2 to L250.
One solution would be to use the plt.legend
function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc
keyterm. More information can be found at this website but I've also included an example showing how to place a legend:
ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2)
Note that because loc=2
, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize
, which will then make the legend smaller.
The whole point of a workspace is to group a set of related projects together that usually make up an application. The workspace framework comes down to the eclipse.core.resources
plugin and it naturally by design makes sense.
Projects have natures, builders are attached to specific projects and as you change resources in one project you can see in real time compile or other issues in projects that are in the same workspace. So the strategy I suggest is have different workspaces for different projects you work on but without a workspace in eclipse there would be no concept of a collection of projects and configurations and after all it's an IDE tool.
If that does not make sense ask how Net Beans or Visual Studio addresses this? It's the same theme. Maven is a good example, checking out a group of related maven projects into a workspace lets you develop and see errors in real time. If not a workspace what else would you suggest? An RCP application can be a different beast depending on what its used for but in the true IDE sense I don't know what would be a better solution than a workspace or context of projects. Just my thoughts. - Duncan
For example for all users (Builtin\Users), this method works fine - enjoy.
public static bool HasFolderWritePermission(string destDir)
{
if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
try
{
DirectorySecurity security = Directory.GetAccessControl(destDir);
SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
if(rule.IdentityReference == users)
{
FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
if(rights.AccessControlType == AccessControlType.Allow)
{
if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
}
}
}
return false;
}
catch
{
return false;
}
}
First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.
String.prototype.beginsWith = function (string) {
return(this.indexOf(string) === 0);
};
Then you use it like this. Caution! Makes the code extremely readable.
var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
// Do stuff here
}