print $input."<hr>".ereg_replace('/&/', ':::', $input);
becomes
print $input."<hr>".preg_replace('/&/', ':::', $input);
More example :
$mytext = ereg_replace('[^A-Za-z0-9_]', '', $mytext );
is changed to
$mytext = preg_replace('/[^A-Za-z0-9_]/', '', $mytext );
While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:
I configured my server app to set a custom response header (X-Response-Url
) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url")
is defined, in which case it compares it to the url that it originally requested via $.ajax()
. If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.
This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.
On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:
import pyramid.events
@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
request = event.request
if request.is_xhr:
event.response.headers['X-Response-URL'] = request.url
For those using bootstrap 4 beta you can add max-width on your navbar link to have control on the size of your logo with img-fluid class on the image element.
<a class="navbar-brand" href="#" style="max-width: 30%;">
<img src="images/logo.png" class="img-fluid">
</a>
You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.
LIKE 'WC[[]R]S123456'
or
LIKE 'WC\[R]S123456' ESCAPE '\'
Should work.
I figured it out from the PostgreSQL docs, the exact syntax is:
ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);
Thanks Fred.
The foreign keys in your schema (on Account_Name
and Account_Type
) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.
There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.
Use Thread.sleep(2000); //2000 for 2 seconds
Run: python -c "import ssl; print(ssl.get_default_verify_paths())"
to check the current paths which are used to verify the certificate. Add your company's root certificate to one of those.
The path openssl_capath_env
points to the environment variable: SSL_CERT_DIR
.
If SSL_CERT_DIR
doesn't exist, you will need to create it and point it to a valid folder within your filesystem. You can then add your certificate to this folder to use it.
You could try wrapping the contents of the row in a <span>
and having your selector be $('#detailed_edit_row span');
- a bit hackish, but I just tested it and it works. I also tried the table-row
suggestion above and it didn't seem to work.
update: I've been playing around with this problem, and from all indications jQuery needs the object it performs slideDown on to be a block element. So, no dice. I was able to conjure up a table where I used slideDown on a cell and it didn't affect the layout at all, so I am not sure how yours is set up. I think your only solution is to refactor the table in such a way that it's ok with that cell being a block, or just .show();
the damn thing. Good luck.
I ran into this issue and when I read in the top voted answer:
HEAD is the symbolic name for the currently checked out commit.
I thought: Ah-ha! If HEAD
is the symbolic name for the currenlty checkout commit, I can reconcile it against master
by rebasing it against master
:
git rebase HEAD master
This command:
master
HEAD
back to the point HEAD
diverged from master
master
The end result is that all commits that were in HEAD
but not master
are then also in master
. master
remains checked out.
Regarding the remote:
a couple of the commits I'd killed in the rebase got pushed, and the new ones committed locally aren't there.
The remote history can no longer be fast-forwarded using your local history. You'll need to force-push (git push -f
) to overwrite the remote history. If you have any collaborators, it usually makes sense to coordinate this with them so everyone is on the same page.
After you push master
to remote origin
, your remote tracking branch origin/master
will be updated to point to the same commit as master
.
for example when you call a function that returns Generic Collections and you don't specify the generic parameters yourself.
for a function
List<String> getNames()
List names = obj.getNames();
will generate this error.
To solve it you would just add the parameters
List<String> names = obj.getNames();
serializeArray already does exactly that. You just need to massage the data into your required format:
function objectifyForm(formArray) {
//serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
Watch out for hidden fields which have the same name as real inputs as they will get overwritten.
Custom format
[>=1000]#,##0,"K";0
will give you:
Note the comma between the zero and the "K". To display millions or billions, use two or three commas instead.
From SQL Server 2012 and onwards I think this will do the trick:
SELECT DISTINCT
o.OrderNumber ,
FIRST_VALUE(li.Quantity) OVER ( PARTITION BY o.OrderNumber ORDER BY li.Description ) AS Quantity ,
FIRST_VALUE(li.Description) OVER ( PARTITION BY o.OrderNumber ORDER BY li.Description ) AS Description
FROM Orders AS o
INNER JOIN LineItems AS li ON o.OrderID = li.OrderID
The Quassnoi query with a change for large table. Parents with more childs then 10: Formating as str(5) the row_number()
WITH q AS ( SELECT m.*, CAST(str(ROW_NUMBER() OVER (ORDER BY m.ordernum),5) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc FROM #t m WHERE ParentID =0 UNION ALL SELECT m.*, q.bc + '.' + str(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.ordernum),5) COLLATE Latin1_General_BIN FROM #t m JOIN q ON m.parentID = q.DBID ) SELECT * FROM q ORDER BY bc
I had very similar issue, removing entire node_modules
folder and re-installing worked for me. Learned this trick from the IT Crowd show!
rm -rf node_modules
npm install
In C++ the stack memory is where local variables get stored/constructed. The stack is also used to hold parameters passed to functions.
The stack is very much like the std::stack class: you push parameters onto it and then call a function. The function then knows that the parameters it expects can be found on the end of the stack. Likewise, the function can push locals onto the stack and pop them off it before returning from the function. (caveat - compiler optimizations and calling conventions all mean things aren't this simple)
The stack is really best understood from a low level and I'd recommend Art of Assembly - Passing Parameters on the Stack. Rarely, if ever, would you consider any sort of manual stack manipulation from C++.
Generally speaking, the stack is preferred as it is usually in the CPU cache, so operations involving objects stored on it tend to be faster. However the stack is a limited resource, and shouldn't be used for anything large. Running out of stack memory is called a Stack buffer overflow. It's a serious thing to encounter, but you really shouldn't come across one unless you have a crazy recursive function or something similar.
Heap memory is much as rskar says. In general, C++ objects allocated with new, or blocks of memory allocated with the likes of malloc end up on the heap. Heap memory almost always must be manually freed, though you should really use a smart pointer class or similar to avoid needing to remember to do so. Running out of heap memory can (will?) result in a std::bad_alloc.
These are the installation i had to run in order to make it work on fedora 22 :-
glibc-2.21-7.fc22.i686
alsa-lib-1.0.29-1.fc22.i686
qt3-3.3.8b-64.fc22.i686
libusb-1:0.1.5-5.fc22.i686
Any one can try this command to truncate any file in linux system
This will surely work in any format :
truncate -s 0 file.txt
Create an another <tr>
just below and add some space or height to content of <td>
Checkout the fiddle for example
Sven has shown how to use the class gaussian_kde
from Scipy, but you will notice that it doesn't look quite like what you generated with R. This is because gaussian_kde
tries to infer the bandwidth automatically. You can play with the bandwidth in a way by changing the function covariance_factor
of the gaussian_kde
class. First, here is what you get without changing that function:
However, if I use the following code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = gaussian_kde(data)
xs = np.linspace(0,8,200)
density.covariance_factor = lambda : .25
density._compute_covariance()
plt.plot(xs,density(xs))
plt.show()
I get
which is pretty close to what you are getting from R. What have I done? gaussian_kde
uses a changable function, covariance_factor
to calculate its bandwidth. Before changing the function, the value returned by covariance_factor for this data was about .5. Lowering this lowered the bandwidth. I had to call _compute_covariance
after changing that function so that all of the factors would be calculated correctly. It isn't an exact correspondence with the bw parameter from R, but hopefully it helps you get in the right direction.
@takrl: The default setting for this option is:
java -XX:+UseConcMarkSweepGC
which means, this option is not active by default. So when you say you used the option
"+XX:UseConcMarkSweepGC
"
I assume you were using this syntax:
java -XX:+UseConcMarkSweepGC
which means you were explicitly activating this option.
For the correct syntax and default settings of Java HotSpot VM Options
@ this
document
I'm consciously writing this answer to an old question with this in mind, because the other answers didn't help me.
I got the Illegal Instruction: 4
while running the binary on the same system I had compiled it on, so -mmacosx-version-min
didn't help.
I was using gcc in Code Blocks 16 on Mac OS X 10.11.
However, turning off all of Code Blocks' compiler flags for optimization worked. So look at all the flags Code Blocks set (right-click on the Project -> "Build Properties") and turn off all the flags you are sure you don't need, especially -s
and the -O
flags for optimization. That did it for me.
I tried to follow the example given in both answers and it might be worth noting that it appears as though std::filesystem::directory_entry
has been changed to not have an overload of the <<
operator. Instead of std::cout << p << std::endl;
I had to use the following to be able to compile and get it working:
#include <iostream>
#include <filesystem>
#include <string>
namespace fs = std::filesystem;
int main() {
std::string path = "/path/to/directory";
for(const auto& p : fs::directory_iterator(path))
std::cout << p.path() << std::endl;
}
trying to pass p
on its own to std::cout <<
resulted in a missing overload error.
One potential solution
Thanks to Alan Haggai Alavi's solution I came up with the following potential workflow:
Step 1:
git fetch origin
Step 2:
git checkout -b localTempOfOriginMaster origin/master
git difftool HEAD~3 HEAD~2
git difftool HEAD~2 HEAD~1
git difftool HEAD~1 HEAD~0
Step 3:
git checkout master
git branch -D localTempOfOriginMaster
git merge origin/master
You can use:
input[type=text]
{
/*Styles*/
}
Define your common style attributes inside this. and for extra style you can add a class then.
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
To find all files modified in the last 24 hours (last full day) in a particular specific directory and its sub-directories:
find /directory_path -mtime -1 -ls
Should be to your liking
The -
before 1
is important - it means anything changed one day or less ago.
A +
before 1
would instead mean anything changed at least one day ago, while having nothing before the 1
would have meant it was changed exacted one day ago, no more, no less.
Change the = to : to
fix the error.
var makeRequest = function(message) {<br>
var options = {<br>
host: 'localhost',<br>
port : 8080,<br>
path : '/',<br>
method: 'POST'<br>
}
#include <stdio.h>
static void (*f[2])(int);
static void p(int i)
{
printf("%d\n", i);
}
static void e(int i)
{
exit(0);
}
static void r(int i)
{
f[(i-1)/1000](i);
r(i+1);
}
int main(int argc, char* argv[])
{
f[0] = p;
f[1] = e;
r(1);
}
Previous answers don't account for the fact that you've overloaded the equals operator and are using that to test for the sought element. In that case, your code would look like this:
list.Find(x => x == objectToFind);
Or, if you don't like lambda syntax, and have overriden object.Equals(object) or have implemented IEquatable<T>, you could do this:
list.Find(objectToFind.Equals);
This works for me:
ln -s /usr/local/Cellar/mysql/5.6.22/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
I solved this issue by adding this line
android.overridePathCheck=true
to
gradle.properties
As this message said
This warning can be disabled by using
the command line flag -Dcom.android.build.gradle.overridePathCheck=true,
or adding the line
'com.android.build.gradle.overridePathCheck=true'
to gradle.properties file in the project directory.
I hope this will be more useful for future scope contain auto complete Google API feature with latitude and longitude
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
Complete View
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete With Latitude & Longitude </title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#pac-input {
background-color: #fff;
padding: 0 11px 0 13px;
width: 400px;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
text-overflow: ellipsis;
}
#pac-input:focus {
border-color: #4d90fe;
margin-left: -1px;
padding-left: 14px; /* Regular padding-left + 1. */
width: 401px;
}
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script>
function initialize() {
var address = (document.getElementById('pac-input'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
/*********************************************************************/
/* var address contain your autocomplete address *********************/
/* place.geometry.location.lat() && place.geometry.location.lat() ****/
/* will be used for current address latitude and longitude************/
/*********************************************************************/
document.getElementById('lat').innerHTML = place.geometry.location.lat();
document.getElementById('long').innerHTML = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="lat"></div>
<div id="long"></div>
</body>
</html>
Try this :
import urllib, urllib2, json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
#print json_object['results']
if json_object['team'] == []:
print 'No Data!'
else:
for rows in json_object['team']:
print 'Team ID:' + rows['team_id']
print 'Team Name:' + rows['team_name']
print 'Team URL:' + rows['team_icon_url']
If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:
//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);
That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...
Hope this helps - Luke
Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:
df['column_name'].astype(np.float).astype("Int32")
NB: You have to go through numpy float first and then to nullable Int32, for some reason.
The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.
Here is an alternative, that does not use enumerate() to create tuples (as in SilentGhost's original answer).
This seems more readable to me. (Maybe I'd feel differently if I was in the habit of using enumerate.) CAVEAT: I have not tested performance of the two approaches.
# Returns a new list. "lst" is not modified.
def delete_by_indices(lst, indices):
indices_as_set = set(indices)
return [ lst[i] for i in xrange(len(lst)) if i not in indices_as_set ]
NOTE: Python 2.7 syntax. For Python 3, xrange
=> range
.
Usage:
lst = [ 11*x for x in xrange(10) ]
somelist = delete_by_indices( lst, [0, 4, 5])
somelist:
[11, 22, 33, 66, 77, 88, 99]
--- BONUS ---
Delete multiple values from a list. That is, we have the values we want to delete:
# Returns a new list. "lst" is not modified.
def delete__by_values(lst, values):
values_as_set = set(values)
return [ x for x in lst if x not in values_as_set ]
Usage:
somelist = delete__by_values( lst, [0, 44, 55] )
somelist:
[11, 22, 33, 66, 77, 88, 99]
This is the same answer as before, but this time we supplied the VALUES to be deleted [0, 44, 55]
.
@PropertySource
can be configured by factory
argument. So you can do something like:
@PropertySource(value = "classpath:application-test.yml", factory = YamlPropertyLoaderFactory.class)
Where YamlPropertyLoaderFactory
is your custom property loader:
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null){
return super.createPropertySource(name, resource);
}
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), null);
}
}
Inspired by https://stackoverflow.com/a/45882447/4527110
I am trying with the below. This seems to be working fine. Are there any limitations to this approach? Please confirm.
var now=new Date(); // Sun Apr 02 2017 2:00:00 GMT+1000 (AEST)
var gmtRe = /GMT([\-\+]?\d{4})/;
var tz = gmtRe.exec(now)[1]; // +1000
var hour=tz/100; // 10
var min=tz%100; // 0
now.setHours(now.getHours()-hour);
now.setMinutes(now.getMinutes()-min); // Sat Apr 01 2017 16:00:00 GMT
In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.
int random_int ( int $min , int $max )
random_int — Generates cryptographically secure pseudo-random integers
which basically makes previous answers obsolete.
unbind()
was deprecated in jQuery 3
, use the off()
method instead:
$("a").off("click");
This works even if you are on 32-bit PHP:
list($msec, $sec) = explode(' ', microtime());
$time_milli = $sec.substr($msec, 2, 3); // '1491536422147'
$time_micro = $sec.substr($msec, 2, 6); // '1491536422147300'
Note this doesn't give you integers, but strings. However this works fine in many cases, for example when building URLs for REST requests.
If you need integers, 64-bit PHP is mandatory.
Then you can reuse the above code and cast to (int):
list($msec, $sec) = explode(' ', microtime());
// these parentheses are mandatory otherwise the precedence is wrong!
// ? ?
$time_milli = (int) ($sec.substr($msec, 2, 3)); // 1491536422147
$time_micro = (int) ($sec.substr($msec, 2, 6)); // 1491536422147300
Or you can use the good ol' one-liners:
$time_milli = (int) round(microtime(true) * 1000); // 1491536422147
$time_micro = (int) round(microtime(true) * 1000000); // 1491536422147300
@All the issue is because of the latest major breaking changes in the google play service and firebase June 17, 2019 release.
If you are on Ionic or Cordova project. Please go through all the plugins where it has dependency google play service and firebase service with + mark
Example:
In my firebase cordova integration I had com.google.firebase:firebase-core:+ com.google.firebase:firebase-messaging:+ So the plus always downloading the latest release which was causing error. Change + with version number as per the March 15, 2019 release https://developers.google.com/android/guides/releases
Make sure to replace + symbols with actual version in build.gradle file of cordova library
I've had same problem, and this is how I fixed it:
Just throw this in your web.config:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE" />
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type" />
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Kindly ensure, the other columns are not constrained to accept Not null
values, hence while creating columns in table just ignore "Not Null" syntax. eg
Create Table Table_Name(
col1 DataType,
col2 DataType);
You can then insert multiple row values in any of the columns you want to. For instance:
Insert Into TableName(columnname)
values
(x),
(y),
(z);
and so on…
Hope this helps.
very simple just use getSelectedItem();
eg :
ArrayAdapter<CharSequence> type=ArrayAdapter.createFromResource(this,R.array.admin_typee,android.R.layout.simple_spinner_dropdown_item);
type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainType.setAdapter(type);
String group=mainType.getSelectedItem().toString();
the above method returns an string value
in the above the R.array.admin_type
is an string resource file in values
just create an .xml file in values>>strings
I can see that the init has the following override:
Init(CALLBACK_FUNC_EX callback_func, void * callback_parm)
where CALLBACK_FUNC_EX
is
typedef void (*CALLBACK_FUNC_EX)(int, void *);
By default, docker uses AF_INET6 sockets which can be used for both IPv4 and IPv6 connections. This causes netstat to report an IPv6 address for the listening address.
From RedHat https://access.redhat.com/solutions/3114021
FIXNUM_MAX = (2**(0.size * 8 -2) -1)
FIXNUM_MIN = -(2**(0.size * 8 -2))
I wanted to share a part of the issue I had because it is the first google result.
I installed Android Studio, when I tried to install my first SDK from the SDK Management windows I got the error that I didn't have any SDK installed. I tried to look on the internet to manually download the .zip,manualy create the folder, no luck what so ever.
When I tried to run the Android Studio as an administrator it detected I didn't have any SDK and prompt me right away at startup to download a SDK.
It prints the byte
in Hexadecimal format.
No format string: 13
'X2' format string: 0D
http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx
Adding images to the drawable folder is pretty simple. Just follow these steps:
Your image will be saved inside drawable and you can use it.
the correct syntax is -
with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;
the give below code works great. It removes all rows except header row. So this code really t
$("#Your_Table tr>td").remove();
Posting a string:
curl -d "String to post" "http://www.example.com/target"
Posting the contents of a file:
curl -d @soap.xml "http://www.example.com/target"
I like the answer of Ed S., but this only works for fixed size arrays and not when the arrays are defined as pointers.
So, the C++ solution where the arrays are defined as pointers:
#include<algorithm>
...
const int bufferSize = 10;
char* origArray, newArray;
std::copy(origArray, origArray + bufferSize, newArray);
Note: No need to deduct buffersize
with 1:
- Copies all elements in the range [first, last) starting from first and proceeding to last - 1
CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.
Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html
With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/
fmt.Sprintf("%v",value);
If you know the specific type of value use the corresponding formatter for example %d
for int
More info - fmt
int hr=Time.valueOf(LocalTime.now()).getHours();
int minutes=Time.valueOf(LocalTime.now()).getMinutes();
These functions will return int values in hours and minutes.
Jalf already linked to it, but the GOTW puts it quite nicely why exception specifications are not as useful as one might hope:
int Gunc() throw(); // will throw nothing (?)
int Hunc() throw(A,B); // can only throw A or B (?)
Are the comments correct? Not quite.
Gunc()
may indeed throw something, andHunc()
may well throw something other than A or B! The compiler just guarantees to beat them senseless if they do… oh, and to beat your program senseless too, most of the time.
That's just what it comes down to, you probably just will end up with a call to terminate()
and your program dying a quick but painful death.
The GOTWs conclusion is:
So here’s what seems to be the best advice we as a community have learned as of today:
- Moral #1: Never write an exception specification.
- Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.
Some more information on the F9 keyboard shortcuts for calculation in Excel
This happens because you use the savedValue
in the onCreate()
method. The savedValue
is updated in onRestoreInstanceState()
method, but onRestoreInstanceState()
is called after the onCreate()
method. You can either:
savedValue
in onCreate()
method, orsavedValue
in onRestoreInstanceState()
method.But I suggest you to use the first approach, making the code like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int display_mode = getResources().getConfiguration().orientation;
if (display_mode == 1) {
setContentView(R.layout.main_grid);
mGrid = (GridView) findViewById(R.id.gridview);
mGrid.setColumnWidth(95);
mGrid.setVisibility(0x00000000);
// mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
} else {
setContentView(R.layout.main_grid_land);
mGrid = (GridView) findViewById(R.id.gridview);
mGrid.setColumnWidth(95);
Log.d("Mode", "land");
// mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
}
if (savedInstanceState != null) {
savedUser = savedInstanceState.getString("TEXT");
} else {
savedUser = ""
}
Log.d("savedUser", savedUser);
if (savedUser.equals("admin")) { //value 0
adapter.setApps(appManager.getApplications());
} else if (savedUser.equals("prof")) { //value 1
adapter.setApps(appManager.getTeacherApplications());
} else {// default value
appManager = new ApplicationManager(this, getPackageManager());
appManager.loadApplications(true);
bindApplications();
}
}
The Basics:
String
is an immutable class, it can't be changed.
StringBuilder
is a mutable class that can be appended to, characters replaced or removed and ultimately converted to a String
StringBuffer
is the original synchronized version of StringBuilder
You should prefer StringBuilder
in all cases where you have only a single thread accessing your object.
The Details:
Also note that StringBuilder/Buffers
aren't magic, they just use an Array as a backing object and that Array has to be re-allocated when ever it gets full. Be sure and create your StringBuilder/Buffer
objects large enough originally where they don't have to be constantly re-sized every time .append()
gets called.
The re-sizing can get very degenerate. It basically re-sizes the backing Array to 2 times its current size every time it needs to be expanded. This can result in large amounts of RAM getting allocated and not used when StringBuilder/Buffer
classes start to grow large.
In Java String x = "A" + "B";
uses a StringBuilder
behind the scenes. So for simple cases there is no benefit of declaring your own. But if you are building String
objects that are large, say less than 4k, then declaring StringBuilder sb = StringBuilder(4096);
is much more efficient than concatenation or using the default constructor which is only 16 characters. If your String
is going to be less than 10k then initialize it with the constructor to 10k to be safe. But if it is initialize to 10k then you write 1 character more than 10k, it will get re-allocated and copied to a 20k array. So initializing high is better than to low.
In the auto re-size case, at the 17th character the backing Array gets re-allocated and copied to 32 characters, at the 33th character this happens again and you get to re-allocated and copy the Array into 64 characters. You can see how this degenerates to lots of re-allocations and copies which is what you really are trying to avoid using StringBuilder/Buffer
in the first place.
This is from the JDK 6 Source code for AbstractStringBuilder
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}
A best practice is to initialize the StringBuilder/Buffer
a little bit larger than you think you are going to need if you don't know right off hand how big the String
will be but you can guess. One allocation of slightly more memory than you need is going to be better than lots of re-allocations and copies.
Also beware of initializing a StringBuilder/Buffer
with a String
as that will only allocated the size of the String + 16 characters, which in most cases will just start the degenerate re-allocation and copy cycle that you are trying to avoid. The following is straight from the Java 6 source code.
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
If you by chance do end up with an instance of StringBuilder/Buffer
that you didn't create and can't control the constructor that is called, there is a way to avoid the degenerate re-allocate and copy behavior. Call .ensureCapacity()
with the size you want to ensure your resulting String
will fit into.
The Alternatives:
Just as a note, if you are doing really heavy String
building and manipulation, there is a much more performance oriented alternative called Ropes.
Another alternative, is to create a StringList
implemenation by sub-classing ArrayList<String>
, and adding counters to track the number of characters on every .append()
and other mutation operations of the list, then override .toString()
to create a StringBuilder
of the exact size you need and loop through the list and build the output, you can even make that StringBuilder
an instance variable and 'cache' the results of .toString()
and only have to re-generate it when something changes.
Also don't forget about String.format()
when building fixed formatted output, which can be optimized by the compiler as they make it better.
I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).
<input type="text" value="<script>alert('test');</script>" />
Produces:
You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value
attribute.
var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";
Non of the answers worked for me, so I've managed to do it like that:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("your content type here"));
headers.set("Content-Disposition", "attachment; filename=fileName.jpg");
headers.setContentLength(fileContent.length);
return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
Setting Content-Disposition
header I was able to download the file with the @ResponseBody
annotation on my method.
Props to @Nick-Harrison for his answer:
$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});
I was wondering what the parseInt() is for there? I've simplified it to this with no problems...
$("input[data-val-length-max]").each(function (index, element) {
element.setAttribute("maxlength", element.getAttribute("data-val-length-max"))
});
I would have commented on Nicks answer but don't have enough rep yet.
I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.
Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )
sqs = boto3.client('sqs')
s3 = boto3.resource('s3')
Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.
# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')
# you have two choices of create custom client session.
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')
Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.
import boto3
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket')
video_bucket = video_s3.Bucket('videobucket')
# just pass the instantiated bucket object
def list_bucket_contents(bucket):
for object in bucket.objects.all():
print(object.key)
list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)
Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.
For example, if you only deal with the default session, this looks similar to boto3.resource.
import boto3
s3 = boto3.client('s3')
def list_bucket_contents(bucket_name):
for object in s3.list_objects_v2(Bucket=bucket_name) :
print(object.key)
list_bucket_contents('Mybucket')
However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.
import boto3
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')
# you must pass boto3.Session.client and the bucket name
def list_bucket_contents(s3session, bucket_name):
response = s3session.list_objects_v2(Bucket=bucket_name)
if 'Contents' in response:
for obj in response['Contents']:
print(obj['key'])
list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket')
if you have for example config folder under Resources folder I tried this Class working perfectly hope be useful
File file = ResourceUtils.getFile("classpath:config/sample.txt")
//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
As Anton Gogolev noted, FileStream reads 4096 bytes at a time by default, But you can specify any other value using the FileStream constructor:
new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 16 * 1024 * 1024)
Note that Brad Abrams from Microsoft wrote in 2004:
there is zero benefit from wrapping a BufferedStream around a FileStream. We copied BufferedStream’s buffering logic into FileStream about 4 years ago to encourage better default performance
$date = new \DateTime("now", new \DateTimeZone('Asia/Calcutta') );
$day = $date->format('D');
$weekendnaame = weekedName();
$weekid =$weekendnaame[$day];
$dayname = 0;
$weekiarray = weekendArray($weekid);
foreach ($weekiarray as $key => $value) {
if (in_array($value, $request->get('week_id')))
{
$dayname = $key+1;
break;
}
}
weeknDate($dayname),
function weeked(){
$week = array("1"=>"Sunday", "2"=>"Monday", "3"=>"Tuesday", "4"=>"Wednesday", "5"=>"Thursday", "6"=>"Friday", "7"=>"Saturday");
return $week;
}
function weekendArray($day){
$favcolor = $day;
switch ($favcolor) {
case 1:
$array = array(2,3,4,5,6,7,1);
break;
case 2:
$array = array(3,4,5,6,7,1,2);
break;
case 3:
$array = array(4,5,6,7,1,2,3);
break;
case 4:
$array = array(5,6,7,1,2,3,4);
break;
case 5:
$array = array(6,7,1,2,3,4,5);
break;
case 6:
$array = array(7,1,2,3,4,5,6);
break;
case 7:
$array = array(1,2,3,4,5,6,7);
break;
default:
$array = array(1,2,3,4,5,6,7);
}
return $array;
}
function weekedName(){
$week = array("Sun"=>0,"Mun"=>1,"Tue"=>3,"Wed"=>4,"Thu"=>5,"Fri"=>6,"Sat"=>7);
return $week;
}
CSS:
table {
table-layout:fixed;
}
Update with CSS from the comments:
td {
overflow: hidden;
text-overflow: ellipsis;
word-wrap: break-word;
}
For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):
@media only screen and (max-width: 480px) {
/* horizontal scrollbar for tables if mobile screen */
.tablemobile {
overflow-x: auto;
display: block;
}
}
Sufficient enough.
This would have worked too. The first quoted pair are interpreted as a window title name in the start command.
start "" "myfile.txt"
start "" "myshortcut.lnk"
If you don't give an aspect
argument to imshow
, it will use the value for image.aspect
in your matplotlibrc
. The default for this value in a new matplotlibrc
is equal
.
So imshow
will plot your array with equal aspect ratio.
If you don't need an equal aspect you can set aspect
to auto
imshow(random.rand(8, 90), interpolation='nearest', aspect='auto')
which gives the following figure
If you want an equal aspect ratio you have to adapt your figsize
according to the aspect
fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()
which gives you:
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
Also, cursor.lastrowid
(a dbapi/PEP249 extension supported by MySQLdb):
>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)
cursor.lastrowid
is somewhat cheaper than connection.insert_id()
and much cheaper than another round trip to MySQL.
That should work. I am not sure why it's failing. You're quoting your variables properly. What happens if you use this script with double [[
]]
?
if [[ -d $PASSED ]]; then
echo "$PASSED is a directory"
elif [[ -f $PASSED ]]; then
echo "$PASSED is a file"
else
echo "$PASSED is not valid"
exit 1
fi
Double square brackets is a bash extension to [ ]
. It doesn't require variables to be quoted, not even if they contain spaces.
Also worth trying: -e
to test if a path exists without testing what type of file it is.
just indent your code correctly:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
return 0
else:
return period
You need to understand that the break
statement in your example will exit the infinite loop you've created with while True
. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the break
statement by a return
statement.
Following your idea to use an infinite loop, this is the best way to write it:
def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
period = 0
break
return period
Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?
x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)
TL;DR
// Run these commands (Tested on Ubuntu 17.04 & above) curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list sudo apt-get update && sudo apt-get install yarn
Additional Notes: Check out this official documentation/guide for installing yarn on other Ubuntu versions & to take care of additional cmdtest
errors. https://yarnpkg.com/lang/en/docs/install/#debian-stable
If you don't have curl
installed you can install it using sudo apt install curl
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
While inserting multiple rows with a single INSERT
statement is generally faster, it leads to a more complicated and often unsafe code. Below I present the best practices when it comes to inserting multiple records in one go using PHP.
To insert multiple new rows into the database at the same time, one needs to follow the following 3 steps:
INSERT
statementUsing database transactions ensures that the data is saved in one piece and significantly improves performance.
PDO is the most common choice of database extension in PHP and inserting multiple records with PDO is quite simple.
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
// Start transaction
$pdo->beginTransaction();
// Prepare statement
$stmt = $pdo->prepare('INSERT
INTO `pxlot` (realname,email,address,phone,status,regtime,ip)
VALUES (?,?,?,?,?,?,?)');
// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
// All seven parameters are passed into the execute() in a form of an array
$stmt->execute([$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
}
// Commit the data into the database
$pdo->commit();
The mysqli extension is a little bit more cumbersome to use but operates on very similar principles. The function names are different and take slightly different parameters.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'user', 'password', 'database');
$mysqli->set_charset('utf8mb4');
// Start transaction
$mysqli->begin_transaction();
// Prepare statement
$stmt = $mysqli->prepare('INSERT
INTO `pxlot` (realname,email,address,phone,status,regtime,ip)
VALUES (?,?,?,?,?,?,?)');
// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
// mysqli doesn't accept bind in execute yet, so we have to bind the data first
// The first argument is a list of letters denoting types of parameters. It's best to use 's' for all unless you need a specific type
// bind_param doesn't accept an array so we need to unpack it first using '...'
$stmt->bind_param('sssssss', ...[$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
$stmt->execute();
}
// Commit the data into the database
$mysqli->commit();
Both extensions offer the ability to use transactions. Executing prepared statement with transactions greatly improves performance, but it's still not as good as a single SQL query. However, the difference is so negligible that for the sake of conciseness and clean code it is perfectly acceptable to execute prepared statements multiple times. If you need a faster option to insert many records into the database at once, then chances are that PHP is not the right tool.
Do you really need an object? What about:
$myArray[] = array("name" => "my name");
Just use a two-dimensional array.
Output (var_dump):
array(1) {
[0]=>
array(1) {
["name"]=>
string(7) "my name"
}
}
You could access your last entry like this:
echo $myArray[count($myArray) - 1]["name"];
You can use this one:
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
It will show a graphical representation of the current sub-directories without files in a few seconds, e.g. in /var/cache/:
.
|-apache2
|---mod_cache_disk
|-apparmor
|-apt
|---archives
|-----partial
|-apt-xapian-index
|---index.1
|-dbconfig-common
|---backups
|-debconf
It stands for
Microsoft's Common Object Runtime Library
and it is the primary assembly for the Framework Common Library.
It contains the following namespaces:
System
System.Collections
System.Configuration.Assemblies
System.Diagnostics
System.Diagnostics.SymbolStore
System.Globalization
System.IO
System.IO.IsolatedStorage
System.Reflection
System.Reflection.Emit
System.Resources
System.Runtime.CompilerServices
System.Runtime.InteropServices
System.Runtime.InteropServices.Expando
System.Runtime.Remoting
System.Runtime.Remoting.Activation
System.Runtime.Remoting.Channels
System.Runtime.Remoting.Contexts
System.Runtime.Remoting.Lifetime
System.Runtime.Remoting.Messaging
System.Runtime.Remoting.Metadata
System.Runtime.Remoting.Metadata.W3cXsd2001
System.Runtime.Remoting.Proxies
System.Runtime.Remoting.Services
System.Runtime.Serialization
System.Runtime.Serialization.Formatters
System.Runtime.Serialization.Formatters.Binary
System.Security
System.Security.Cryptography
System.Security.Cryptography.X509Certificates
System.Security.Permissions
System.Security.Policy
System.Security.Principal
System.Text
System.Threading
Microsoft.Win32
Interesting info about MSCorlib:
.NET 1.1
assembly will reference the 1.1 mscorlib
but will use
the 2.0 mscorlib at runtime (due to hard-coded version redirects in
theruntime itself)MSCorlib 2.0
alone is in GAC whereas 1.x version live inside framework folder Gender :<br>
<input type="radio" name="g" value="male" <?php echo ($g=='Male')?'checked':'' ?>>male <br>
<input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
<?php echo $errors['g'];?>
FormData method .entries
and the for of
expression is not supported in IE11 and Safari.
Here is a simplier version to support Safari, Chrome, Firefox and Edge
function formDataToJSON(formElement) {
var formData = new FormData(formElement),
convertedJSON = {};
formData.forEach(function(value, key) {
convertedJSON[key] = value;
});
return convertedJSON;
}
Warning: this answer doesn't work in IE11.
FormData doesn't have a forEach
method in IE11.
I'm still searching for a final solution to support all major browsers.
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);
line 2 should be replaced with
byte[] binData = b.ReadBytes(file.ContentLength);
Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.
function cleanInt(x) {
x = Number(x);
return x >= 0 ? Math.floor(x) : Math.ceil(x);
}
See results of below test cases.
console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));
result:
CleanInt: NaN ParseInt: NaN
CleanInt: NaN ParseInt: 123
CleanInt: 234 ParseInt: 234
CleanInt: -679 ParseInt: -679
CleanInt: 897 ParseInt: 897
CleanInt: Infinity ParseInt: NaN
You could use KEY
unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.
All work perfectly :)
NSString *test = @"test";
unichar a;
int index = 5;
@try {
a = [test characterAtIndex:index];
}
@catch (NSException *exception) {
NSLog(@"%@", exception.reason);
NSLog(@"Char at index %d cannot be found", index);
NSLog(@"Max index is: %lu", [test length] - 1);
}
@finally {
NSLog(@"Finally condition");
}
Log:
[__NSCFConstantString characterAtIndex:]: Range or index out of bounds
Char at index 5 cannot be found
Max index is: 3
Finally condition
I suppose your html page is hosted on a different port. Same origin policy requires in most browsers that the loaded file be on the same port than the loading file.
you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.
declare a HashMap somewhere in your class:
private static HashMap<String, Integer> images = null;
//Then initialize it in your constructor:
public myClass() {
if (images == null) {
images = new HashMap<String, Integer>();
images.put("Human1Arm", R.drawable.human_one_arm);
// for all your images - don't worry, this is really fast and will only happen once
}
}
Now for access -
String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity)
marks the entity as Deleted
in the context. (It's EntityState
is Deleted
after that.) If you call SaveChanges
afterwards EF sends a SQL DELETE
statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity)
marks the relationship between parent and childEntity
as Deleted
. If the childEntity
itself is deleted from the database and what exactly happens when you call SaveChanges
depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL
values, this foreign will be set to null and if you call SaveChanges
this NULL
value for the childEntity
will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE
statement. No DELETE
statement occurs.
If the relationship is required (the FK doesn't allow NULL
values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject
then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges
- the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL
) EF will mark the childEntity
as Deleted
as well. If you call SaveChanges
a SQL DELETE
statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
you have to set cellpadding and cellspacing that's it.
<table cellpadding="5" cellspacing="5">
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
</tr>
</table>
I was working on something like this. But is working only with structures generated from proto. https://github.com/flowup-labs/grpc-utils
in your proto
message Msg {
Firstname string = 1 [(gogoproto.jsontag) = "name.firstname"];
PseudoFirstname string = 2 [(gogoproto.jsontag) = "lastname"];
EmbedMsg = 3 [(gogoproto.nullable) = false, (gogoproto.embed) = true];
Lastname string = 4 [(gogoproto.jsontag) = "name.lastname"];
Inside string = 5 [(gogoproto.jsontag) = "name.inside.a.b.c"];
}
message EmbedMsg{
Opt1 string = 1 [(gogoproto.jsontag) = "opt1"];
}
Then your output will be
{
"lastname": "Three",
"name": {
"firstname": "One",
"inside": {
"a": {
"b": {
"c": "goo"
}
}
},
"lastname": "Two"
},
"opt1": "var"
}
Organize your files in hierarchical directories and then just use relative paths.
Demo:
HTML (index.html)
<a href='inner/file.html'>link</a>
Directory structure:
base/
base/index.html
base/inner/file.html
....
If you're using getline
after cin >> something
, you need to flush the newline out of the buffer in between.
My personal favourite for this if no characters past the newline are needed is cin.sync()
. However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore()
. Or make use of std::ws
to remove leading whitespace if desirable:
int a;
cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
//discard characters until newline is found
//my method: cin.sync(); //discard unread characters
string s;
getline (cin, s); //newline is gone, so this executes
//other method: getline(cin >> ws, s); //remove all leading whitespace
For MS SQL Server, you can use:
where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)
DECLARE
a VARCHAR2(30);
b VARCHAR2(30);
c VARCHAR2(30);
BEGIN
a := ' Abc ';
b := ' def ';
c := a || b;
DBMS_OUTPUT.PUT_LINE(c);
END;
output:: Abc def
On bootstrap-modal.js v2.2.0:
( $('element').data('modal') || {}).isShown
Use String.substring(beginIndex, endIndex)
str.substring(0, str.length() - 2);
The substring begins at the specified beginIndex and extends to the character at index (endIndex - 1)
Unless your application has specially needs, I think you have 2 approaches:
Session is not only thread-safe but also state-safe, in a way that you know that until the current request is completed, every session variable wont change from another active request. In order for this to happen you must ensure that session WILL BE LOCKED until the current request have completed.
You can create a session like behavior by many ways, but if it does not lock the current session, it wont be 'session'.
For the specific problems you mentioned I think you should check HttpContext.Current.Response.IsClientConnected. This can be useful to to prevent unnecessary executions and waits on the client, although it cannot solve this problem entirely, as this can be used only by a pooling way and not async.
Run this
for (Method m : sex.class.getDeclaredMethods()) {
System.out.println(m);
}
you will see
public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()
These are all public methods that "sex" class has. They are not in the source code, javac.exe added them
Notes:
never use sex as a class name, it's difficult to read your code, we use Sex in Java
when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class
i found a way that's works:
axios
.delete(URL, {
params: { id: 'IDDataBase'},
headers: {
token: 'TOKEN',
},
})
.then(function (response) {
})
.catch(function (error) {
console.log(error);
});
I hope this work for you too.
I have been searching for this for ages on my CM 11 android phone, running kitkat.
Well.. finally I found it. It's hidden in a totally unintuitive location:
Here you can choose between Media Device (MTP), Camera (PTP) and Mass storage (UMS). Turn them all off to get it to charge only.
Sadly, if the option is not there, it is not supported by the phone. This seems to be the case for my HTC One (M7).
giammin's solution is partially incorrect. You SHOULD NOT remove that entire PropertyGroup from your solution. If you do, MSBuild's "DeployTarget=Package" feature will stop working. This feature relies on the "VSToolsPath" being set.
<PropertyGroup>
<!-- VisualStudioVersion is incompatible with later versions of Visual Studio. Removing. -->
<!-- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> -->
<!-- VSToolsPath is required by MSBuild for features like "DeployTarget=Package" -->
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
...
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
If you already have the figure object use:
f.set_figheight(15)
f.set_figwidth(15)
But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:
f, axs = plt.subplots(2,2,figsize=(15,15))
To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:
JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);
And if you have an image:
JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);
But, I believe you want to make the label such that there are only 2 words on 1 line.
In that case try this:
String urText="<html>You can<br>use basic HTML<br>in Swing<br> components,"
+"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);
Transition properties are comma delimited in all browsers that support transitions:
.nav a {
transition: color .2s, text-shadow .2s;
}
ease
is the default timing function, so you don't have to specify it. If you really want linear
, you will need to specify it:
transition: color .2s linear, text-shadow .2s linear;
This starts to get repetitive, so if you're going to be using the same times and timing functions across multiple properties it's best to go ahead and use the various transition-*
properties instead of the shorthand:
transition-property: color, text-shadow;
transition-duration: .2s;
transition-timing-function: linear;
This is universal code , no matter how your input is long but in same schema if there is : separator :)
var string = "firstName:name1, lastName:last1";
var pass = string.replace(',',':');
var arr = pass.split(':');
var empty = {};
arr.forEach(function(el,i){
var b = i + 1, c = b/2, e = c.toString();
if(e.indexOf('.') != -1 ) {
empty[el] = arr[i+1];
}
});
console.log(empty)
Another option would be to use Angular's built-in pub-sub architecture in order to notify your directive to focus. Similar to the other approaches, but it's then not directly tied to a property, and is instead listening in on it's scope for a particular key.
Directive:
angular.module("app").directive("focusOn", function($timeout) {
return {
restrict: "A",
link: function(scope, element, attrs) {
scope.$on(attrs.focusOn, function(e) {
$timeout((function() {
element[0].focus();
}), 10);
});
}
};
});
HTML:
<input type="text" name="text_input" ng-model="ctrl.model" focus-on="focusTextInput" />
Controller:
//Assume this is within your controller
//And you've hit the point where you want to focus the input:
$scope.$broadcast("focusTextInput");
With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:
div#logo {
position: absolute;
left: 100px; // or whatever
}
Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want.
Visual Studio 2019 with CMake
Add the following to CMakeLists.txt
:
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
To get the moving average in pandas we can use cum_sum and then divide by count.
Here is the working example:
import pandas as pd
import numpy as np
df = pd.DataFrame({'id': range(5),
'value': range(100,600,100)})
# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']
# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()
print(df)
id value cum_sum count mov_avg rolling_mean2
0 0 100 100 1 100.0 NaN
1 1 200 300 2 150.0 150.0
2 2 300 600 3 200.0 250.0
3 3 400 1000 4 250.0 350.0
4 4 500 1500 5 300.0 450.0
For me, this error was caused by running the minified version of my angular app. Angular docs suggest a way to work around this. Here is the relevant quote describing the issue, and you can find the suggested solution in the docs themselves here:
A Note on Minification Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.
If you want to get the form data directly from Http request, without any model bindings or FormCollection
you can use this:
[HttpPost]
public ActionResult SubmitAction() {
// This will return an string array of all keys in the form.
// NOTE: you specify the keys in form by the name attributes e.g:
// <input name="this is the key" value="some value" type="test" />
var keys = Request.Form.AllKeys;
// This will return the value for the keys.
var value1 = Request.Form.Get(keys[0]);
var value2 = Request.Form.Get(keys[1]);
}
I actually had a similar issue, where we had to many trusted root certificates. Our fresh installed webserver had over a hunded. Our root started with the letter Z so it ended up at the end of the list.
The problem was that the IIS sent only the first twenty-something trusted roots to the client and truncated the rest, including ours. It was a few years ago, can't remember the name of the tool... it was part of the IIS admin suite, but Fiddler should do as well. After realizing the error, we removed a lot trusted roots that we don't need. This was done trial and error, so be careful what you delete.
After the cleanup everything worked like a charm.
You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
If you do not have file access to the repository, I prefer rsvndump (remote Subversion repository dump) to make the dump file.
A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.
You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.
UPDATE 1:
ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.
If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.
So it's all about what will happen when you delete rows from Parent table not from child table.
So in your case when user removes entries from CATs table then rows will be deleted from books table. :)
Hope this helps you :)
The compiler is pointing the error to you, you're comparing a structure instance and nil. They're not of the same type so it considers it as an invalid comparison and yells at you.
What you want to do here is to compare a pointer to your config instance to nil, which is a valid comparison. To do that you can either use the golang new builtin, or initialize a pointer to it:
config := new(Config) // not nil
or
config := &Config{
host: "myhost.com",
port: 22,
} // not nil
or
var config *Config // nil
Then you'll be able to check if
if config == nil {
// then
}
The Upgrade element inside the Product element, combined with proper scheduling of the action will perform the uninstall you're after. Be sure to list the upgrade codes of all the products you want to remove.
<Property Id="PREVIOUSVERSIONSINSTALLED" Secure="yes" />
<Upgrade Id="00000000-0000-0000-0000-000000000000">
<UpgradeVersion Minimum="1.0.0.0" Maximum="1.0.5.0" Property="PREVIOUSVERSIONSINSTALLED" IncludeMinimum="yes" IncludeMaximum="no" />
</Upgrade>
Note that, if you're careful with your builds, you can prevent people from accidentally installing an older version of your product over a newer one. That's what the Maximum field is for. When we build installers, we set UpgradeVersion Maximum to the version being built, but IncludeMaximum="no" to prevent this scenario.
You have choices regarding the scheduling of RemoveExistingProducts. I prefer scheduling it after InstallFinalize (rather than after InstallInitialize as others have recommended):
<InstallExecuteSequence>
<RemoveExistingProducts After="InstallFinalize"></RemoveExistingProducts>
</InstallExecuteSequence>
This leaves the previous version of the product installed until after the new files and registry keys are copied. This lets me migrate data from the old version to the new (for example, you've switched storage of user preferences from the registry to an XML file, but you want to be polite and migrate their settings). This migration is done in a deferred custom action just before InstallFinalize.
Another benefit is efficiency: if there are unchanged files, Windows Installer doesn't bother copying them again when you schedule after InstallFinalize. If you schedule after InstallInitialize, the previous version is completely removed first, and then the new version is installed. This results in unnecessary deletion and recopying of files.
For other scheduling options, see the RemoveExistingProducts help topic in MSDN. This week, the link is: http://msdn.microsoft.com/en-us/library/aa371197.aspx
TreeMap<String,String>
HashMap
entries with the value as the key.If the values are nonunique, you would need a list in the second position.
Having the AVD android emulator:
On the first field(HTTP Proxy Server) set only the IP address where is your proxy (XXX.XXX.XXX.XXX) on the second field set the port of your proxy (example: 8080)
Then, click Close on the window and start the emulator
---- Added ... Then the alex steps works on my case:
Click on Menu
Click on Settings
Click on Wireless & Networks
Go to Mobile Networks
Go to Access Point Names
Here you will Telkila Internet (or other name), click on it.
In the Edit access point section, input the "proxy" and "port"
I got same problem recently where
$(window).mousewheel
was returning undefined
What I did was $(window).on('mousewheel', function() {});
Further to process it I am using:
function (event) {
var direction = null,
key;
if (event.type === 'mousewheel') {
if (yourFunctionForGetMouseWheelDirection(event) > 0) {
direction = 'up';
} else {
direction = 'down';
}
}
}
I have got the JDK installed
You haven't specified the version. I think it is not 6 nor 5.
JDK 6 was the latest version at time of NetBeans 6.0 - 6.9 are developed. For that reason, They require JDK 6 (or JDK 5) and do not run on JDK 7 or later.
when a developer use an initializer block, the Java Compiler copies the initializer into each constructor of the current class.
Example:
the following code:
class MyClass {
private int myField = 3;
{
myField = myField + 2;
//myField is worth 5 for all instance
}
public MyClass() {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
is equivalent to:
class MyClass {
private int myField = 3;
public MyClass() {
myField = myField + 2;
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
myField = myField + 2;
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
I hope my example is understood by developers.
You could use hashname.key(valuename)
Or, an inversion may be in order. new_hash = hashname.invert
will give you a new_hash
that lets you do things more traditionally.
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
slide to right
viewPager.arrowScroll(View.FOCUS_RIGHT);
slide to left
viewPager.arrowScroll(View.FOCUS_LEFT);
i'm not sure if i understand you, but to query the source code of your triggers, procedures, package and functions you can try with the "user_source" table.
select * from user_source
This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.
pros:
cons:
Commented and runable example of batch-ps-script.cmd:
<# : Begin batch (batch script is in commentary of powershell v2.0+)
@echo off
: Use local variables
setlocal
: Change current directory to script location - useful for including .ps1 files
cd %~dp0
: Invoke this file as powershell expression
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
: Restore environment variables present before setlocal and restore current directory
endlocal
: End batch - go to end of file
goto:eof
#>
# here start your powershell script
# example: include another .ps1 scripts (commented, for quick copy-paste and test run)
#. ".\anotherScript.ps1"
# example: standard input from console
$variableInput = Read-Host "Continue? [Y/N]"
if ($variableInput -ne "Y") {
Write-Host "Exit script..."
break
}
# example: call standard powershell command
Get-Item .
Snippet for .cmd file:
<# : batch script
@echo off
setlocal
cd %~dp0
powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"
endlocal
goto:eof
#>
# here write your powershell commands...
My overlays disappeared all of a sudden (or so I thought). I came across this article https://corengen.wordpress.com/2014/07/30/my-tortoisesvn-icon-overlays-have-disappeared/ which points out that windows has 15 slots for overlay icons; 4 are reserved for windows, which leaves 11 for other applications. Regardless of how many overlay keys are in the registry, Windows selects the first 11 in alphabetical order.
When I upgraded Office, OneDrive added overlay icons -- prefixed with a lot of spaces -- pushing down Tortoise's overlays below the threshold: windows registry Since I am not using OneDrive, the solution was to add a "z" to the OneDrive key names.
Oracle views like ALL_TABLES and ALL_CONSTRAINTS have an owner column, which you can use to restrict your query. There are also variants of these tables beginning with USER instead of ALL, which only list objects which can be accessed by the current user.
One of these views should help to solve your problem. They always worked fine for me for similar problems.
I'm late to the party, but hopefully this is a useful addition to the other answers here...
I need to know how I can determine what "too much work" my application may be doing as all my processing is done in AsyncTasks.
The following are all candidates:
Uri
's on ImageView
's all constitute IO on the main thread)View
hierarchiesView
hierarchyonDraw
methods in custom View
'sAsyncTask
's are "background" by default, java.lang.Thread
is not)To actually determine the specific cause you'll need to profile your app.
I've been trying to understand Choreographer by experimenting and looking at the code.
The documentation of Choreographer opens with "Coordinates the timing of animations, input and drawing." which is actually a good description, but the rest goes on to over-emphasize animations.
The Choreographer is actually responsible for executing 3 types of callbacks, which run in this order:
The aim is to match the rate at which invalidated views are re-drawn (and animations tweened) with the screen vsync - typically 60fps.
The warning about skipped frames looks like an afterthought: The message is logged if a single pass through the 3 steps takes more than 30x the expected frame duration, so the smallest number you can expect to see in the log messages is "skipped 30 frames"; If each pass takes 50% longer than it should you will still skip 30 frames (naughty!) but you won't be warned about it.
From the 3 steps involved its clear that it isn't only animations that can trigger the warning: Invalidating a significant portion of a large View
hierarchy or a View
with a complicated onDraw method might be enough.
For example this will trigger the warning repeatedly:
public class AnnoyTheChoreographerActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_linear_layout);
ViewGroup root = (ViewGroup) findViewById(R.id.root);
root.addView(new TextView(this){
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
long sleep = (long)(Math.random() * 1000L);
setText("" + sleep);
try {
Thread.sleep(sleep);
} catch (Exception exc) {}
}
});
}
}
... which produces logging like this:
11-06 09:35:15.865 13721-13721/example I/Choreographer? Skipped 42 frames! The application may be doing too much work on its main thread.
11-06 09:35:17.395 13721-13721/example I/Choreographer? Skipped 59 frames! The application may be doing too much work on its main thread.
11-06 09:35:18.030 13721-13721/example I/Choreographer? Skipped 37 frames! The application may be doing too much work on its main thread.
You can see from the stack during onDraw
that the choreographer is involved regardless of whether you are animating:
at example.AnnoyTheChoreographerActivity$1.onDraw(AnnoyTheChoreographerActivity.java:25) at android.view.View.draw(View.java:13759)
... quite a bit of repetition ...
at android.view.ViewGroup.drawChild(ViewGroup.java:3169) at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3039) at android.view.View.draw(View.java:13762) at android.widget.FrameLayout.draw(FrameLayout.java:467) at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2396) at android.view.View.getDisplayList(View.java:12710) at android.view.View.getDisplayList(View.java:12754) at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1144) at android.view.ViewRootImpl.draw(ViewRootImpl.java:2273) at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2145) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1956) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1112) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4472) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725) at android.view.Choreographer.doCallbacks(Choreographer.java:555) at android.view.Choreographer.doFrame(Choreographer.java:525) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4898)
Finally, if there is contention from other threads that reduce the amount of work the main thread can get done, the chance of skipping frames increases dramatically even though you aren't actually doing the work on the main thread.
In this situation it might be considered misleading to suggest that the app is doing too much on the main thread, but Android really wants worker threads to run at low priority so that they are prevented from starving the main thread. If your worker threads are low priority the only way to trigger the Choreographer warning really is to do too much on the main thread.
This will keep the \n character, but you can also just wrap the quote in parentheses. Especially useful in RMarkdown.
t <- ("
this is a long
string
")
Simple tabulation of the output:
a = 0.3333333
b = 200/3
print("variable a variable b")
print("%10.2f %10.2f" % (a, b))
output:
variable a variable b
0.33 66.67
%10.2f: 10 is the minimum length and 2 is the number of decimal places.
Include jquery.validate.js before additional-methods.js
.
$.validate()
method is defined there
Check the static Nullable.GetUnderlyingType
.
- If the underlying type is null, then the template parameter is not Nullable
, and we can use that type directly
- If the underlying type is not null, then use the underlying type in the conversion.
Seems to work for me:
public object Get( string _toparse, Type _t )
{
// Test for Nullable<T> and return the base type instead:
Type undertype = Nullable.GetUnderlyingType(_t);
Type basetype = undertype == null ? _t : undertype;
return Convert.ChangeType(_toparse, basetype);
}
public T Get<T>(string _key)
{
return (T)Get(_key, typeof(T));
}
public void test()
{
int x = Get<int>("14");
int? nx = Get<Nullable<int>>("14");
}
eXtcos looks promising. Imagine you want to find all the classes that:
With eXtcos this is as simple as
ClasspathScanner scanner = new ClasspathScanner();
final Set<Class> classStore = new ArraySet<Class>();
Set<Class> classes = scanner.getClasses(new ClassQuery() {
protected void query() {
select().
from(“common”).
andStore(thoseExtending(Component.class).into(classStore)).
returning(allAnnotatedWith(MyComponent.class));
}
});
The list function will do this
>>> list('foo')
['f', 'o', 'o']
ERROR: flake8 3.7.9 has requirement pycodestyle<2.6.0,>=2.5.0, but you'll have pycodestyle 2.3.1 which is incompatible.
ERROR: nuscenes-devkit 1.0.8 has requirement motmetrics<=1.1.3, but you'll have motmetrics 1.2.0 which is incompatible.
Installing collected packages: descartes, future, torch, cachetools, torchvision, flake8-import-order, xmltodict, entrypoints, flake8, motmetrics, nuscenes-devkit
Attempting uninstall: torch
Found existing installation: torch 1.0.0
Uninstalling torch-1.0.0:
Successfully uninstalled torch-1.0.0
Attempting uninstall: torchvision
Found existing installation: torchvision 0.2.1
Uninstalling torchvision-0.2.1:
Successfully uninstalled torchvision-0.2.1
Attempting uninstall: entrypoints
Found existing installation: entrypoints 0.2.3
ERROR: Cannot uninstall 'entrypoints'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
Then I type:
conda uninstall entrypoints
pip install --upgrade pycodestyle
pip install nuscenes-devkit
Done!
this would help.. from google apis demos
private List<Marker> markerList = new ArrayList<>();
Marker marker = mGoogleMap.addMarker(new MarkerOptions().position(geoLatLng)
.title(title));
markerList.add(marker);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView!=null) {
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation") // We use the new method when supported
@SuppressLint("NewApi") // We check which build version we are using.
@Override
public void onGlobalLayout() {
//Calculate the markers to get their position
LatLngBounds.Builder b = new LatLngBounds.Builder();
for (Marker m : markerList) {
b.include(m.getPosition());
}
// also include current location to include in the view
b.include(new LatLng(mLocation.getLatitude(),mLocation.getLongitude()));
LatLngBounds bounds = b.build();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
});
}
}
for clear info look at this url. https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/MarkerDemoActivity.java
Maybe you should try
^[#;].*$
^
matches the beggining, $
the end.
This is usually a result of the server not accepting SSLv2 or SSLv3 connections which is a standard for cPanel/WHM in favor of TLS only connections. You can check this by going to WHM>>Service Configuration>>Exim Configuration Manager -> Options for OpenSSL
easy step
brew install postgresql
gem install pg -v 'your version'
//import fremework in .h file
#import <AVFoundation/AVFoundation.h>
{
AVCaptureSession *torchSession;
}
@property(nonatomic,retain)AVCaptureSession *torchSession;
-(IBAction)onoff:(id)sender;
//implement in .m file
@synthesize torchSession;
-(IBAction)onoff:(id)sender
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash])
{
if (device.torchMode == AVCaptureTorchModeOff)
{
[button setTitle:@"OFF" forState:UIControlStateNormal];
AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
[session addInput:flashInput];
[session addOutput:output];
[device unlockForConfiguration];
[output release];
[session commitConfiguration];
[session startRunning];
[self setTorchSession:session];
[session release];
}
else
{
[button setTitle:@"ON" forState:UIControlStateNormal];
[torchSession stopRunning];
}
}
}
- (void)dealloc
{
[torchSession release];
[super dealloc];
}
Two things to keep in mind Content-Type and the Encoding
1) What if the file is css
if (/.(css)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data, 'utf8');
}
2) What if the file is jpg/png
if (/.(jpg)$/.test(path)) {
res.writeHead(200, {'Content-Type': 'image/jpg'});
res.end(data,'Base64');
}
Above one is just a sample code to explain the answer and not the exact code pattern.
This is a known bug in MSys2, which provides the terminal used by Git Bash. You can work around it by running a Python build without ncurses support, or by using WinPTY, used as follows:
To run a Windows console program in mintty or Cygwin sshd, prepend console.exe to the command-line:
$ build/console.exe c:/Python27/python.exe Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 10 + 20 30 >>> exit()
The prebuilt binaries for msys are likely to work with Git Bash. (Do check whether there's a newer version if significant time has passed since this answer was posted!).
As of Git for Windows 2.7.1, also try using winpty c:Python27/python.exe
; WinPTY may be included out-of-the-box.
Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).
If you have installed Visual studio 2017 (profressional)
The install location:
C:\ProgramData\Anaconda3\Scripts
If you do not want the hassle of putting this in your path environment variable on windows and restarting you can run it by simply:
C:\>"C:\ProgramData\Anaconda3\Scripts\conda.exe" update qt pyqt
Apply this to your first <td>
:
padding-right:10px;
HTML example:
<table>
<tr>
<td style="padding-right:10px">data</td>
<td>more data</td>
</tr>
</table>
Applications that are not satisfied with only 256 different characters have the options of either using wide characters (more than 8 bits) or a variable-length encoding (a multibyte encoding in C++ terminology) such as UTF-8. Wide characters generally require more space than a variable-length encoding, but are faster to process. Multi-language applications that process large amounts of text usually use wide characters when processing the text, but convert it to UTF-8 when storing it to disk.
The only difference between a string
and a wstring
is the data type of the characters they store. A string stores char
s whose size is guaranteed to be at least 8 bits, so you can use strings for processing e.g. ASCII, ISO-8859-15, or UTF-8 text. The standard says nothing about the character set or encoding.
Practically every compiler uses a character set whose first 128 characters correspond with ASCII. This is also the case with compilers that use UTF-8 encoding. The important thing to be aware of when using strings in UTF-8 or some other variable-length encoding, is that the indices and lengths are measured in bytes, not characters.
The data type of a wstring is wchar_t
, whose size is not defined in the standard, except that it has to be at least as large as a char, usually 16 bits or 32 bits. wstring can be used for processing text in the implementation defined wide-character encoding. Because the encoding is not defined in the standard, it is not straightforward to convert between strings and wstrings. One cannot assume wstrings to have a fixed-length encoding either.
If you don't need multi-language support, you might be fine with using only regular strings. On the other hand, if you're writing a graphical application, it is often the case that the API supports only wide characters. Then you probably want to use the same wide characters when processing the text. Keep in mind that UTF-16 is a variable-length encoding, meaning that you cannot assume length()
to return the number of characters. If the API uses a fixed-length encoding, such as UCS-2, processing becomes easy. Converting between wide characters and UTF-8 is difficult to do in a portable way, but then again, your user interface API probably supports the conversion.
Swift 3.0 makes this a bit more verbose:
let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.index(of: needle) {
let pos = string.characters.distance(from: string.startIndex, to: idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
Extension:
extension String {
public func index(of char: Character) -> Int? {
if let idx = characters.index(of: char) {
return characters.distance(from: startIndex, to: idx)
}
return nil
}
}
In Swift 2.0 this has become easier:
let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.indexOf(needle) {
let pos = string.startIndex.distanceTo(idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
Extension:
extension String {
public func indexOfCharacter(char: Character) -> Int? {
if let idx = self.characters.indexOf(char) {
return self.startIndex.distanceTo(idx)
}
return nil
}
}
Swift 1.x implementation:
For a pure Swift solution one can use:
let string = "Hello.World"
let needle: Character = "."
if let idx = find(string, needle) {
let pos = distance(string.startIndex, idx)
println("Found \(needle) at position \(pos)")
}
else {
println("Not found")
}
As an extension to String
:
extension String {
public func indexOfCharacter(char: Character) -> Int? {
if let idx = find(self, char) {
return distance(self.startIndex, idx)
}
return nil
}
}
datetime.time
can not do it - But you could use datetime.datetime.now()
start = datetime.datetime.now()
sleep(10)
end = datetime.datetime.now()
duration = end - start
In case you are using Java 8 and want to have a more Functional Programming approach, you can define a Function
that manages the control and then you can reuse it and apply()
whenever is needed.
Coming to practice, you can define the Function
as
Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)
Then, you can use it by simply calling the apply()
method as:
String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true
If you prefer, you can define a Function
that checks if the String
is empty and then negate it with !
.
In this case, the Function
will look like as :
Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)
Then, you can use it by simply calling the apply()
method as:
String emptyString = "";
!isEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true
It's not an issue related to authentication at the first step. Your import
is not working. So, try writing this on first line:
#!/usr/bin/python
and for the time being run using
python xx.py
For you here is one explanation:
>>> abc = "Hei Buddy"
>>> print "%s" %abc
Hei Buddy
>>>
>>> print "%s" %xyz
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print "%s" %xyz
NameError: name 'xyz' is not defined
At first, I initialized abc variable and it works fine. On the otherhand, xyz doesn't work as it is not initialized!
solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
You can use the CONCAT
with CURDATE()
to the entire time of the day and then filter by using the BETWEEN
in WHERE
condition:
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE (users.signup_date BETWEEN CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59'))
There are a few different points here:
.npmrc
file created.Running npm config ls -l
will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc
. But if you have never logged in (using npm login
) it will be empty. Simply log in to create it.
Another thing is #2. You can actually do that by putting a .npmrc
file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:
; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
Pointers
The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.
angular.module('app')
.directive('my-slider',
['$timeout', function($timeout) {
return {
restrict:'E',
scope: true,
template: '<div id="{{ id }}"></div>',
link: function($scope) {
$scope.id = String(Math.random()).substr(2, 8);
$timeout(function() {
angular.element('#'+$scope.id).slider();
});
}
};
}]
);
Your logic condition is wrong. IIUC, what you want is:
import pyspark.sql.functions as f
df.filter((f.col('d')<5))\
.filter(
((f.col('col1') != f.col('col3')) |
(f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
)\
.show()
I broke the filter()
step into 2 calls for readability, but you could equivalently do it in one line.
Output:
+----+----+----+----+---+
|col1|col2|col3|col4| d|
+----+----+----+----+---+
| A| xx| D| vv| 4|
| A| x| A| xx| 3|
| E| xxx| B| vv| 3|
| F|xxxx| F| vvv| 4|
| G| xxx| G| xx| 4|
+----+----+----+----+---+
If you set null=True
, it will allow the value of your database column to be set as NULL
. If you only set blank=True
, django will set the default new value for the column equal to ""
.
There's one point where null=True
would be necessary even on a CharField
or TextField
and that is when the database has the unique
flag set for the column. In this case you'll need to use this:
a_unique_string = models.CharField(blank=True, null=True, unique=True)
Preferrably skip the null=True
for non-unique CharField
or TextField
. Otherwise some fields will be set as NULL
while others as ""
, and you'll have to check the field value for NULL
everytime.
You can non-interactively remove B and C in your example with:
git rebase --onto HEAD~5 HEAD~3 HEAD
or symbolically,
git rebase --onto A C HEAD
Note that the changes in B and C will not be in D; they will be gone.
This is the simplest way I found for doing this:
byte[] byteArray = ...
InputStream is = new BufferedInputStream(new ByteArrayInputStream(byteArray));
String mimeType = URLConnection.guessContentTypeFromStream(is);
The difference is in the subsystem that each executable targets.
java.exe
targets the CONSOLE
subsystem.javaw.exe
targets the WINDOWS
subsystem.Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter.
I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this...
C#
var bldr = new SqlBuilder( myCommand );
bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId);
//or
bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName);
myCommand.CommandText = bldr.ToString();
Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here...
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
public class SqlBuilder
{
private StringBuilder _rq;
private SqlCommand _cmd;
private int _seq;
public SqlBuilder(SqlCommand cmd)
{
_rq = new StringBuilder();
_cmd = cmd;
_seq = 0;
}
public SqlBuilder Append(String str)
{
_rq.Append(str);
return this;
}
public SqlBuilder Value(Object value)
{
string paramName = "@SqlBuilderParam" + _seq++;
_rq.Append(paramName);
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public SqlBuilder FuzzyValue(Object value)
{
string paramName = "@SqlBuilderParam" + _seq++;
_rq.Append("'%' + " + paramName + " + '%'");
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public override string ToString()
{
return _rq.ToString();
}
}
Base-64 encoding is a way of taking binary data and turning it into text so that it's more easily transmitted in things like e-mail and HTML form data.
You can download in the various way you can follow my way. Though files may not download due to 'allow-popups' permission is not set but in your environment, this will work perfectly
<div className="col-6">_x000D_
<a download href="https://www.w3schools.com/images/myw3schoolsimage.jpg" >Test Download </a>_x000D_
</div>
_x000D_
another one this one will also fail due to 'X-Frame-Options' to 'sameorigin'.
<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg" download>_x000D_
<img src="https://www.w3schools.com/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142">_x000D_
</a>
_x000D_
The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).
# now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')
This is using ms-Dropdown : https://github.com/marghoobsuleman/ms-Dropdown
But data resource is json.
Example : http://jsfiddle.net/tcibikci/w3rdhj4s/6
HTML
<div id="byjson"></div>
Script
<script>
var jsonData = [
{description:'Choos your payment gateway', value:'', text:'Payment Gateway'},
{image:'https://via.placeholder.com/50', description:'My life. My card...', value:'amex', text:'Amex'},
{image:'https://via.placeholder.com/50', description:'It pays to Discover...', value:'Discover', text:'Discover'},
{image:'https://via.placeholder.com/50', title:'For everything else...', description:'For everything else...', value:'Mastercard', text:'Mastercard'},
{image:'https://via.placeholder.com/50', description:'Sorry not available...', value:'cash', text:'Cash on devlivery', disabled:true},
{image:'https://via.placeholder.com/50', description:'All you need...', value:'Visa', text:'Visa'},
{image:'https://via.placeholder.com/50', description:'Pay and get paid...', value:'Paypal', text:'Paypal'}
];
$("#byjson").msDropDown({byJson:{data:jsonData, name:'payments2'}}).data("dd");
}
</script>
Here is my entry, simple and clean..
function array2xml($array, $xml = false){
if($xml === false){
$xml = new SimpleXMLElement('<root/>');
}
foreach($array as $key => $value){
if(is_array($value)){
array2xml($value, $xml->addChild($key));
}else{
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}
header('Content-type: text/xml');
print array2xml($array);
Try this: http://www.webtrickss.com/javascript/jquery-slidetoggle-signup-form-and-login-form/
????????????????????????????????????????????????
NO, you can't do it other way than so.
For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with
nohup some_command > nohup2.out&
and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.
Another one:
"-exec rm -rf {} \;" can be replaced by "-delete"
find -type d -name __pycache__ -delete # GNU find
find . -type d -name __pycache__ -delete # POSIX find (e.g. Mac OS X)
This answer helped me https://stackoverflow.com/a/18880670/1821607
The reason of crush — index 0 wasn't set. Simple $array = $array + array(null)
did the trick. Or you should check whether array element on index 0 is set via isset($array[0])
. The second variant is the best approach for me.
You can always write the code in VBA that updates similarly. I had this problem too, and my workaround was making a select query, with all the joins, that had all the data I was looking for to be able to update, making that a recordset and running the update query repeatedly as an update query of only the updating table, only searching the criteria you're looking for
Dim updatingItems As Recordset
Dim clientName As String
Dim tableID As String
Set updatingItems = CurrentDb.OpenRecordset("*insert SELECT SQL here*");", dbOpenDynaset)
Do Until updatingItems .EOF
clientName = updatingItems .Fields("strName")
tableID = updatingItems .Fields("ID")
DoCmd.RunSQL "UPDATE *ONLY TABLE TO UPDATE* SET *TABLE*.strClientName= '" & clientName & "' WHERE (((*TABLE*.ID)=" & tableID & "))"
updatingItems.MoveNext
Loop
I'm only doing this to about 60 records a day, doing it to a few thousand could take much longer, as the query is running from start to finish multiple times, instead of just selecting an overall group and making changes. You might need ' ' around the quotes for tableID, as it's a string, but I'm pretty sure this is what worked for me.
Call make
command this way:
make CFLAGS=-Dvar=42
And be sure to use $(CFLAGS)
in your compile command in the Makefile. As @jørgensen mentioned , putting the variable assignment after the make
command will override the CFLAGS
value already defined the Makefile.
Alternatively you could set -Dvar=42
in another variable than CFLAGS
and then reuse this variable in CFLAGS
to avoid completely overriding CFLAGS
.
File.exist?("directory")
Dir[]
returns an array, so it will never be nil
. If you want to do it your way, you could do
Dir["directory"].empty?
which will return true
if it wasn't found.
I found a very simple solution to the problem. I simply created two GridViews. The first GridView called a DataSource with a query that was designed to return no rows. It simply contained the following:
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<HeaderTemplate>
<asp:Label ID="lbl0" etc.> </asp:Label>
<asp:Label ID="lbl1" etc.> </asp:Label>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
Then I created a div with the following characteristics and I place a GridView inside of it with ShowHeader="false" so that the top row is the same size as all the other rows.
<div style="overflow: auto; height: 29.5em; width: 100%">
<asp:GridView ID="Rollup" runat="server" ShowHeader="false" DataSourceID="ObjectDataSource">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lbl0" etc.> </asp:Label>
<asp:Label ID="lbl1" etc.> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
You have two choices:
Use fileno()
to obtain the file descriptor associated with the stdio
stream pointer
Don't use <stdio.h>
at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write()
call won't even return until the lower-level IO has completed (in theory).
For device-level IO I'd say it's pretty unusual to use stdio
. I'd strongly recommend using the lower-level open()
, read()
and write()
functions instead (based on your later reply):
int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);
There is also one useful setting that tells IntelliJ to check for new versions of dependencies even if the version numbers didn't change. We had a local maven repository and a snapshot project that was updated a few times but the version numbers stood the same. The problem was that IntelliJ/Maven didn't update this project because of the fixed version number.
To enable checking for a changed dependency although the version number didn't change go to the "Maven Projects" tab, select "Maven settings" and there activate "Always update snapshots".
Just press ?K it will toggle keyboard.
Do you want to find the length of the string in python language ? If you want to find the length of the word, you can use the len function.
string = input("Enter the string : ")
print("The string length is : ",len(string))
OUTPUT : -
Enter the string : viral
The string length is : 5
let vc = DetailUserViewController()
vc.userdetails = userViewModels[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
You need to add an event, before call your handleFunction like this:
function SingInContainer() {
..
..
handleClose = () => {
}
return (
<SnackBar
open={open}
handleClose={() => handleClose}
variant={variant}
message={message}
/>
<SignInForm/>
)
}
you can 'invoke' alternative bindings on Y
this way:
...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).
Note the parenthesis are required to keep the correct execution control flow. The ;
/2 it's the general or
operator. For your restricted use you could as well choice the more idiomatic
...registered(X, Y), member(Y, [ct101,ct102,ct103]).
that on backtracking binds Y to each member of the list.
edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead
...registered(X, ct101), registered(X, ct102), registered(X, ct103).
or the more compact
...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).
findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.
...setof(Y, registered(X, Y), [ct101,ct102,ct103]).
setof/3 also sorts the result list
static class Thing
will make your program work.
As it is, you've got Thing
as an inner class, which (by definition) is associated with a particular instance of Hello
(even if it never uses or refers to it), which means it's an error to say new Thing();
without having a particular Hello
instance in scope.
If you declare it as a static class instead, then it's a "nested" class, which doesn't need a particular Hello
instance.
Use padding
on the cells and border-spacing
on the table. The former will give you cellpadding while the latter will give you cellspacing.
table { border-spacing: 5px; } /* cellspacing */
th, td { padding: 5px; } /* cellpadding */
\r\n
for Windows will do just fine.
If it's fixed layout you can do like that:
public void onClick(View v) {
ViewGroup parent = (ViewGroup) IdNumber.this.getParent();
EditText firstName = (EditText) parent.findViewById(R.id.display_name);
firstName.setText("Some Text");
}
If you want find the EditText in flexible layout, I will help you later. Hope this help.
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
For those who want to improve the time for retrieval of records and dump into the file (i.e no processing on records), instead of putting them into an ArrayList, append those records into a StringBuffer. Apply toSring() function to get a single String and write it into the file at once.
For me, the retrieval time reduced from 22 seconds to 17 seconds.
If you change your function definition to use a variable instead:
var get_page = func(url string) string {
...
}
You can override it in your tests:
func TestDownloader(t *testing.T) {
get_page = func(url string) string {
if url != "expected" {
t.Fatal("good message")
}
return "something"
}
downloader()
}
Careful though, your other tests might fail if they test the functionality of the function you override!
The Go authors use this pattern in the Go standard library to insert test hooks into code to make things easier to test:
The accepted answer is wrong. GET
requests can indeed contain a body. This is the solution implemented by WordPress, as an example:
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
EDIT: To clarify, the initial curl_setopt
is necessary in this instance, because libcurl will default the HTTP method to POST
when using CURLOPT_POSTFIELDS
(see documentation).
if(stop == true)
or
if(stop)
= is for assignment.
== is for checking condition.
if(stop = true)
It will assign true to stop and evaluates if(true). So it will always execute the code inside if because stop will always being assigned with true.
use this too :
if(e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
Becoz e.preventDefault() is not supported in IE( some versions ). In IE it is e.returnValue = false