A bit late to the party but still - I prefer using numpy where:
import numpy as np
df['First Season'] = np.where(df['First Season'] > 1990, 1, df['First Season'])
Try this:
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg),
Base64.NO_WRAP);
The line
base64String = Base64.encode(byteArray);
converts the full array (102400 bytes) to Base64, not just the number of bytes you have read. You need to pass it the numbers of bytes.
You've just published that private key, so now the whole world knows what it is. Hopefully that was just for testing.
EDIT: Others have noted that the openssl text header of the published key, -----BEGIN RSA PRIVATE KEY-----, indicates that it is PKCS#1. However, the actual Base64 contents of the key in question is PKCS#8. Evidently the OP copy and pasted the header and trailer of a PKCS#1 key onto the PKCS#8 key for some unknown reason. The sample code I've provided below works with PKCS#8 private keys.
Here is some code that will create the private key from that data. You'll have to replace the Base64 decoding with your IBM Base64 decoder.
public class RSAToy {
private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIIEuwIBADAN ...skipped the rest\n"
// + ...
// + ... skipped the rest
// + ...
+ "-----END RSA PRIVATE KEY-----";
public static void main(String[] args) throws Exception {
// Remove the first and last lines
String privKeyPEM = BEGIN_RSA_PRIVATE_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
System.out.println(privKeyPEM);
// Base64 decode the data
byte [] encoded = Base64.decode(privKeyPEM);
// PKCS8 decode the encoded RSA private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
// Display the results
System.out.println(privKey);
}
}
Check Metrix++ http://metrixplusplus.sourceforge.net/. It may require some extensions which are specific for your needs.
Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the this
value.
# -*- mode: python -*-
block_cipher = None
a = Analysis(['SCRIPT.py'],
pathex=[
'folder path',
'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_50c6cb8431e7428f',
'C:\\Windows\\WinSxS\\x86_microsoft-windows-m..namespace-downlevel_31bf3856ad364e35_10.0.17134.1_none_c4f50889467f081d'
],
binaries=[(''C:\\Users\\chromedriver.exe'')],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='NAME OF YOUR EXE',
debug=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )
There's also the function tags, a bit more flexible:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">
And here's the tag documentation.
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
public class MyObject implements Cloneable, Serializable{
@Override
@SuppressWarnings(value = "unchecked")
protected MyObject clone(){
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream bOs = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bOs);
oos.writeObject(this);
ois = new ObjectInputStream(new ByteArrayInputStream(bOs.toByteArray()));
return (MyObject)ois.readObject();
} catch (Exception e) {
//Some seriouse error :< //
return null;
}finally {
if (oos != null)
try {
oos.close();
} catch (IOException e) {
}
if (ois != null)
try {
ois.close();
} catch (IOException e) {
}
}
}
}
Another option is using command line:
code -d left.txt right.txt
Note: You may need to add code
to your path first. See: How to call VS Code Editor from command line
If you read the link you shared, the accepted answer is:
You cannot post pictures to Instagram via the API.
Instagram have now said this:
Now you can post your content using Instagram APIs (New) effects from 26th Jan 2021 !
https://developers.facebook.com/blog/post/2021/01/26/introducing-instagram-content-publishing-api/
Hopefully you have some luck here.
Steps:
var fs = require('fs');
function base64Encode(file) {
var body = fs.readFileSync(file);
return body.toString('base64');
}
var base64String = base64Encode('test.jpg');
console.log(base64String);
The SQL Server login required is DOMAIN\machinename$
. This is the how the calling NT AUTHORITY\NETWORK SERVICE
appears to SQL Server (and file servers etc)
In SQL,
CREATE LOGIN [XYZ\Gandalf$] FROM WINDOWS
Just try this:
Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();
If bitmapdata
is the byte array then getting Bitmap
is done like this:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
Returns the decoded Bitmap
, or null
if the image could not be decoded.
Go to Start -> Run -> Services.msc in Windows.
Locate OracleService < SID > (here OracleServiceORCL
) and click on Start
to start the oracle database service (if not already running)
Once it is up and running, from the command prompt run the following:
tnsping < tnsalias >
(tnsalias entry you can find it in tnsnames.ora
file)
Global.asax is the asp.net application file.
It is an optional file that handles events raised by ASP.NET or by HttpModules. Mostly used for application and session start/end events and for global error handling.
When used, it should be in the root of the website.
Following the fact that the load order cannot be anticipated, a simple solution can be used.
Let's look at the directive-'user of directive' relationship. Usually the user of the directive will supply some data to the directive or use some functionality ( functions ) the directive supplies. The directive on the other hand expects some variables to be defined on its scope.
If we can make sure that all players have all their action requirements fulfilled before they attempt to execute those actions - everything should be well.
And now the directive:
app.directive('aDirective', function () {
return {
scope: {
input: '=',
control: '='
},
link: function (scope, element) {
function functionThatNeedsInput(){
//use scope.input here
}
if ( scope.input){ //We already have input
functionThatNeedsInput();
} else {
scope.control.init = functionThatNeedsInput;
}
}
};
})
and now the user of the directive html
<a-directive control="control" input="input"></a-directive>
and somewhere in the controller of the component that uses the directive:
$scope.control = {};
...
$scope.input = 'some data could be async';
if ( $scope.control.functionThatNeedsInput){
$scope.control.functionThatNeedsInput();
}
That's about it. There is a lot of overhead but you can lose the $timeout. We also assume that the component that uses the directive is instantiated before the directive because we depend on the control variable to exist when the directive is instantiated.
Probably you haven't injected $http
service to your controller. There are several ways of doing that.
Please read this reference about DI. Then it gets very simple:
function MyController($scope, $http) {
// ... your code
}
Just tested and this works:
public class Coordinates {
byte red;
@JsonProperty("r")
public byte getR() {
return red;
}
@JsonProperty("red")
public void setRed(byte red) {
this.red = red;
}
}
The idea is that method names should be different, so jackson parses it as different fields, not as one field.
Here is test code:
Coordinates c = new Coordinates();
c.setRed((byte) 5);
ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(c));
Coordinates r = mapper.readValue("{\"red\":25}",Coordinates.class);
System.out.println("Deserialization: " + r.getR());
Result:
Serialization: {"r":5}
Deserialization: 25
As @Vlad from Moscow says,
Take into account that value_type
for std::map
is defined the following way:
typedef pair<const Key, T> value_type
This then means that if you wish to replace the keyword auto
with a more explicit type specifier, then you could this;
for ( const pair<const string, int> &p : table ) {
std::cout << p.first << '\t' << p.second << std::endl;
}
Just for understanding what auto
will translate to in this case.
EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
Date date = new Date(1318386508000L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
formatted = format.format(date);
System.out.println(formatted);
}
}
Output:
12/10/2011 02:28:28
12/10/2011 13:28:28
I would also suggest you start using Joda Time which is simply a much nicer date/time API...
EDIT: Note that if your system doesn't know about the Australia/Sydney
time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah")
it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName()
and see what it says... and check your code for typos too :)
As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
Demo: https://ideone.com/rMF2XA
Note that any of the quoting mechanisms -- \____HERE
or "____HERE"
or '____HERE'
-- will disable all variable interpolation, and turn the here-document into a piece of literal text.
A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
:
Thanks all person who try to help in this post
I have ubuntu 13.10 and my chrome version is 34.0
For my situation this works
1.open developer tools in chrome(or use right click on your page and then select inspect element)
2.go to "Network" tab
3.find your ajax request in "Name Path" column
4.click on the specific ajax link
now you should see a new Panel in front of you request
in this panel select "Response" tab
Using tidyr
package, this can be easily handled in 1 function call.
data <- data.frame('a' = 1:3,
'b' = c('a','b','c'),
'c' = c('d', 'e', 'f'),
'd' = c('g', 'h', 'i'))
tidyr::unite_(data, paste(colnames(data)[-1], collapse="_"), colnames(data)[-1])
a b_c_d
1 1 a_d_g
2 2 b_e_h
3 3 c_f_i
Edit: Exclude first column, everything else gets pasted.
# tidyr_0.6.3
unite(data, newCol, -a)
# or by column index unite(data, newCol, -1)
# a newCol
# 1 1 a_d_g
# 2 2 b_e_h
# 3 3 c_f_i
Using jQuery:
$('#Button').click(function(){
$(this).addClass("active");
});
This way, you don't have to pollute your HTML markup with onclick
handlers.
Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.
The GitLens icon will show up in nav bar. Click on it.
Click on compare
Select branches to compare
Now you can see the difference. You can select any file for which you want to see the diff for.
You want an outer join for this (and you need to use person as the "driving" table)
SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person
LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;
The reason why this is working, is that the outer (left) join will return NULL
for those persons that do not have an appointment. The aggregate function count()
will not count NULL
values and thus you'll get a zero.
If you want to learn more about outer joins, here is a nice tutorial: http://sqlzoo.net/wiki/Using_Null
I think you want this:
foreach ($myarray as $key => $value) {
echo "$key = $value\n";
}
It worked for me this way, it's the best I've found. It is for a max length of 200 characters
editObservations.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (editObservations.getText().length() >= 201){
String str = editObservations.getText().toString().substring(0, 200);
editObservations.setText(str);
editObservations.setSelection(str.length());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
Trying not to sound zany, but can't help myself.
Your question should be what is the difference between mutex and semaphores ? And to be more precise question should be, 'what is the relationship between mutex and semaphores ?'
(I would have added that question but I'm hundred % sure some overzealous moderator would close it as duplicate without understanding difference between difference and relationship.)
In object terminology we can observe that :
observation.1 Semaphore contains mutex
observation.2 Mutex is not semaphore and semaphore is not mutex.
There are some semaphores that will act as if they are mutex, called binary semaphores, but they are freaking NOT mutex.
There is a special ingredient called Signalling (posix uses condition_variable for that name), required to make a Semaphore out of mutex. Think of it as a notification-source. If two or more threads are subscribed to same notification-source, then it is possible to send them message to either ONE or to ALL, to wakeup.
There could be one or more counters associated with semaphores, which are guarded by mutex. The simple most scenario for semaphore, there is a single counter which can be either 0 or 1.
This is where confusion pours in like monsoon rain.
A semaphore with a counter that can be 0 or 1 is NOT mutex.
Mutex has two states (0,1) and one ownership(task). Semaphore has a mutex, some counters and a condition variable.
Now, use your imagination, and every combination of usage of counter and when to signal can make one kind-of-Semaphore.
Single counter with value 0 or 1 and signaling when value goes to 1 AND then unlocks one of the guy waiting on the signal == Binary semaphore
Single counter with value 0 to N and signaling when value goes to less than N, and locks/waits when values is N == Counting semaphore
Single counter with value 0 to N and signaling when value goes to N, and locks/waits when values is less than N == Barrier semaphore (well if they dont call it, then they should.)
Now to your question, when to use what. (OR rather correct question version.3 when to use mutex and when to use binary-semaphore, since there is no comparison to non-binary-semaphore.) Use mutex when 1. you want a customized behavior, that is not provided by binary semaphore, such are spin-lock or fast-lock or recursive-locks. You can usually customize mutexes with attributes, but customizing semaphore is nothing but writing new semaphore. 2. you want lightweight OR faster primitive
Use semaphores, when what you want is exactly provided by it.
If you dont understand what is being provided by your implementation of binary-semaphore, then IMHO, use mutex.
And lastly read a book rather than relying just on SO.
http://en.wikipedia.org/wiki/Division_by_zero
http://en.wikipedia.org/wiki/Unix_signal#SIGFPE
This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0
IS division by zero and as such, will trigger a SIGFPE being thrown.
This is an old question but I think it needs a more up to date answer because now there is a way to have more control of website caching.
In Offline Web Applications (which is really any HTML5 website) applicationCache.swapCache()
can be used to update the cached version of your website without the need for manually reloading the page.
This is a code example from the Beginner's Guide to Using the Application Cache on HTML5 Rocks explaining how to update users to the newest version of your site:
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);
See also Using the application cache on Mozilla Developer Network for more info.
Things change quickly on the Web. This question was asked in 2009 and in 2012 I posted an update about a new way to handle the problem described in the question. Another 4 years passed and now it seems that it is already deprecated. Thanks to cgaldiolo for pointing it out in the comments.
Currently, as of July 2016, the HTML Standard, Section 7.9, Offline Web applications includes a deprecation warning:
This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using any of the offline Web application features at this time is highly discouraged. Use service workers instead.
So does Using the application cache on Mozilla Developer Network that I referenced in 2012:
Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
See also Bug 1204581 - Add a deprecation notice for AppCache if service worker fetch interception is enabled.
this sample code loads the Japanese yield curve, and creates PCA components. It then estimates a given date's move using the PCA and compares it against the actual move.
%matplotlib inline
import numpy as np
import scipy as sc
from scipy import stats
from IPython.display import display, HTML
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import datetime
from datetime import timedelta
import quandl as ql
start = "2016-10-04"
end = "2019-10-04"
ql_data = ql.get("MOFJ/INTEREST_RATE_JAPAN", start_date = start, end_date = end).sort_index(ascending= False)
eigVal_, eigVec_ = np.linalg.eig(((ql_data[:300]).diff(-1)*100).cov()) # take latest 300 data-rows and normalize to bp
print('number of PCA are', len(eigVal_))
loc_ = 10
plt.plot(eigVec_[:,0], label = 'PCA1')
plt.plot(eigVec_[:,1], label = 'PCA2')
plt.plot(eigVec_[:,2], label = 'PCA3')
plt.xticks(range(len(eigVec_[:,0])), ql_data.columns)
plt.legend()
plt.show()
x = ql_data.diff(-1).iloc[loc_].values * 100 # set the differences
x_ = x[:,np.newaxis]
a1, _, _, _ = np.linalg.lstsq(eigVec_[:,0][:, np.newaxis], x_) # linear regression without intercept
a2, _, _, _ = np.linalg.lstsq(eigVec_[:,1][:, np.newaxis], x_)
a3, _, _, _ = np.linalg.lstsq(eigVec_[:,2][:, np.newaxis], x_)
pca_mv = m1 * eigVec_[:,0] + m2 * eigVec_[:,1] + m3 * eigVec_[:,2] + c1 + c2 + c3
pca_MV = a1[0][0] * eigVec_[:,0] + a2[0][0] * eigVec_[:,1] + a3[0][0] * eigVec_[:,2]
pca_mV = b1 * eigVec_[:,0] + b2 * eigVec_[:,1] + b3 * eigVec_[:,2]
display(pd.DataFrame([eigVec_[:,0], eigVec_[:,1], eigVec_[:,2], x, pca_MV]))
print('PCA1 regression is', a1, a2, a3)
plt.plot(pca_MV)
plt.title('this is with regression and no intercept')
plt.plot(ql_data.diff(-1).iloc[loc_].values * 100, )
plt.title('this is with actual moves')
plt.show()
I believe that must-revalidate
means :
Once the cache expires, refuse to return stale responses to the user even if they say that stale responses are acceptable.
Whereas no-cache
implies :
must-revalidate
plus the fact the response becomes stale right away.
If a response is cacheable for 10 seconds, then must-revalidate
kicks in after 10 seconds, whereas no-cache
implies must-revalidate
after 0 seconds.
At least, that's my interpretation.
Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL
Do following steps to detect your device in eclipse : -
On Mobile Side:- For Connect USB sync, your Android device needs to have USB Debugging enabled.
To enable Android USB Debugging Mode do following steps :-
Android 2.x - 3.x devices:
Go to Settings > Application > Development > USB Debugging.
Android 4.x devices:
Go to Settings > Developer Options > USB Debugging.
For devices running Android 4.2.2 or later, you may need to unlock Developer Options before it is available within the Menu:
On PC side
Now in eclipse do following steps to install your app in your device:-
Some fixes I've used for this problem:
Check if the connection you want to share is shareable.
a. Press Win-key + r and run ncpa.cpl
b. Right click on the connection you want to share and go to properties
c. Go to sharing tab and check if sharing is enabled
Run devmgmt.msc
from the run console.
a. Expand the network adapters list
b. Right click -> properties on the adapter of the connection you want to share
c. Go to power management tab and enable allow this computer to turn off this device to save power
. Restart your laptop if you've made changes.
Check if airplane mode is disabled. You can enable airplane mode and then turn on the wi-fi, you can never know. Do disable airplane mode if it is on.
Use admin command prompt to run this command.
How about using the Dynamic data template that comes with Visual Studio. This could be hosted on IIS.
In addition to the anwser of Bill the Lizard:
Most of the backends parse the raw post data. In PHP for example, you will have an array $_POST
in which individual variables within the post data will be stored. In this case you have to use an additional header "Content-type: application/x-www-form-urlencoded"
:
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("var1=value1&var2=value2&var3=value3")
Otherwise you have to read the raw post data on the variable "$HTTP_RAW_POST_DATA"
.
To fix the issue for package http-proxy
1) HTTP (localhost) accessing HTTPS To fix this issue set changeOrigin to true.
const proxy = httpProxy.createProxyServer();
proxy.web(req, res, {
changeOrigin: true,
target: https://example.com:3000,
});
2) HTTPS accessing HTTPS you should include SSL certificate
httpProxy.createServer({
ssl: {
key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
},
target: 'https://example.com:3000',
secure: true
}).listen(443);
I always remove the .gradle folder from %USERS% folder and start the studio again. When starting the IDE it downloads gradle again with all the dependencies again. Its work PERFECT.
If your element has parent
element.parentElement.innerHTML
Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS
Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
convertDataURIToBinary: function(dataURI) {_x000D_
var BASE64_MARKER = ';base64,',_x000D_
base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
base64 = dataURI.substring(base64Index),_x000D_
raw = window.atob(base64),_x000D_
rawLength = raw.length,_x000D_
array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
for (var i = 0; i < rawLength; i++) {_x000D_
array[i] = raw.charCodeAt(i);_x000D_
}_x000D_
return array;_x000D_
},
_x000D_
I faced the same situation. Create your connection string as follows.
Replace
"connectionString": "Data Source=server name;Initial Catalog=DB name;User id=user id;Password=password;Integrated Security=True;MultipleActiveResultSets=True"
by
"connectionString": "Server=server name; Database=Treat; User Id=user id; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true"
Also, if nothing else from given solutions doesn't work, check if you imported "FormsModule" inside of "AppModule", that was a key for me.
You're right that it involves a loop, but this is, at least, made simple by use of the each()
method:
$('.target').each(
function(){
// iterate through each of the `.target` elements, and do stuff in here
// `this` and `$(this)` refer to the current `.target` element
var images = $(this).find('img'),
imageWidth = images.width(); // returns the width of the _first_ image
numImages = images.length;
$(this).css('width', (imageWidth*numImages));
});
References:
You can disable sql_mode=only_full_group_by by some command you can try this by terminal or MySql IDE
mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
I find this works better:
SELECT type, *
FROM sys.objects
WHERE OBJECT_DEFINITION(object_id) LIKE '%' + @ObjectName + '%'
AND type IN ('V')
ORDER BY name
Filtering VIEW_DEFINTION
inside INFORMATION_SCHEMA.VIEWS
is giving me quite a few false positives.
In kotlin you can use unaryPlus and unaryMinus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html
I received this error while trying to run Google's Firebase analytics sample app:
Prerequisites:
Add Procedure:
Remove Procedure:
I added and removed the sample app multiple times without any noticeable side effects.
You should read up on the onclick
html attribute and the window.open()
documentation. Below is what you want.
<a href='#' onclick='window.open("http://www.google.com", "myWin", "scrollbars=yes,width=400,height=650"); return false;'>1</a>
_x000D_
JSFiddle: http://jsfiddle.net/TBcVN/
The best way is:
if ps -p $PID > /dev/null
then
echo "$PID is running"
# Do something knowing the pid exists, i.e. the process with $PID is running
fi
The problem with:
kill -0 $PID
is the exit code will be non-zero even if the pid is running and you dont have permission to kill it. For example:
kill -0 1
and
kill -0 $non-running-pid
have an indistinguishable (non-zero) exit code for a normal user, but the init process (PID 1) is certainly running.
The answers discussing kill and race conditions are exactly right if the body of the test is a "kill". I came looking for the general "how do you test for a PID existence in bash".
The /proc method is interesting, but in some sense breaks the spirit of the "ps" command abstraction, i.e. you dont need to go looking in /proc because what if Linus decides to call the "exe" file something else?
You will need to run this command in every path you have in your environment.
>>> import sys
>>> sys.path
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/source_code/src/python', '/usr/lib/python3/dist-packages']
Then run the command in every directory here
find /usr/lib/python3.6/ -name "*.pyc" -delete
find /usr/local/lib/python3.6/dist-packages -name "*.pyc" -delete
# etc...
The trap
shell builtin allows catching signals, and other useful conditions, including failed command execution (i.e., a non-zero return status). So if you don't want to explicitly test return status of every single command you can say trap "your shell code" ERR
and the shell code will be executed any time a command returns a non-zero status. For example:
trap "echo script failed; exit 1" ERR
Note that as with other cases of catching failed commands, pipelines need special treatment; the above won't catch false | true
.
>>> def is_near_integer(n, precision=8, get_integer=False):
... if get_integer:
... return int(round(n, precision))
... else:
... return round(n) == round(n, precision)
...
>>> print(is_near_integer(10648 ** (1.0/3)))
True
>>> print(is_near_integer(10648 ** (1.0/3), get_integer=True))
22
>>> for i in [4.9, 5.1, 4.99, 5.01, 4.999, 5.001, 4.9999, 5.0001, 4.99999, 5.000
01, 4.999999, 5.000001]:
... print(i, is_near_integer(i, 4))
...
4.9 False
5.1 False
4.99 False
5.01 False
4.999 False
5.001 False
4.9999 False
5.0001 False
4.99999 True
5.00001 True
4.999999 True
5.000001 True
>>>
Bear in mind that, if you're going to be doing a lot of lookups, there are STL containers that are better for that. I don't know what your application is, but associative containers like std::map may be worth considering.
std::vector is the container of choice unless you have a reason for another, and lookups by value can be such a reason.
This:
<img onerror="this.src='/images/image.png'" src="...">
SIMPLE..
First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)
I have solve this problem in my program using:
number_input = float("{:.1f}".format(float(input())))
list.append(number_input)
Since I find myself rather regularly looking for this exact problem (in the hopes I missed something before...), I finally decided to take the time and write up a small gist to export MySQL queries as CSV files, kinda like https://stackoverflow.com/a/28168869 but based on PHP and with a couple of more options. This was important for my use case, because I need to be able to fine-tune the CSV parameters (delimiter, NULL value handling) AND the files need to be actually valid CSV, so that a simple CONCAT
is not sufficient since it doesn't generate valid CSV files if the values contain line breaks or the CSV delimiter.
Caution: Requires PHP to be installed on the server!
(Can be checked via php -v
)
"Install" mysql2csv
via
wget https://gist.githubusercontent.com/paslandau/37bf787eab1b84fc7ae679d1823cf401/raw/29a48bb0a43f6750858e1ddec054d3552f3cbc45/mysql2csv -O mysql2csv -q && (sha256sum mysql2csv | cmp <(echo "b109535b29733bd596ecc8608e008732e617e97906f119c66dd7cf6ab2865a65 mysql2csv") || (echo "ERROR comparing hash, Found:" ;sha256sum mysql2csv) ) && chmod +x mysql2csv
(download content of the gist, check checksum and make it executable)
Usage example
./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"
generates file /tmp/result.csv
with content
foo,bar
1,2
help for reference
./mysql2csv --help
Helper command to export data for an arbitrary mysql query into a CSV file.
Especially helpful if the use of "SELECT ... INTO OUTFILE" is not an option, e.g.
because the mysql server is running on a remote host.
Usage example:
./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"
cat /tmp/result.csv
Options:
-q,--query=name [required]
The query string to extract data from mysql.
-h,--host=name
(Default: 127.0.0.1) The hostname of the mysql server.
-D,--database=name
The default database.
-P,--port=name
(Default: 3306) The port of the mysql server.
-u,--user=name
The username to connect to the mysql server.
-p,--password=name
The password to connect to the mysql server.
-F,--file=name
(Default: php://stdout) The filename to export the query result to ('php://stdout' prints to console).
-L,--delimiter=name
(Default: ,) The CSV delimiter.
-C,--enclosure=name
(Default: ") The CSV enclosure (that is used to enclose values that contain special characters).
-E,--escape=name
(Default: \) The CSV escape character.
-N,--null=name
(Default: \N) The value that is used to replace NULL values in the CSV file.
-H,--header=name
(Default: 1) If '0', the resulting CSV file does not contain headers.
--help
Prints the help for this command.
Queues
Pros
Cons
Topics
Pros
Cons
i start using npm package called react-html-parser
another possibility is that the server does not handle the OPTIONS request.
There are multiple function to do this work that wrote in bottom based on priority.
Set one or more CSS properties for the set of matched elements.
$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
display: "block",
color: "red",
...
})
Display the matched elements and is roughly equivalent to calling .css("display", "block")
You can display element using .show()
instead
$("div").show()
Set one or more attributes for the set of matched elements.
If target element hasn't style
attribute, you can use this method to add inline style to element.
$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")
You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.
var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red";
// Multiple properties
div.setAttribute("style", "display:block; color:red");
None of the above solutions are going to work.
Try this:
function filter_html($value){
$value = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
return $value;
}
In Linux:
sudo docker ps -aqf "name=containername"
Or in OS X, Windows:
docker ps -aqf "name=containername"
where containername
is your container name.
To avoid getting false positives, as @llia Sidorenko notes, you can use regex anchors like so:
docker ps -aqf "name=^containername$"
explanation:
-q
for quiet. output only the ID-a
for all. works even if your container is not running-f
for filter.^
container name must start with this string$
container name must end with this stringI used something like this if($._data($("a.wine-item-link")[0]).events == null) { ... do something, pretty much bind their event handlers again } to check if my element is bound to any event. It will still say undefined (null) if you have unattached all your event handlers from that element. That is the reason why I am evaluating this in an if expression.
For Apache server, you should check mod_expires for setting Expires and Cache-Control headers.
Alternatively, you can use Header directive to add Cache-Control on your own:
Header set Cache-Control "max-age=290304000, public"
This code worked for me:
if (strpos(shell_exec('/usr/local/apache/bin/apachectl -l'), 'mod_rewrite') !== false) echo "mod_rewrite enabled";
else echo "mod_rewrite disabled";
You can try this:
SET LANGUAGE SPANISH
DECLARE @startDate DATE = GETDATE() -- Your start date
DECLARE @endDate DATE = DATEADD(MONTH, 16, GETDATE()) -- Your end date
DECLARE @years INT = YEAR(@endDate) - YEAR(@startDate)
CREATE TABLE #TMP_YEARS (
[year] INT
)
-- Get all posible years between the start and end date
WHILE @years >= 0
BEGIN
INSERT INTO #TMP_YEARS
([year])
SELECT YEAR(@startDate) + @years
SET @years = @years - 1
END
;WITH [days]([day]) AS -- Posible days at a month
(
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL -- days lower than 10
SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 UNION ALL SELECT 19 UNION ALL -- days lower than 20
SELECT 20 UNION ALL SELECT 21 UNION ALL SELECT 22 UNION ALL SELECT 23 UNION ALL SELECT 24 UNION ALL SELECT 25 UNION ALL SELECT 26 UNION ALL SELECT 27 UNION ALL SELECT 28 UNION ALL SELECT 29 UNION ALL -- days lower than 30
SELECT 30 UNION ALL SELECT 31 -- days higher 30
),
[months]([month]) AS -- All months at a year
(
SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
)
SELECT CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) as [date]
FROM #TMP_YEARS a
CROSS JOIN [months] n -- Join all years with all months
INNER JOIN [days] d on DAY(EOMONTH(CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + CONVERT(VARCHAR, DAY(EOMONTH(CAST(CONVERT(VARCHAR, a.[year]) + '-' + CONVERT(varchar, n.[month]) + '-15' AS DATE)))))) >= d.[day] AND -- The number of the day can't be higher than the last day of the current month and the current year
CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) <= ISNULL(@endDate, GETDATE()) AND -- The current date can't be higher than the end date
CONVERT(VARCHAR, a.[year]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, n.[month]))) + CONVERT(VARCHAR, n.[month]) + '-' + REPLICATE('0', 2 - LEN(CONVERT(VARCHAR, d.[day]))) + CONVERT(VARCHAR, d.[day]) >= ISNULL(@startDate, GETDATE()) -- The current date should be higher than the start date
ORDER BY a.[year] ASC, n.[month] ASC, d.[day] ASC
The output will be something like this, you can format the date as you like:
2019-01-24
2019-01-25
2019-01-26
2019-01-27
2019-01-28
2019-01-29
2019-01-30
2019-01-31
2019-02-01
2019-02-02
2019-02-03
2019-02-04
2019-02-05
2019-02-06
2019-02-07
2019-02-08
2019-02-09
...
By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.
If our python list is:-
l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
To find occurrence of every items in the python list use following:-
\>>from collections import Counter
\>>c=Counter(l)
\>>print c
Counter({'1': 6, '2': 4, '7': 3, '10': 2})
To find most/highest occurrence of items in the python list:-
\>>k=c.most_common()
\>>k
[('1', 6), ('2', 4), ('7', 3), ('10', 2)]
For Highest one:-
\>>k[0][1]
6
For the item just use k[0][0]
\>>k[0][0]
'1'
For nth highest item and its no of occurrence in the list use follow:-
**for n=2 **
\>>print k[n-1][0] # For item
2
\>>print k[n-1][1] # For value
4
The splat and spread operators are part of ES6, the planned next version of Javascript. So far only Firefox supports them. This code works in FF16+:
var arr = ['quick', 'brown', 'lazy'];
var sprintf = function(str, ...args)
{
for (arg of args) {
str = str.replace(/%s/, arg);
}
return str;
}
sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]);
sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');
Note the awkard syntax for spread. The usual syntax of sprintf('The %s %s fox jumps over the %s dog.', ...arr);
is not yet supported. You can find an ES6 compatibility table here.
Note also the use of for...of
, another ES6 addition. Using for...in
for arrays is a bad idea.
I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;
string data = "phone_number=19735559042";
byte[] dataStream = Encoding.UTF8.GetBytes(data);
request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
Use two single-quotes
SQL> SELECT 'D''COSTA' name FROM DUAL;
NAME
-------
D'COSTA
Alternatively, use the new (10g+) quoting method:
SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;
NAME
-------
D'COSTA
The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.
.imagetest img {
transform: rotate(270deg);
...
margin: 10px 0px;
}
The amount will depend on the difference in height x width of the image.
You may also need to add display:inline-block;
or display:block
to get it to recognize the margin parameter.
the format for the image you have chosen must be 16x16 pixels or 32x32 pixels, using either 8-bit or 24-bit colors. The format of the image must be one of PNG (a W3C standard), GIF, or ICO. - How to Add a Favicon to your Site - QA @ W3C
I just found out that the following works:
https://www.youtube.com/embed/[video_id]?start=[start_at_second]&end=[end_at_second]
Note: the time must be an integer number of seconds (e.g. 119, not 1m59s).
I think maybe you are implementing the OnClickListener in the wrong place - usually you should definitely implement an OnItemClickListener in your Activity and set it on the ListView instead, or you will get problems with your events...
I was also trying to run Spring Boot application in Eclipse, without any plugins.
Step 1
Right click on your project. Select "Run As" -> "Maven build...". Then in "Goals" field, enter "spring-boot:run". Apply & Run.
After this you do not have to Run again.
Step 2
After making any change, clean your project. After cleaning, it automatically builds the project once. Then when you will refresh your pages on browser, change will be reflected.
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);
As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.
var mockFileBrowser = new Mock<FileBrowser>();
instead of
var mockFileBrowser = new Mock<IFileBrowser>();
from tkinter import *
import time
tk=Tk()
def clock():
t=time.strftime('%I:%M:%S',time.localtime())
if t!='':
label1.config(text=t,font='times 25')
tk.after(100,clock)
label1=Label(tk,justify='center')
label1.pack()
clock()
tk.mainloop()
Without an access modifier, a class member is accessible throughout the package in which it's declared. You can learn more from the Java Language Specification, §6.6.
Members of an interface are always publicly accessible, whether explicitly declared or not.
Many times, we need to hide some parts of codes while writing a long code.
Example: - Just on clicking "Code show/hide", we can hide 3 lines of codes.
So here is the function that you need to define for partially hiding few part of codes and then call it whenever you want to hide some code:
from IPython.display import HTML
def hide_toggle(for_next=False):
this_cell = """$('div.cell.code_cell.rendered.selected')""" ; next_cell = this_cell + '.next()';
toggle_text = 'Code show/hide' # text shown on toggle link
target_cell = this_cell ; js_hide_current = ''
if for_next:
target_cell = next_cell; toggle_text += ' next cell';
js_hide_current = this_cell + '.find("div.input").hide();'
js_f_name = 'code_toggle_{}'.format(str(random.randint(1,2**64)))
html = """<script>
function {f_name}() {{{cell_selector}.find('div.input').toggle(); }}
{js_hide_current}
</script>
<a href="javascript:{f_name}()">{toggle_text}</a>
""".format(f_name=js_f_name,cell_selector=target_cell,js_hide_current=js_hide_current, toggle_text=toggle_text )
return HTML(html)
Once we are ready with function definition, our next task is very easy. Just we need to call the function to hide/show the code.
print("Function for hiding the cell")
hide_toggle()
try {
// THIS for POST+JSON
options.contentType = 'application/json';
options.type = 'POST';
options.data = JSON.stringify(options.data);
// OR THIS for GET+URL-encoded
//options.data = $.param(_.clone(options.data));
console.log('.fetch options = ', options);
collection.fetch(options);
} catch (excp) {
alert(excp);
}
I would use this rule:
RewriteEngine On
RewriteCond %{HTTP_HOST} !=""
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
The first condition checks whether the Host value is not empty (in case of HTTP/1.0); the second checks whether the the Host value does not begin with www.
; the third checks for HTTPS (%{HTTPS}
is either on
or off
, so %{HTTPS}s
is either ons
or offs
and in case of ons
the s
is matched). The substitution part of RewriteRule
then just merges the information parts to a full URL.
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity
, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent
in an onClick
:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Then receive the result:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath))
, which is different from the code from developer.android.com. The original code gave me a FileNotFoundException
.
You'll want to check your docs for your version of gcc & ld:
However for me (OS X gcc 4.0.1) I find these for ld
-dead_strip
Remove functions and data that are unreachable by the entry point or exported symbols.
-dead_strip_dylibs
Remove dylibs that are unreachable by the entry point or exported symbols. That is, suppresses the generation of load command commands for dylibs which supplied no symbols during the link. This option should not be used when linking against a dylib which is required at runtime for some indirect reason such as the dylib has an important initializer.
And this helpful option
-why_live symbol_name
Logs a chain of references to symbol_name. Only applicable with
-dead_strip
. It can help debug why something that you think should be dead strip removed is not removed.
There's also a note in the gcc/g++ man that certain kinds of dead code elimination are only performed if optimization is enabled when compiling.
While these options/conditions may not hold for your compiler, I suggest you look for something similar in your docs.
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
After executing
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true
check your .m2 repository folder (/com/oracle/ojdbc6/11.2.0.3) to see if ojdbc6.jar exists. If not check your maven repository settings under $M2_HOME/conf/settings.xml
You could set width
of div using Javascript and add white-space:pre-wrap
to p tag
, this break your textarea content at end of each line.
document.querySelector("button").onclick = function gt(){_x000D_
var card = document.createElement('div');_x000D_
card.style.width = "160px";_x000D_
card.style.background = "#eee";_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.style.whiteSpace = "pre-wrap";_x000D_
card.append(post);_x000D_
post.append(postText);_x000D_
document.body.append(card);_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required>_x000D_
Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea>_x000D_
<br><br>_x000D_
<button>Copy!!</button>
_x000D_
All user installed apks are located in /data/app/, but you can only access this if you are rooted(afaik, you can try without root and if it doesn't work, rooting isn't hard. I suggest you search xda-developers for rooting instructions)
Use Root explorer or ES File Explorer to access /data/app/ (you have to keep going "up" until you reach the root directory /, kind of like C: in windows, before you can see the data directory(folder)). In ES file explorer you must also tick a checkbox in settings to allow going up to the root directory.
When you are in there you will see all your applications apks, though they might be named strangely. Just copy the wanted .apk and paste in the sd card, after that you can copy it to your computer and when you want to install it just open the .apk in a file manager (be sure to have install from unknown sources enabled in android settings). Even if you only want to send over bluetooth I would recommend copying it to the SD first.
PS Note that paid apps probably won't work being copied this way, since they usually check their licence online. PPS Installing an app this way may not link it with google play(you won't see it in my apps and it won't get updates).
.youtube-thumb img {display:block;} or .youtube-thumb img {float:left;}
If you are building the code yourself, then this issue could be overcome by giving "-target 1.5" to the java compiler (or by setting the corresponding option in your IDE or your build config).
You can use this
whereDate('date', '=', $date)
If you give whereDate then compare only date from datetime field.
Release notes iOS 3.2 (External Display Support) and iOS 4.0 (Inherited Improvements) mentions that it should be possible to connect external displays to iOS 4.0 devices.
But you still have to jailbreak if you would mirror your iPhone screen...
Related SO Question with updates
you can do it with pd.date_range() and Timestamp. Let's say you have read a csv file with a date column using parse_dates option:
df = pd.read_csv('my_file.csv', parse_dates=['my_date_col'])
Then you can define a date range index :
rge = pd.date_range(end='15/6/2020', periods=2)
and then filter your values by date thanks to a map:
df.loc[df['my_date_col'].map(lambda row: row.date() in rge)]
HandlerThread
is better option to normal java Threads in Android .
requestHandler
post
a Runnable
task on requestHandler
Communication with UI Thread from HandlerThread
Handler
with Looper
for main thread : responseHandler
and override handleMessage
methodRunnable
task of other Thread ( HandlerThread
in this case), call sendMessage
on responseHandler
sendMessage
result invocation of handleMessage
in responseHandler
.Message
and process it, update UIExample: Update TextView
with data received from a web service. Since web service should be invoked on non-UI thread, created HandlerThread
for Network Operation. Once you get the content from the web service, send message to your main thread (UI Thread) handler and that Handler
will handle the message and update UI.
Sample code:
HandlerThread handlerThread = new HandlerThread("NetworkOperation");
handlerThread.start();
Handler requestHandler = new Handler(handlerThread.getLooper());
final Handler responseHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
txtView.setText((String) msg.obj);
}
};
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
Log.d("Runnable", "Before IO call");
URL page = new URL("http://www.your_web_site.com/fetchData.jsp");
StringBuffer text = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
String line;
while ((line = buff.readLine()) != null) {
text.append(line + "\n");
}
Log.d("Runnable", "After IO call:"+ text.toString());
Message msg = new Message();
msg.obj = text.toString();
responseHandler.sendMessage(msg);
} catch (Exception err) {
err.printStackTrace();
}
}
};
requestHandler.post(myRunnable);
Useful articles:
handlerthreads-and-why-you-should-be-using-them-in-your-android-apps
A stream is an object used to transfer data. There is a generic stream class System.IO.Stream
, from which all other stream classes in .NET are derived. The Stream
class deals with bytes.
The concrete stream classes are used to deal with other types of data than bytes. For example:
FileStream
class is used when the outside source is a fileMemoryStream
is used to store data in memorySystem.Net.Sockets.NetworkStream
handles network dataReader/writer streams such as StreamReader
and StreamWriter
are not streams - they are not derived from System.IO.Stream
, they are designed to help to write and read data from and to stream!
If you were using SQL 2012 or above you could use the CONCAT function:
SELECT CONCAT(field1, field2, field3) FROM table1
NULL fields won't break your concatenation.
@bummi - Thanks for the comment - edited my answer to correspond to it.
To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)
For example this escapes the % symbol, using \ as the escape char:
select * from table where myfield like '%15\% off%' ESCAPE '\'
If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:
set @myString = replace(
replace(
replace(
replace( @myString
, '\', '\\' )
, '%', '\%' )
, '_', '\_' )
, '[', '\[' )
(Note that you have to escape your escape char too, and make sure that's the inner replace
so you don't escape the ones added from the other replace
statements). Then you can use something like this:
select * from table where myfield like '%' + @myString + '%' ESCAPE '\'
Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.
Because they do not use the SQL import wizard, the steps would be as follows:
Right click on the database in the option tasks to import data,
Once the wizard is open, we select the type of data to be implied. In this case it would be the
Flat file source
We select the CSV file, you can configure the data type of the tables in the CSV, but it is best to bring it from the CSV.
SQL client
Depending on our type of authentication we select it, once this is done, a very important option comes.
Enable id insert
(usually not starting from 1), instead if we have a column with the id in the CSV we select the enable id insert, the next step is to end the wizard, we can review the changes here.
On the other hand, in the following window may come alerts, or warnings the ideal is to ignore this, only if they leave error is necessary to pay attention.
I think git fetch is what your looking for.
It will pull the changes and objects without committing them to your local repo's index.
They can be merged later with git merge.
Edit: Further Explination
Straight from the Git- SVN Crash Course link
Now, how do you get any new changes from a remote repository? You fetch them:
git fetch http://host.xz/path/to/repo.git/
At this point they are in your repository and you can examine them using:
git log origin
You can also diff the changes. You can also use git log HEAD..origin to see just the changes you don't have in your branch. Then if would like to merge them - just do:
git merge origin
Note that if you don't specify a branch to fetch, it will conveniently default to the tracking remote.
Reading the man page is honestly going to give you the best understanding of options and how to use it.
I'm just trying to do this by examples and memory, I don't currently have a box to test out on. You should look at:
git log -p //log with diff
A fetch can be undone with git reset --hard (link) , however all uncommitted changes in your tree will be lost as well as the changes you've fetched.
CD E:\Documents and Settings\All Users\Application Data
E:\Documents and Settings\All Users\Application Data>REGSVR32 xyz.dll
If you use .Net 4.5 you can also use standard .Net json serializer:
using System.Runtime.Serialization.Json;
...
Stream jsonSource = ...; // serializer will read data stream
var s = new DataContractJsonSerializer(typeof(string[][]));
var j = (string[][])s.ReadObject(jsonSource);
In .Net 4.5 and older you can use JavaScriptSerializer class:
using System.Web.Script.Serialization;
...
JavaScriptSerializer serializer = new JavaScriptSerializer();
string[][] list = serializer.Deserialize<string[][]>(json);
mysqli executable sample code:
<?php
$db = new mysqli("localhost", "user", "password", "YourDatabaseName");
if ($db->connect_errno) die ($db->connect_error);
$table=$db->prepare("SHOW TABLE STATUS FROM YourDatabaseName");
$table->execute();
$sonuc = $table->get_result();
while ($satir=$sonuc->fetch_assoc()){
if ($satir["Name"]== "YourTableName"){
$ai[$satir["Name"]]=$satir["Auto_increment"];
}
}
$LastAutoIncrement=$ai["YourTableName"];
echo $LastAutoIncrement;
?>
In Java land typically "PO" means "plain old". The rest can be tricky, so I'm guessing that your example (in the context of Java) is "plain old class object".
some other examples
Generally the first 2 package "words" are your web address in reverse. (You'd have 3 here as convention, if you had a subdomain.)
So something stackoverflow produces would likely be in package com.stackoverflow.whatever.customname
something asp.net produces might be called net.asp.whatever.customname.omg.srsly
something from mysubdomain.toplevel.com would be com.toplevel.mysubdomain.whatever
Beyond that simple convention, the sky's the limit. This is an old linux convention for something that I cannot recall exactly...
This is more than a bit late, but you can extend the regex expression to account for scientific notation too.
import re
# Format is [(<string>, <expected output>), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
('hello X42 I\'m a Y-32.35 string Z30',
['42', '-32.35', '30']),
('he33llo 42 I\'m a 32 string -30',
['33', '42', '32', '-30']),
('h3110 23 cat 444.4 rabbit 11 2 dog',
['3110', '23', '444.4', '11', '2']),
('hello 12 hi 89',
['12', '89']),
('4',
['4']),
('I like 74,600 commas not,500',
['74,600', '500']),
('I like bad math 1+2=.001',
['1', '+2', '.001'])]
for s, r in ss:
rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
if rr == r:
print('GOOD')
else:
print('WRONG', rr, 'should be', r)
Gives all good!
Additionally, you can look at the AWS Glue built-in regex
You should be using the unwind library.
unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
unsigned long a[100];
int ctr = 0;
while (unw_step(&cursor) > 0) {
unw_get_reg(&cursor, UNW_REG_IP, &ip);
unw_get_reg(&cursor, UNW_REG_SP, &sp);
if (ctr >= 10) break;
a[ctr++] = ip;
}
Your approach also would work fine unless you make a call from a shared library.
You can use the addr2line
command on Linux to get the source function / line number of the corresponding PC.
I found it easiest to just read the entire line into one column then parse out the data using XML.
IF (OBJECT_ID('tempdb..#data') IS NOT NULL) DROP TABLE #data
CREATE TABLE #data (data VARCHAR(MAX))
BULK INSERT #data FROM 'E:\filefromabove.txt' WITH (FIRSTROW = 2, ROWTERMINATOR = '\n')
IF (OBJECT_ID('tempdb..#dataXml') IS NOT NULL) DROP TABLE #dataXml
CREATE TABLE #dataXml (ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, data XML)
INSERT #dataXml (data)
SELECT CAST('<r><d>' + REPLACE(data, '|', '</d><d>') + '</d></r>' AS XML)
FROM #data
SELECT d.data.value('(/r//d)[1]', 'varchar(max)') AS col1,
d.data.value('(/r//d)[2]', 'varchar(max)') AS col2,
d.data.value('(/r//d)[3]', 'varchar(max)') AS col3
FROM #dataXml d
File.expand_path File.dirname(__FILE__)
will return the directory relative to the file this command is called from.
But Dir.pwd
returns the working directory (results identical to executing pwd
in your terminal)
Did you try
:set encoding=utf-8
:set fileencoding=utf-8
?
import traceback
traceback.print_stack()
another way to access a column by number is to use a mapping dictionary where the key is the column name and the value is the column number
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 4),
index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
dct={'A':0,'B':1,'C':2,'D':3}
columns=df.columns
print(df.iloc[:,dct['D']])
Delete entire node "Element" (inside "Connections" tree) from XML file, used by version 18 or higher.
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml
It should work fine. Don't use tuple
, list
or other special names as a variable name. It's probably what's causing your problem.
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
>>> tuple = 'whoops' # Don't do this
>>> tuple(l)
TypeError: 'tuple' object is not callable
You need to use the .format()
function.
MM
- Month number
MMM
- Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
It is a reference to the current file name. In the file foo.rb
, __FILE__
would be interpreted as "foo.rb"
.
Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:
# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__
Running ruby test.rb
will output
test.rb
/full/path/to/dir2/test.rb
Self-explanatory code follows which first creates a std::tm
corresponding to 10-10-2012 12:38:40, converts that to a std::chrono::system_clock::time_point
, adds 0.123456 seconds, and then prints that out by converting back to a std::tm
. How to handle the fractional seconds is in the very last step.
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
// Create 10-10-2012 12:38:40 UTC as a std::tm
std::tm tm = {0};
tm.tm_sec = 40;
tm.tm_min = 38;
tm.tm_hour = 12;
tm.tm_mday = 10;
tm.tm_mon = 9;
tm.tm_year = 112;
tm.tm_isdst = -1;
// Convert std::tm to std::time_t (popular extension)
std::time_t tt = timegm(&tm);
// Convert std::time_t to std::chrono::system_clock::time_point
std::chrono::system_clock::time_point tp =
std::chrono::system_clock::from_time_t(tt);
// Add 0.123456 seconds
// This will not compile if std::chrono::system_clock::time_point has
// courser resolution than microseconds
tp += std::chrono::microseconds(123456);
// Now output tp
// Convert std::chrono::system_clock::time_point to std::time_t
tt = std::chrono::system_clock::to_time_t(tp);
// Convert std::time_t to std::tm (popular extension)
tm = std::tm{0};
gmtime_r(&tt, &tm);
// Output month
std::cout << tm.tm_mon + 1 << '-';
// Output day
std::cout << tm.tm_mday << '-';
// Output year
std::cout << tm.tm_year+1900 << ' ';
// Output hour
if (tm.tm_hour <= 9)
std::cout << '0';
std::cout << tm.tm_hour << ':';
// Output minute
if (tm.tm_min <= 9)
std::cout << '0';
std::cout << tm.tm_min << ':';
// Output seconds with fraction
// This is the heart of the question/answer.
// First create a double-based second
std::chrono::duration<double> sec = tp -
std::chrono::system_clock::from_time_t(tt) +
std::chrono::seconds(tm.tm_sec);
// Then print out that double using whatever format you prefer.
if (sec.count() < 10)
std::cout << '0';
std::cout << std::fixed << sec.count() << '\n';
}
For me this outputs:
10-10-2012 12:38:40.123456
Your std::chrono::system_clock::time_point
may or may not be precise enough to hold microseconds.
Update
An easier way is to just use this date library. The code simplifies down to (using C++14 duration literals):
#include "date.h"
#include <iostream>
#include <type_traits>
int
main()
{
using namespace date;
using namespace std::chrono;
auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
static_assert(std::is_same<decltype(t),
time_point<system_clock, microseconds>>{}, "");
std::cout << t << '\n';
}
which outputs:
2012-10-10 12:38:40.123456
You can skip the static_assert
if you don't need to prove that the type of t
is a std::chrono::time_point
.
If the output isn't to your liking, for example you would really like dd-mm-yyyy ordering, you could:
#include "date.h"
#include <iomanip>
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
using namespace std;
auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
auto dp = floor<days>(t);
auto time = make_time(t-dp);
auto ymd = year_month_day{dp};
cout.fill('0');
cout << ymd.day() << '-' << setw(2) << static_cast<unsigned>(ymd.month())
<< '-' << ymd.year() << ' ' << time << '\n';
}
which gives exactly the requested output:
10-10-2012 12:38:40.123456
Update
Here is how to neatly format the current time UTC with milliseconds precision:
#include "date.h"
#include <iostream>
int
main()
{
using namespace std::chrono;
std::cout << date::format("%F %T\n", time_point_cast<milliseconds>(system_clock::now()));
}
which just output for me:
2016-10-17 16:36:02.975
C++17 will allow you to replace time_point_cast<milliseconds>
with floor<milliseconds>
. Until then date::floor
is available in "date.h"
.
std::cout << date::format("%F %T\n", date::floor<milliseconds>(system_clock::now()));
In C++20 this is now simply:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
auto t = sys_days{10d/10/2012} + 12h + 38min + 40s + 123456us;
std::cout << t << '\n';
}
Or just:
std::cout << std::chrono::system_clock::now() << '\n';
std::format
will be available to customize the output.
In intellij8 I was using a specific plugin "Jar Tool" that is configurable and allows to pack a JAR archive.
The build-in raw_input should help.
for i in range(3):
print ("So much work to do!")
k = raw_input("Press any key to continue...")
print ("Ok, back to work.")
Make it so that your function accepts a const std::string&
instead of by-value. Not only does this avoid the copy and is therefore always preferable when accepting strings into functions, but it also enables the compiler to construct a temporary std::string
from the char[]
that you're giving it. :)
Here's a chart that summarises some of the most important conversions in pandas.
Conversions to string are trivial .astype(str)
and are not shown in the figure.
Note that "conversions" in this context could either refer to converting text data into their actual data type (hard conversion), or inferring more appropriate data types for data in object columns (soft conversion). To illustrate the difference, take a look at
df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes
a object
b object
dtype: object
# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes
a int64
b int64
dtype: object
# Infers better data types for object data - soft conversion
df.infer_objects().dtypes
a object # no change
b int64
dtype: object
# Same as infer_objects, but converts to equivalent ExtensionType
df.convert_dtypes().dtypes
C:\path\to\eclipse\eclipse -clean
Then change the working project directory to something different. It should work after that.
And now for something completely different.
If you want a really fast answer in some constrained context when strings are not rotation of one another
Agreed, it can fail, but it is very fast to say if strings don't match and if they match you can still use another algorithm like string concatenation to check.
1.2975118E7
is scientific notation.
1.2975118E7 = 1.2975118 * 10^7 = 12975118
Also, Math.round(f)
returns an integer. You can't use it to get your desired format x.xx
.
You could use String.format
.
String s = String.format("%.2f", 1.2975118);
// 1.30
Use return statement anywhere you want to exit from function.
if(somecondtion)
return;
if(somecondtion)
return false;
The Rob Evans anwser works correctly for me but when I use request.abort(), it occurs to throw a socket hang up error which stays unhandled.
I had to add an error handler for the request object :
var options = { ... }
var req = http.request(options, function(res) {
// Usual stuff: on(data), on(end), chunks, etc...
}
req.on('socket', function (socket) {
socket.setTimeout(myTimeout);
socket.on('timeout', function() {
req.abort();
});
}
req.on('error', function(err) {
if (err.code === "ECONNRESET") {
console.log("Timeout occurs");
//specific error treatment
}
//other error treatment
});
req.write('something');
req.end();
I solved this by changing the file path in the browser:
c/XAMPP/htdocs/myfile.html
localhost/myfile.html
(message.length() + 152) / 153
This will give a "rounded up" integer.
I have just include Maven
integration plug-in with Eclipse
:
Just follow the bellow steps:
In eclipse
, from upper menu item select- Help
->click on Install New Software..
-> then click on Add
button.
set the MavenAPI
at name text box and http://download.eclipse.org/technology/m2e/releases
at location text box.
press OK
and select the Maven
project and install by clicking next
.
I am facing some issue with menu change when fragment changes in ViewPager. I ended up implemented below code.
DashboardFragment
public class DashboardFragment extends BaseFragment {
private Context mContext;
private TabLayout mTabLayout;
private ViewPager mViewPager;
private DashboardPagerAdapter mAdapter;
private OnModuleChangeListener onModuleChangeListener;
private NavDashBoardActivity activityInstance;
public void setOnModuleChangeListener(OnModuleChangeListener onModuleChangeListener) {
this.onModuleChangeListener = onModuleChangeListener;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dashboard_fragment, container, false);
}
//pass -1 if you want to get it via pager
public Fragment getFragmentFromViewpager(int position) {
if (position == -1)
position = mViewPager.getCurrentItem();
return ((Fragment) (mAdapter.instantiateItem(mViewPager, position)));
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContext = getActivity();
activityInstance = (NavDashBoardActivity) getActivity();
mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
final List<EnumUtils.Module> moduleToShow = getModuleToShowList();
mViewPager.setOffscreenPageLimit(moduleToShow.size());
for(EnumUtils.Module module :moduleToShow)
mTabLayout.addTab(mTabLayout.newTab().setText(EnumUtils.Module.getTabText(module)));
updateTabPagerAndMenu(0 , moduleToShow);
mAdapter = new DashboardPagerAdapter(getFragmentManager(),moduleToShow);
mViewPager.setOffscreenPageLimit(mAdapter.getCount());
mViewPager.setAdapter(mAdapter);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(final TabLayout.Tab tab) {
mViewPager.post(new Runnable() {
@Override
public void run() {
mViewPager.setCurrentItem(tab.getPosition());
}
});
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//added to redraw menu on scroll
}
@Override
public void onPageSelected(int position) {
updateTabPagerAndMenu(position , moduleToShow);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
//also validate other checks and this method should be in SharedPrefs...
public static List<EnumUtils.Module> getModuleToShowList(){
List<EnumUtils.Module> moduleToShow = new ArrayList<>();
moduleToShow.add(EnumUtils.Module.HOME);
moduleToShow.add(EnumUtils.Module.ABOUT);
return moduleToShow;
}
public void setCurrentTab(final int position){
if(mViewPager != null){
mViewPager.postDelayed(new Runnable() {
@Override
public void run() {
mViewPager.setCurrentItem(position);
}
},100);
}
}
private Fragment getCurrentFragment(){
return mAdapter.getCurrentFragment();
}
private void updateTabPagerAndMenu(int position , List<EnumUtils.Module> moduleToShow){
//it helps to change menu on scroll
//http://stackoverflow.com/a/27984263/3496570
//No effect after changing below statement
ActivityCompat.invalidateOptionsMenu(getActivity());
if(mTabLayout != null)
mTabLayout.getTabAt(position).select();
if(onModuleChangeListener != null){
if(activityInstance != null){
activityInstance.updateStatusBarColor(
EnumUtils.Module.getStatusBarColor(moduleToShow.get(position)));
}
onModuleChangeListener.onModuleChanged(moduleToShow.get(position));
mTabLayout.setSelectedTabIndicatorColor(EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
mTabLayout.setTabTextColors(ContextCompat.getColor(mContext,android.R.color.black)
, EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
}
}
}
dashboardfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabBackground="@android:color/white"
app:tabGravity="fill"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="@android:color/black"
app:tabTextColor="@android:color/black" />
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</LinearLayout>
DashboardPagerAdapter
public class DashboardPagerAdapter extends FragmentPagerAdapter {
private List<EnumUtils.Module> moduleList;
private Fragment mCurrentFragment = null;
public DashboardPagerAdapter(FragmentManager fm, List<EnumUtils.Module> moduleList){
super(fm);
this.moduleList = moduleList;
}
@Override
public Fragment getItem(int position) {
return EnumUtils.Module.getDashboardFragment(moduleList.get(position));
}
@Override
public int getCount() {
return moduleList.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
public int getModulePosition(EnumUtils.Module moduleName){
for(int x = 0 ; x < moduleList.size() ; x++){
if(moduleList.get(x).equals(moduleName))
return x;
}
return -1;
}
}
And in each page of Fragment setHasOptionMenu(true)
in onCreate and implement onCreateOptionMenu
. then it will work properly.
dASHaCTIVITY
public class NavDashBoardActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Context mContext;
private DashboardFragment dashboardFragment;
private Toolbar mToolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_dash_board);
mContext = NavDashBoardActivity.this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(ContextCompat.getColor(mContext,R.color.yellow_action_bar));
}
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
updateToolbarText(new ToolbarTextBO("NCompass " ,""));
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//onclick of back button on Navigation it will popUp fragment...
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!toggle.isDrawerIndicatorEnabled()) {
getSupportFragmentManager().popBackStack();
}
}
});
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);//It helps to show icon on Navigation
updateNavigationMenuItem(navigationView);
navigationView.setNavigationItemSelectedListener(this);
//Left Drawer Upper Section
View headerLayout = navigationView.getHeaderView(0); // 0-index header
TextView userNameTv = (TextView) headerLayout.findViewById(R.id.tv_user_name);
userNameTv.setText(AuthSharePref.readUserLoggedIn().getFullName());
RoundedImageView ivUserPic = (RoundedImageView) headerLayout.findViewById(R.id.iv_user_pic);
ivUserPic.setImageResource(R.drawable.profile_img);
headerLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//close drawer and add a fragment to it
drawer.closeDrawers();//also try other methods..
}
});
//ZA code starts...
dashboardFragment = new DashboardFragment();
dashboardFragment.setOnModuleChangeListener(new OnModuleChangeListener() {
@Override
public void onModuleChanged(EnumUtils.Module module) {
if(mToolbar != null){
mToolbar.setBackgroundColor(EnumUtils.Module.getModuleColor(module));
if(EnumUtils.Module.getMenuID(module) != -1)
navigationView.getMenu().findItem(EnumUtils.Module.getMenuID(module)).setChecked(true);
}
}
});
addBaseFragment(dashboardFragment);
backStackListener();
}
public void updateStatusBarColor(int colorResourceID){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(colorResourceID);
}
}
private void updateNavigationMenuItem(NavigationView navigationView){
List<EnumUtils.Module> modules = DashboardFragment.getModuleToShowList();
if(!modules.contains(EnumUtils.Module.MyStores)){
navigationView.getMenu().findItem(R.id.nav_my_store).setVisible(false);
}
if(!modules.contains(EnumUtils.Module.Livewall)){
navigationView.getMenu().findItem(R.id.nav_live_wall).setVisible(false);
}
}
private void backStackListener(){
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() >= 1)
{
toggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
toggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); //set your own
///toggle.setDrawerArrowDrawable();
///toggle.setDrawerIndicatorEnabled(false); // this will hide hamburger image
///Toast.makeText(mContext,"Update to Arrow",Toast.LENGTH_SHORT).show();
}
else{
toggle.setDrawerIndicatorEnabled(true);
}
if(getSupportFragmentManager().getBackStackEntryCount() >0){
if(getCurrentFragment() instanceof DashboardFragment){
Fragment subFragment = ((DashboardFragment) getCurrentFragment())
.getViewpager(-1);
}
}
else{
}
}
});
}
private void updateToolBarTitle(String title){
getSupportActionBar().setTitle(title);
}
public void updateToolBarColor(String hexColor){
if(mToolbar != null)
mToolbar.setBackgroundColor(Color.parseColor(hexColor));
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (drawer.isDrawerOpen(GravityCompat.START))
getMenuInflater().inflate(R.menu.empty, menu);
return super.onCreateOptionsMenu(menu);//true is wriiten first..
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home)
{
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
} else
drawer.openDrawer(GravityCompat.START);
}
return false;///true;
}
return false;// false so that fragment can also handle the menu event. Otherwise it is handled their
///return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_my_store) {
// Handle the camera action
dashboardFragment.setCurrentTab(EnumUtils.Module.MyStores);
}
}else if (id == R.id.nav_log_out) {
Dialogs.logOut(mContext);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void updateToolbarText(ToolbarTextBO toolbarTextBO){
mToolbar.setTitle("");
mToolbar.setSubtitle("");
if(toolbarTextBO.getTitle() != null && !toolbarTextBO.getTitle().isEmpty())
mToolbar.setTitle(toolbarTextBO.getTitle());
if(toolbarTextBO.getDescription() != null && !toolbarTextBO.getDescription().isEmpty())
mToolbar.setSubtitle(toolbarTextBO.getDescription());*/
}
@Override
public void onPostCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
}
None of the above worked for me Swift 5 for Local Video Player
after reading apple documentation I was able to create simple example for playing video from Local resources
Here is code snip
import UIKit
import AVKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play
}
@IBAction func playLocalVideo(_ sender: Any) {
guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else {
return
}
let videoURL = NSURL(fileURLWithPath: path)
// Create an AVPlayer, passing it the local video url path
let player = AVPlayer(url: videoURL as URL)
let controller = AVPlayerViewController()
controller.player = player
present(controller, animated: true) {
player.play()
}
}
}
PS: Make sure you don't forget to add and copy video named "SampleVideo.mp4" in project
It's easier for me to think in these terms, but borrowing from other answers. The value you want is located in the series:
df[*column*][*row*]
where column and row point to the value you want returned. For your example, column is 'A' and for row you use a mask:
df['B'] == 3
To get the value from the series there are several options:
df['A'][df['B'] == 3].values[0]
df['A'][df['B'] == 3].iloc[0]
df['A'][df['B'] == 3].to_numpy()[0]
If You using Android 9.0 with legacy jar than you have to use. in your mainfest file.
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
To expand on this a bit more:
If you are running a server you either need to use TCP_KEEPALIVE to monitor the client connections, or do something similar yourself, or have knowledge about the data/protocol that you are running over the connection.
Basically, if the connection gets killed (i.e. not properly closed) then the server won't notice until it tries to write something to the client, which is what the keepalive achieves for you. Alternatively, if you know the protocol better, you could just disconnect on an inactivity timeout anyway.
I found that sometimes JavaScript doesn't allow me to click the checkbox because was working with the element by onchange
event.
And that sentence helps me to allow the problem:
driver.findElement(By.xpath(".//*[@id='theID']")).sendKeys(Keys.SPACE);
Using numpy:
In [1]: import numpy as np
In [2]: np.log2?
Type: function
Base Class: <type 'function'>
String Form: <function log2 at 0x03049030>
Namespace: Interactive
File: c:\python26\lib\site-packages\numpy\lib\ufunclike.py
Definition: np.log2(x, y=None)
Docstring:
Return the base 2 logarithm of the input array, element-wise.
Parameters
----------
x : array_like
Input array.
y : array_like
Optional output array with the same shape as `x`.
Returns
-------
y : ndarray
The logarithm to the base 2 of `x` element-wise.
NaNs are returned where `x` is negative.
See Also
--------
log, log1p, log10
Examples
--------
>>> np.log2([-1, 2, 4])
array([ NaN, 1., 2.])
In [3]: np.log2(8)
Out[3]: 3.0
ls = [x if (condition) else None for x in ls]
RewriteEngine On
RewriteCond %{SERVER_PORT} 443
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
This may not solve all of your problems, but the variable you are using inside your function (text) is not the same as the parameter you are passing in (x).
Changing:
function textreplace(x) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
To:
function textreplace(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
seems like it would do some good.
While giving this error it will clearly mention the package name of the app because of which the permission was denied. And just uninstalling the application will not solve the problem. In order to solve problem we need to do the following step:
Problem solved :D
I solved this just created label on desktop with option/parameter --locale en-US
"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vs_installer.exe" --locale en-US
The slickest method woud be to use LINQ:
var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
select file).Count();
cvWaitKey(0)
stops your program until you press a button.
cvWaitKey(10)
doesn't stop your program but wake up and alert to end your program when you press a button. Its used into loops because cvWaitkey
doesn't stop loop.
Normal use
char k;
k=cvWaitKey(0);
if(k == 'ESC')
with k
you can see what key was pressed.
Sometimes above all answer not woking, when you can use below trick
.form-group {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input {_x000D_
padding-left: 1rem;_x000D_
}_x000D_
_x000D_
i {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 50%;_x000D_
transform: translateY(-50%);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">_x000D_
_x000D_
<form role="form">_x000D_
<div class="form-group">_x000D_
<input type="text" class="form-control empty" id="iconified" placeholder="search">_x000D_
<i class="fas fa-search"></i>_x000D_
</div>_x000D_
</form>
_x000D_
To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100
in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application.
If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.
Here is the best and simplest answer. Use try and except calls.
x = randint(1,9)
guess = -1
print "Guess the number below 10:"
while guess != x:
try:
guess = int(raw_input("Guess: "))
if guess < x:
print "Guess higher."
elif guess > x:
print "Guess lower."
else:
print "Correct."
except:
print "You did not put any number."
In Kotlin you can do this...
Service:
class MyService : Service() {
init {
instance = this
}
companion object {
lateinit var instance: MyService
fun terminateService() {
instance.stopSelf()
}
}
}
In your activity (or anywhere in your app for that matter):
btn_terminate_service.setOnClickListener {
MyService.terminateService()
}
Note: If you have any pending intents showing a notification in Android's status bar, you may want to terminate that as well.
You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.
It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.
Make sure you wrap the condition in the correct precedence
ng-disabled="((!product.img) || (!product.name))"
I believe the accepted answer should be:
android:background="?attr/selectableItemBackground"
This is the same as @lory105's answer but it uses the support library for maximum compatibility (the android:
equivalent is only available for API >= 11)
Well given the choice, I'd be using objects. I'd create an object for each record where each object has a children
collection and store them all in an assoc array (/hashtable) where the Id is the key. And blitz through the collection once, adding the children to the relevant children fields. Simple.
But because you're being no fun by restricting use of some good OOP, I'd probably iterate based on:
function PrintLine(int pID, int level)
foreach record where ParentID == pID
print level*tabs + record-data
PrintLine(record.ID, level + 1)
PrintLine(0, 0)
Edit: this is similar to a couple of other entries, but I think it's slightly cleaner. One thing I'll add: this is extremely SQL-intensive. It's nasty. If you have the choice, go the OOP route.
On my Galaxy Nexus with Android 4.2.2, I had the same problem initially, 'adb devices' was showing the device but with offline status (USB debugging was initially active on my device).
These are the steps I took to remedy the situation :
adb devices now lists both device id and no offline.
Here's a one-line solution with mapfile:
$ mapfile -d $'\0' -t arr < <(printf '%s\0' "${arr[@]}" | grep -Pzv "<regexp>")
Example:
$ arr=("Adam" "Bob" "Claire"$'\n'"Smith" "David" "Eve" "Fred")
$ echo "Size: ${#arr[*]} Contents: ${arr[*]}"
Size: 6 Contents: Adam Bob Claire
Smith David Eve Fred
$ mapfile -d $'\0' -t arr < <(printf '%s\0' "${arr[@]}" | grep -Pzv "^Claire\nSmith$")
$ echo "Size: ${#arr[*]} Contents: ${arr[*]}"
Size: 5 Contents: Adam Bob David Eve Fred
This method allows for great flexibility by modifying/exchanging the grep command and doesn't leave any empty strings in the array.
Try this one..
var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
console.log($(this).val());
listCheck .push($(this).val());
});
console.log(listCheck);
// Create a Employee table
create table employee(
id number(10),
name varchar2(100),
salary number(10)
);
======================================================================= //Employee.java
public class Employee {
private int id;
private String name;
private float salary;
//no-arg and parameterized constructors
public Employee(){};
public Employee(int id, String name, float salary){
this.id=id;
this.name=name;
this.salary=salary;
}
//getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String toString(){
return id+" "+name+" "+salary;
}
}
========================================================================= //EmployeeDao.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate nameTemplate;
public void setnameTemplate(NamedParameterJdbcTemplate template) {
this.nameTemplate = template;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// BY using JdbcTemplate
public int saveEmployee(Employee e){
int id = e.getId();
String name = e.getName();
float salary = e.getSalary();
Object p[] = {id, name, salary};
String query="insert into employee values(?,?,?)";
return jdbcTemplate.update(query, p);
/*String query="insert into employee values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";
return jdbcTemplate.update(query);
*/
}
//By using NameParameterTemplate
public void insertEmploye(Employee e) {
String query="insert into employee values (:id,:name,:salary)";
Map<String,Object> map=new HashMap<String,Object>();
map.put("id",e.getId());
map.put("name",e.getName());
map.put("salary",e.getSalary());
nameTemplate.execute(query,map,new MyPreparedStatement());
}
// Updating Employee
public int updateEmployee(Employee e){
String query="update employee set name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";
return jdbcTemplate.update(query);
}
// Deleting a Employee row
public int deleteEmployee(Employee e){
String query="delete from employee where id='"+e.getId()+"' ";
return jdbcTemplate.update(query);
}
//Selecting Single row with condition and also all rows
public int selectEmployee(Employee e){
//String query="select * from employee where id='"+e.getId()+"' ";
String query="select * from employee";
List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
for(Map<String, Object> row : rows){
String id = row.get("id").toString();
String name = (String)row.get("name");
String salary = row.get("salary").toString();
System.out.println(id + " " + name + " " + salary );
}
return 1;
}
// Can use MyrowMapper class an implementation class for RowMapper interface
public void getAllEmployee()
{
String query="select * from employee";
List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());
Iterator it=l.iterator();
while(it.hasNext())
{
Employee e=(Employee)it.next();
System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
}
}
//Can use directly a RowMapper implementation class without an object creation
public List<Employee> getAllEmployee1(){
return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){
@Override
public Employee mapRow(ResultSet rs, int rownumber) throws SQLException {
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
return e;
}
});
}
// End of all the function
}
================================================================ //MyrowMapper.java
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class MyrowMapper implements RowMapper<Employee> {
@Override
public Employee mapRow(ResultSet rs, int rownumber) throws SQLException
{
System.out.println("mapRow()====:"+rownumber);
Employee e=new Employee();
e.setId(rs.getInt("id"));
e.setName(rs.getString("name"));
e.setSalary(rs.getFloat("salary"));
return e;
}
}
========================================================== //MyPreparedStatement.java
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
public class MyPreparedStatement implements PreparedStatementCallback<Object> {
@Override
public Object doInPreparedStatement(PreparedStatement ps)
throws SQLException, DataAccessException {
return ps.executeUpdate();
}
}
===================================================================== //Test.java
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
// By calling constructor for insert
/*
int status=dao.saveEmployee(new Employee(103,"Ajay",35000));
System.out.println(status);
*/
// By calling PreparedStatement
dao.insertEmploye(new Employee(103,"Roh",25000));
// By calling setter-getter for update
/*
Employee e=new Employee();
e.setId(102);
e.setName("Rohit");
e.setSalary(8000000);
int status=dao.updateEmployee(e);
*/
// By calling constructor for update
/*
int status=dao.updateEmployee(new Employee(102,"Sadhan",15000));
System.out.println(status);
*/
// Deleting a record
/*
Employee e=new Employee();
e.setId(102);
int status=dao.deleteEmployee(e);
System.out.println(status);
*/
// Selecting single or all rows
/*
Employee e=new Employee();
e.setId(102);
int status=dao.selectEmployee(e);
System.out.println(status);
*/
// Can use MyrowMapper class an implementation class for RowMapper interface
dao.getAllEmployee();
// Can use directly a RowMapper implementation class without an object creation
/*
List<Employee> list=dao.getAllEmployee1();
for(Employee e1:list)
System.out.println(e1);
*/
}
}
================================================================== //applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="hr" />
<property name="password" value="hr" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="nameTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="ds"></constructor-arg>
</bean>
<bean id="edao" class="EmployeeDao">
<!-- Can use both -->
<property name="nameTemplate" ref="nameTemplate"></property>
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
===================================================================
First thing you should check is that whether the image exists in the root directory or not. This is mostly due to image with height = 0. Which means that cv2.imread(imageName)
is not reading the image.
To write it with a while loop you can do:
ls -f /var | while read -r file; do cmd $file; done
The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)
Depending upon the relationships of the repositories, another approach is to add the other repository (repositories) as a git submodules to one of the repositories. A git submodule is creates a reference to the other repos. Those submodule repos are not cloned unless the you specify the --recursive
flag when cloning the "superproject" (official term).
Here's the command to add a submodule into the current project:
git submodule add <repository URI path to clone>
We are using Jenkins v1.645 and the git SCM will out-of-the-box do a recursive clone for superprojects. Voila you get the superproject files and all the dependent (submodule) repo files in their own respective directories in the same Jenkins job workspace.
Not vouching that this is the correct approach rather it's an approach.
I found a better, but buggy way, combining sdleihssirhc's idea:
window.onscroll = function() {
window.scrollTo(window.scrollX, window.scrollY);
//Or
//window.scroll(window.scrollX, window.scrollY);
//Or Fallback
//window.scrollX=window.scrollX;
//window.scrollY=window.scrollY;
};
I didn't test it, but I'll edit later and let you all know. I'm 85% sure it works on major browsers.
(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)
You can feed data right through the standard input of the ssh
command and read
that from the remote location.
In the following example,
ssh
a null-terminated line giving the name and value of the variable.shh
command itself, we loop through these lines to initialise the required variables.# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb
# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
FOO
BAR
)
for name in "${VAR_NAMES[@]}"
do
printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
while read -rd '"''"' name value
do
export "$name"="$value"
done
# Check
printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'
Output:
FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]
If you don’t need to export
those, you should be able to use declare
instead of export
.
A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:
$ ssh [email protected] 'read foo' <<< "$foo"
jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.
to know more about this take a look at the How to internationalize your pages using JQuery?
I use both depending on who in my department I am helping (Some people prefer 2.7, others 3.5). Anyway, I use Anaconda and my default installation is 3.5. I use environments for other versions of python, packages, etc.. So for example, when I wanted to start using python 2.7 I ran:
conda create -n Python27 python=2.7
This creates a new environment named Python27 and installs Python version 2.7. You can add arguments to that line for installing other packages by default or just start from scratch. The environment will automatically activate, to deactivate simply type deactivate
(windows) or source deactivate
(linux, osx) in the command line. To activate in the future type activate Python27
(windows) or source activate Python27
(linux, osx). I would recommend reading the documentation for Managing Environments in Anaconda, if you choose to take that route.
Update
As of conda
version 4.6 you can now use conda activate
and conda deactivate
. The use of source
is now deprecated and will eventually be removed.
We should use recursion in following scenarios:
Recursion will save multiple traversals. And it will be useful, if we can divide the stack allocation like:
int N = 10;
int output = process(N) + process(N/2);
public void process(int n) {
if (n==N/2 + 1 || n==1) {
return 1;
}
return process(n-1) + process(n-2);
}
In this case only half stacks will be allocated at any given time.
Not sure if this applies, but the fix for me was to commit something locally after git init. Then I pushed to remote using --set-upstream ...
We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST
VERIFYPEER
did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget
to the same link as the cURL was doing also resulted in a certificate error.
-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.
For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover
does not work try to reboot your machine.
For me with iexplorer 11 and Angular 2 I fixed all those above issues by doing 2 things:
in index.html add:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
in src\polyfills.ts uncomment:
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
Im not a java developer but was using a java app to test a RESTful API. In order for me to fix the error I had to install the intermediate certificates in the webserver in order to make the error go away. I was using lighttpd, the original certificate was installed on an IIS server. Hope it helps. These were the certificates I had missing on the server.
Do I need to pass pointers, references, or non-pointer and non-reference values?
This is a question that matters when writing a function and choosing the types of the parameters it takes. That choice will affect how the function is called and it depends on a few things.
The simplest option is to pass objects by value. This basically creates a copy of the object in the function, which has many advantages. But sometimes copying is costly, in which case a constant reference, const&
, is usually best. And sometimes you need your object to be changed by the function. Then a non-constant reference, &
, is needed.
For guidance on the choice of parameter types, see the Functions section of the C++ Core Guidelines, starting with F.15. As a general rule, try to avoid raw pointers, *
.
I was asking the same question just now after a quick google I found that There is a pair class in .NET except its in the System.Web.UI ^ ~ ^ (http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) goodness knows why they put it there instead of the collections framework
I was looking for a solution for this for a long time and found most of the answers are not working or not suitable for my situation i also find most of the java script code for that they worked but only with the vertical scroll not with the horizontal scroll and also combination of header and rows doesn't match.
Finally i have found a solution with javascript here is the link bellow :-
scrollable horizontal and vertical grid view with fixed headers
Late to the party: Try this>
base_filename = 'Values.txt'
with open(os.path.join(WorkingFolder, base_filename),'w') as outfile:
df.to_string(outfile)
#Neatly allocate all columns and rows to a .txt file
You can use HTML5 validation on your text inputs by adding a pattern. No need to manually validate with regex or keyCodes.
<input type="text" pattern="[0-9.]+" />
$("input[type=text][pattern]").on("input", function () {
if (!this.checkValidity())
this.value = this.value.slice(0, -1);
});
Possible, but not as simple for inputs [type=number]...
The problem with [type="number"] is that we cannot only remove the invalid character at the end. The User Agents return an empty string whenever the input is invalid.
From the W3C HTML5 spec:
If the value of the element is not a valid floating point number, then set it to the empty string instead.
https://dev.w3.org/html5/spec-LC/number-state.html#number-state
This means we need a way to store the previous input value by hand.
So for number inputs, the solution would look like this:
$("input[type=number], input[type=text][pattern]").on("input", function () {
if (!this.checkValidity())
this.value = $(this).data("current-valid") || "";
else
$(this).data("current-valid", this.value);
});
Unfortunately, this will not work on IE and EDGE. We need to resort to the pattern solution above for these browsers. However, you can still use number inputs with this simple polyfill.
$("input[type=number]").attr("type", "text").attr("pattern", "[0-9.]+");
Just an addition to the solved answer:
This COULD be a problem with Android Studio's Instant Run feature, for example, if you realized you forgot to add the line of code: finish()
to your activity after opening another one, and you already re-opened the activity you shouldn't have reopened (which the finish()
solved), then you add finish()
and Instant Run occurs, then the app will crash since the logic has been broken.
TL:DR;
This is not necessarily a code problem, just an Instant Run problem
You can use pyuic4
command on shell:
pyuic4 input.ui -o output.py
int min and max values
Int -2,147,483,648 / 2,147,483,647 Int 64 -9,223,372,036,854,775,808 / 9,223,372,036,854,775,807
i guess you could set a to equal 9,223,372,036,854,775,807 but it would need to be an int64
if you always want a to be grater that b why do you need to check it? just set it to be true always
You can always check if the thread's id is different than std::thread::id() default constructed. A Running thread has always a genuine associated id. Try to avoid too much fancy stuff :)
My grep that works after trying out stuff in this thread:
echo "hi how are you " | grep -shoP ".*? "
Just make sure you append a space to each one of your lines
(Mine was a line by line search to spit out words)
This answer is for XAMPP on Ubuntu.
The manual for installation and download is on (site official)
http://www.apachefriends.org/it/xampp-linux.html
After to start XAMPP simply call this command:
sudo /opt/lampp/lampp start
You should now see something like this on your screen:
Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.
If you have this
Starting XAMPP for Linux 1.8.1...
XAMPP: Another web server daemon is already running.
XAMPP: Another MySQL daemon is already running.
XAMPP: Starting ProFTPD...
XAMPP for Linux started
. The solution is
sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop
And the restast with sudo //opt/lampp/lampp restart
You to fix most of the security weaknesses simply call the following command:
/opt/lampp/lampp security
After the change this file
sudo kate //opt/lampp/etc/extra/httpd-xampp.conf
Find and replace on
#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8
Allow from all
#\
# fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
# fe80::/10 169.254.0.0/16
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
A complete example for scripted pipepline:
stage('Build'){
withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
sh 'bash build.sh'
}
}
These instructions are for windows machine with a single user profile for AWS. Make sure your ~/.aws/credentials
file looks like this
[profile_name]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey
I had to set the AWS_DEFAULT_PROFILE
environment variable to profile_name
found in your credentials.
Then my python was able to connect. eg from here
import boto3
# Let's use Amazon S3
s3 = boto3.resource('s3')
# Print out bucket names
for bucket in s3.buckets.all():
print(bucket.name)
General solution, works on arrays of non-strings:
>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'
Issues were:
Here is how I fixed it:
IPV6 Disabling
su
and enter to log in as the super usercd /etc/modprobe.d/
to change directory to /etc/modprobe.d/
vi disableipv6.conf
to create a new file thereEsc + i
to insert data to fileinstall ipv6 /bin/true
on the file to avoid loading IPV6 related modulesEsc + :
and then wq
for save and exitreboot
to restart fedoralsmod | grep ipv6
Add Google DNS server
su
and enter to log in as the super usercat /etc/resolv.conf
to check what DNS server your Fedora using. Mostly this will be your Modem IP address.8.8.8.8
and 8.8.4.4
. But in future those may change.vi /etc/resolv.conf
to edit the resolv.conf
fileEsc + i
for insert data to fileType below two lines in the file
nameserver 8.8.8.8
nameserver 8.8.4.4
-Type Esc + :
and then wq
for save and exit
Here is my blog post about this: http://codeketchup.blogspot.sg/2014/07/how-to-fix-curl-6-could-not-resolve.html
If your menu height is variable (for responsiveness or because it's loaded dynamically), you can set the top margin to where the fixed div ends. For example:
CSS
.fixed-header {
width: 100%;
margin: 0 auto;
position: fixed;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
z-index: 999;
}
Javascript
$(document).ready(function() {
var contentPlacement = $('#header').position().top + $('#header').height();
$('#content').css('margin-top',contentPlacement);
});
HTML
...
<div id="header" class="fixed-header"></div>
<div id="content">...</div>
...
Here's a fiddle (https://jsfiddle.net/632k9xkv/5/) that goes a little beyond this with both a fixed nav menu and header in an attempt to hopefully make this a useful sample.
The width attribute of <td>
is deprecated in HTML 5.
Use CSS. e.g.
<td style="width:100px">
in detail, like this:
<table >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td style="width:70%">January</td>
<td style="width:30%">$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
Refer to Microsoft vscode-tips-and-tricks. Just run these commands in your terminal:
git config --global merge.tool code
I'm currently using two GCM Project Id in the same app package. I put the google-service.json of my first GCM project but I switch from the first to the second one only changing the SENDER_ID:
String token = instanceID.getToken(SENDER_ID,GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
(At this point I think that the google-services.json isn't mandatory )
You can make an AJAX request like any other requests:
$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
alert(data);
}
})
Assuming you are using this for a web service, you can just apply the following attribute to the class:
[System.Web.Script.Services.ScriptService]
Then the following attribute to each method that should return Json:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
And set the return type for the methods to be "object"
you can also set environment variables in the script itself, rather than passing region_name parameter
os.environ['AWS_DEFAULT_REGION'] = 'your_region_name'
case sensitivity may matter.
First install the driver (Ubuntu)
sudo apt-get install python-pip
sudo pip install -U pip
sudo apt-get install python-dev libmysqlclient-dev
sudo apt-get install MySQL-python
MySQL database connection codes
import MySQLdb
conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
You can update to an older revision:
svn update -r 666 file
Or you can just view the file directly:
svn cat -r 666 file | less
Application pools allow you to isolate your applications from one another, even if they are running on the same server. This way, if there is an error in one app, it won't take down other applications.
Additionally, applications pools allow you to separate different apps which require different levels of security.
Here's a good resource: IIS and ASP.NET: The Application Pool
You can use this following code. work just on chrome browser.
function failed(e) {_x000D_
// video playback failed - show a message saying why_x000D_
switch (e.target.error.code) {_x000D_
case e.target.error.MEDIA_ERR_ABORTED:_x000D_
alert('You aborted the video playback.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_NETWORK:_x000D_
alert('A network error caused the video download to fail part-way.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_DECODE:_x000D_
alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
break;_x000D_
default:_x000D_
alert('An unknown error occurred.');_x000D_
break;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
<meta name="author" content="Amin Developer!" />_x000D_
_x000D_
<title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Here is a little refactoring of your function (it does not use "else" or "elif"):
def function(a):
if a not in (1, 2):
a = 3
print(str(a) + "a")
@ghostdog74: Python 3 requires parentheses for "print".
$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used
The accepted answer is fine, but I actually prefer format(number,',')
. Easier for me to interpret and remember.
Try this: The data returned from SQL has to converted into a Dict.
or could it be "Pollutant Levels"
is now Pollutants'
StationID Pollutants
0 8809 {"a":"46","b":"3","c":"12"}
1 8810 {"a":"36","b":"5","c":"8"}
2 8811 {"b":"2","c":"7"}
3 8812 {"c":"11"}
4 8813 {"a":"82","c":"15"}
df2["Pollutants"] = df2["Pollutants"].apply(lambda x : dict(eval(x)) )
df3 = df2["Pollutants"].apply(pd.Series )
a b c
0 46 3 12
1 36 5 8
2 NaN 2 7
3 NaN NaN 11
4 82 NaN 15
result = pd.concat([df, df3], axis=1).drop('Pollutants', axis=1)
result
StationID a b c
0 8809 46 3 12
1 8810 36 5 8
2 8811 NaN 2 7
3 8812 NaN NaN 11
4 8813 82 NaN 15
Check the jQuery FAQ...
You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length ){}