I have had problems debugging binaries on the device via XCode when the app includes an Entitlements.plist file, which is not necessary to install onto the device for debugging. In general, then, I have included this file for release builds (where it is required for the App Store) and removed it for debugging (so I can debug the app from XCode). That may be your problem here.
Update: As of (at least) August 2010 (iPhone 4.1 SDK) the Entitlements.plist is no longer necessary to include in your application in many cases (e.g., distribution through the App Store.) See here for more information on the cases when Entitlements.plist is required:
IMPORTANT: An Entitlements file is generally only needed when building for Ad Hoc Distribution or enabling Keychain data sharing. If neither of these is true, delete the entry in Code Signing Entitlements. (emphasis mine)
Using the window subview hierarchy as indication for keyboard showing is a hack. If Apple changers their underlying implementation all these answers would break.
The correct way would be to monitor Keyboard show and hide notifications application wide such as inside your App Delegate:
In AppDelegate.h:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (assign, nonatomic) BOOL keyboardIsShowing;
@end
In AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Monitor keyboard status application wide
self.keyboardIsShowing = NO;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
return YES;
}
- (void)keyboardWillShow:(NSNotification*)aNotification
{
self.keyboardIsShowing = YES;
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
self.keyboardIsShowing = NO;
}
Then you can check using:
BOOL keyboardIsShowing = ((AppDelegate*)[UIApplication sharedApplication].delegate).keyboardIsShowing;
It should be noted the keyboard show/hide notifications will not fire when user is using a bluetooth or external keyboard.
This is a method for converting a svg picture to a gif using standard php GD tools
1) You put the image into a canvas element in the browser:
<canvas id=myCanvas></canvas>
<script>
var Key='picturename'
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
base_image = new Image();
base_image.src = myimage.svg;
base_image.onload = function(){
//get the image info as base64 text string
var dataURL = canvas.toDataURL();
//Post the image (dataURL) to the server using jQuery post method
$.post('ProcessPicture.php',{'TheKey':Key,'image': dataURL ,'h': canvas.height,'w':canvas.width,"stemme":stemme } ,function(data,status){ alert(data+' '+status) });
}
</script>
And then convert it at the server (ProcessPicture.php) from (default) png to gif and save it. (you could have saved as png too then use imagepng instead of image gif):
//receive the posted data in php
$pic=$_POST['image'];
$Key=$_POST['TheKey'];
$height=$_POST['h'];
$width=$_POST['w'];
$dir='../gif/'
$gifName=$dir.$Key.'.gif';
$pngName=$dir.$Key.'.png';
//split the generated base64 string before the comma. to remove the 'data:image/png;base64, header created by and get the image data
$data = explode(',', $pic);
$base64img = base64_decode($data[1]);
$dimg=imagecreatefromstring($base64img);
//in order to avoid copying a black figure into a (default) black background you must create a white background
$im_out = ImageCreateTrueColor($width,$height);
$bgfill = imagecolorallocate( $im_out, 255, 255, 255 );
imagefill( $im_out, 0,0, $bgfill );
//Copy the uploaded picture in on the white background
ImageCopyResampled($im_out, $dimg ,0, 0, 0, 0, $width, $height,$width, $height);
//Make the gif and png file
imagegif($im_out, $gifName);
imagepng($im_out, $pngName);
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
Simply remove/delete android and ios (keep backup android and ios folder) and run following command:
react-native eject
Supported version :
react-native <= 0.59.10
react-native-cli <= 1.3.0
react-native upgrade --legacy true
Supported version :
react-native >= 0.60.0
react-native-cli >= 2.1.0
Ref : link
I will suggest move all templates to separate files, and don't do spagetti inside repeat
take a look here:
html:
<div ng-repeat = "data in comments">
<div ng-include src="buildUrl(data.type)"></div>
</div>
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.comments = [
{"_id":"52fb84fac6b93c152d8b4569",
"post_id":"52fb84fac6b93c152d8b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"hoot"},
{"_id":"52fb798cc6b93c74298b4568",
"post_id":"52fb798cc6b93c74298b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"story"},
{"_id":"52fb7977c6b93c5c2c8b456b",
"post_id":"52fb7977c6b93c5c2c8b456a",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"article"}
];
$scope.buildUrl = function(type) {
return type + '.html';
}
});
Write your permission before the application tag as given below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.someapp.sample">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
You can, but the variable in your last include will overwrite the variable in your first one:
myfile.php
$var = 'test';
mysecondfile.php
$var = 'tester';
test.php
include 'myfile.php';
echo $var;
include 'mysecondfile.php';
echo $var;
Output:
test
tester
I suggest using different variable names.
I'm using the terminal in VSCode and I realized I was using the bash
terminal instead of the node
terminal.
You can just pass a list of the two points you want to connect to plt.plot
. To make this easily expandable to as many points as you want, you could define a function like so.
import matplotlib.pyplot as plt
x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5, 1, -0.5, -1]
plt.plot(x,y, 'ro')
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'k-')
connectpoints(x,y,0,1)
connectpoints(x,y,2,3)
plt.axis('equal')
plt.show()
Note, that function is a general function that can connect any two points in your list together.
To expand this to 2N points, assuming you always connect point i
to point i+1
, we can just put it in a for loop:
import numpy as np
for i in np.arange(0,len(x),2):
connectpoints(x,y,i,i+1)
In that case of always connecting point i
to point i+1
, you could simply do:
for i in np.arange(0,len(x),2):
plt.plot(x[i:i+2],y[i:i+2],'k-')
glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:
OpenGL documentation (my bold)
The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).
The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:
Parallel projections have lines of projection that are parallel both in reality and in the projection plane.
Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".
Best way to solve this until a fix is available (if a fix comes) is to force IE compatibility mode on the user.
Use <META http-equiv="X-UA-Compatible" content="IE=9">
ideally in the masterpage so all pages in your site get the workaround.
Why does
response.json
return a promise?
Because you receive the response
as soon as all headers have arrived. Calling .json()
gets you another promise for the body of the http response that is yet to be loaded. See also Why is the response object from JavaScript fetch API a promise?.
Why do I get the value if I return the promise from the
then
handler?
Because that's how promises work. The ability to return promises from the callback and get them adopted is their most relevant feature, it makes them chainable without nesting.
You can use
fetch(url).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
console.log(res.status, res.data.title)
}));
or any other of the approaches to access previous promise results in a .then() chain to get the response status after having awaited the json body.
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname
.
This is a fairly trivial effect to accomplish. One way to achieve this is to simply place floated div
elements within a common parent container, and set their width and height. In order to clear the floated elements, we set the overflow
property of the parent.
<div class="container">
<div class="cube">do</div>
<div class="cube">ray</div>
<div class="cube">me</div>
<div class="cube">fa</div>
<div class="cube">so</div>
<div class="cube">la</div>
<div class="cube">te</div>
<div class="cube">do</div>
</div>
The CSS resembles the strategy outlined in the first paragraph above:
.container {
width: 450px;
overflow: auto;
}
.cube {
float: left;
width: 150px;
height: 150px;
}
You can see the end result here: http://jsfiddle.net/Qjum2/2/
Browsers that support pseudo elements provide an alternative way to clear:
.container::after {
content: "";
clear: both;
display: block;
}
You can see the results here: http://jsfiddle.net/Qjum2/3/
I hope this helps.
SELECT table_name as Table_Name, row_cnt as Row_Count, SUM(mb) as Size_MB
FROM
(SELECT in_tbl.table_name, to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from ' ||ut.table_name)),'/ROWSET/ROW/C')) AS row_cnt , mb
FROM
(SELECT CASE WHEN lob_tables IS NULL THEN table_name WHEN lob_tables IS NOT NULL THEN lob_tables END AS table_name , mb
FROM (SELECT ul.table_name AS lob_tables, us.segment_name AS table_name , us.bytes/1024/1024 MB FROM user_segments us
LEFT JOIN user_lobs ul ON us.segment_name = ul.segment_name ) ) in_tbl INNER JOIN user_tables ut ON in_tbl.table_name = ut.table_name ) GROUP BY table_name, row_cnt ORDER BY 3 DESC;``
Above query will give, Table_name, Row_count, Size_in_MB(includes lob column size) of specific user.
If you're using Visual C#, all you need to do is add a class in Program.cs inheriting Form and change all the inherited class from Form to your class in every Form*.cs.
//Program.cs
public class Forms : Form
{
//Declare your global valuables here.
}
//Form1.cs
public partial class Form1 : Forms //Change from Form to Forms
{
//...
}
Of course, there might be a way to extending the class Form without modifying it. If that's the case, all you need to do is extending it! Since all the forms are inheriting it by default, so all the valuables declared in it will become global automatically! Good luck!!!
You might have not copied the MySQL connector/J
jar file into the lib folder and then this file has to be there in the classpath.
If you have not done so, please let me know I shall elaborate the answer
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
Just for fun I thought I'd knock it up. It ended up being trickier than I thought because I went in not fully understanding how the boundary part works, eventually I worked out that the starting and ending '--' were significant and off it went.
<?php
if(isset($_POST['submit']))
{
//The form has been submitted, prep a nice thank you message
$output = '<h1>Thanks for your file and message!</h1>';
//Set the form flag to no display (cheap way!)
$flags = 'style="display:none;"';
//Deal with the email
$to = '[email protected]';
$subject = 'a file for you';
$message = strip_tags($_POST['message']);
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
$filename = $_FILES['file']['name'];
$boundary =md5(date('r', time()));
$headers = "From: [email protected]\r\nReply-To: [email protected]";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$message="This is a multi-part message in MIME format.
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
$message
--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
mail($to, $subject, $message, $headers);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>MailFile</title>
</head>
<body>
<?php echo $output; ?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" <?php echo $flags;?>>
<p><label for="message">Message</label> <textarea name="message" id="message" cols="20" rows="8"></textarea></p>
<p><label for="file">File</label> <input type="file" name="file" id="file"></p>
<p><input type="submit" name="submit" id="submit" value="send"></p>
</form>
</body>
</html>
Very barebones really, and obviously the using inline CSS to hide the form is a bit cheap and you'd almost certainly want a bit more feedback to the user! Also, I'd probably spend a bit more time working out what the actual Content-Type for the file is, rather than cheating and using application/octet-stream but that part is quite as interesting.
You have to create an instance of the Bitmap
class, using the constructor overload that loads an image from a file on disk. As your code is written now, you're trying to use the PictureBox.Image
property as if it were a method.
Change your code to look like this (also taking advantage of the using
statement to ensure proper disposal, rather than manually calling the Dispose
method):
private void button1_Click(object sender, EventArgs e)
{
// Wrap the creation of the OpenFileDialog instance in a using statement,
// rather than manually calling the Dispose method to ensure proper disposal
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox PictureBox1 = new PictureBox();
// Create a new Bitmap object from the picture file on disk,
// and assign that to the PictureBox.Image property
PictureBox1.Image = new Bitmap(dlg.FileName);
}
}
}
Of course, that's not going to display the image anywhere on your form because the picture box control that you've created hasn't been added to the form. You need to add the new picture box control that you've just created to the form's Controls
collection using the Add
method. Note the line added to the above code here:
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
PictureBox PictureBox1 = new PictureBox();
PictureBox1.Image = new Bitmap(dlg.FileName);
// Add the new control to its parent's controls collection
this.Controls.Add(PictureBox1);
}
}
}
Just adding this. In your package.json, if your "main": "index.js" is correctly set. Just use node .
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
...
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
...
},
"devDependencies": {
...
}
}
These are equivalent
char buf[10] = "";
char buf[10] = {0};
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
These are equivalent
char buf[10] = " ";
char buf[10] = {' '};
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
These are equivalent
char buf[10] = "a";
char buf[10] = {'a'};
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
You can't write to the HKCR (or HKLM) hives in Vista and newer versions of Windows unless you have administrative privileges. Therefore, you'll either need to be logged in as an Administrator before you run your utility, give it a manifest that says it requires Administrator level (which will prompt the user for Admin login info), or quit changing things in places that non-Administrators shouldn't be playing. :-)
I know it's been so long but I got this problem too, tried this solution and it's working. So I guess it may help the others too.
I add android:fillViewport="true" on the layout xml for the scrollView. So overall my ScrollView will be like this.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollView6"
android:fillViewport="true">
And it works like magic to me. the ListView that located inside my ScrollView expand to its size again.
Here is the full example code for the ScrollView and the ListView.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scrollView6" android:fillViewport="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
....
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv_transList" android:layout_gravity="top"
android:layout_marginTop="5dp"/>
....
</LinearLayout>
</ScrollView>
In my case I wanted to remove jsonobject with status as non zero value, so what I did is made a function "removeJsonObject" which takes old json and gives required json and called that function inside the constuctor.
public CommonAdapter(Context context, JSONObject json, String type) {
this.context=context;
this.json= removeJsonObject(json);
this.type=type;
Log.d("CA:", "type:"+type);
}
public JSONObject removeJsonObject(JSONObject jo){
JSONArray ja= null;
JSONArray jsonArray= new JSONArray();
JSONObject jsonObject1=new JSONObject();
try {
ja = jo.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i=0; i<ja.length(); i++){
try {
if(Integer.parseInt(ja.getJSONObject(i).getString("status"))==0)
{
jsonArray.put(ja.getJSONObject(i));
Log.d("jsonarray:", jsonArray.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
jsonObject1.put("data",jsonArray);
Log.d("jsonobject1:", jsonObject1.toString());
return jsonObject1;
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
Standard is use is
or has
as a prefix. For example isValid
, hasChildren
.
To delete all records from a table without deleting the table.
DELETE FROM table_name
use with care, there is no undo!
To remove a table
DROP TABLE table_name
I started to write a Script to read OS and browser version that can be tested on Fiddle. Feel free to use and extend.
Breaking Change:
Since September 2020 the new Edge gets detected. So 'Microsoft Edge' is the new version based on Chromium and the old Edge is now detected as 'Microsoft Legacy Edge'!
/**
* JavaScript Client Detection
* (C) viazenetti GmbH (Christian Ludwig)
*/
(function (window) {
{
var unknown = '-';
// screen
var screenSize = '';
if (screen.width) {
width = (screen.width) ? screen.width : '';
height = (screen.height) ? screen.height : '';
screenSize += '' + width + " x " + height;
}
// browser
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browser = navigator.appName;
var version = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;
// Opera
if ((verOffset = nAgt.indexOf('Opera')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Opera Next
if ((verOffset = nAgt.indexOf('OPR')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 4);
}
// Legacy Edge
else if ((verOffset = nAgt.indexOf('Edge')) != -1) {
browser = 'Microsoft Legacy Edge';
version = nAgt.substring(verOffset + 5);
}
// Edge (Chromium)
else if ((verOffset = nAgt.indexOf('Edg')) != -1) {
browser = 'Microsoft Edge';
version = nAgt.substring(verOffset + 4);
}
// MSIE
else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
}
// Chrome
else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
browser = 'Chrome';
version = nAgt.substring(verOffset + 7);
}
// Safari
else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
browser = 'Safari';
version = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Firefox
else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
browser = 'Firefox';
version = nAgt.substring(verOffset + 8);
}
// MSIE 11+
else if (nAgt.indexOf('Trident/') != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(nAgt.indexOf('rv:') + 3);
}
// Other browsers
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
browser = nAgt.substring(nameOffset, verOffset);
version = nAgt.substring(verOffset + 1);
if (browser.toLowerCase() == browser.toUpperCase()) {
browser = navigator.appName;
}
}
// trim the version string
if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);
majorVersion = parseInt('' + version, 10);
if (isNaN(majorVersion)) {
version = '' + parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion, 10);
}
// mobile version
var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);
// cookie
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
}
// system
var os = unknown;
var clientStrings = [
{s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
{s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
{s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
{s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
{s:'Windows Vista', r:/Windows NT 6.0/},
{s:'Windows Server 2003', r:/Windows NT 5.2/},
{s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
{s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
{s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
{s:'Windows 98', r:/(Windows 98|Win98)/},
{s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
{s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
{s:'Windows CE', r:/Windows CE/},
{s:'Windows 3.11', r:/Win16/},
{s:'Android', r:/Android/},
{s:'Open BSD', r:/OpenBSD/},
{s:'Sun OS', r:/SunOS/},
{s:'Chrome OS', r:/CrOS/},
{s:'Linux', r:/(Linux|X11(?!.*CrOS))/},
{s:'iOS', r:/(iPhone|iPad|iPod)/},
{s:'Mac OS X', r:/Mac OS X/},
{s:'Mac OS', r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
{s:'QNX', r:/QNX/},
{s:'UNIX', r:/UNIX/},
{s:'BeOS', r:/BeOS/},
{s:'OS/2', r:/OS\/2/},
{s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
];
for (var id in clientStrings) {
var cs = clientStrings[id];
if (cs.r.test(nAgt)) {
os = cs.s;
break;
}
}
var osVersion = unknown;
if (/Windows/.test(os)) {
osVersion = /Windows (.*)/.exec(os)[1];
os = 'Windows';
}
switch (os) {
case 'Mac OS':
case 'Mac OS X':
case 'Android':
osVersion = /(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([\.\_\d]+)/.exec(nAgt)[1];
break;
case 'iOS':
osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
break;
}
// flash (you'll need to include swfobject)
/* script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" */
var flashVersion = 'no check';
if (typeof swfobject != 'undefined') {
var fv = swfobject.getFlashPlayerVersion();
if (fv.major > 0) {
flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
}
else {
flashVersion = unknown;
}
}
}
window.jscd = {
screen: screenSize,
browser: browser,
browserVersion: version,
browserMajorVersion: majorVersion,
mobile: mobile,
os: os,
osVersion: osVersion,
cookies: cookieEnabled,
flashVersion: flashVersion
};
}(this));
alert(
'OS: ' + jscd.os +' '+ jscd.osVersion + '\n' +
'Browser: ' + jscd.browser +' '+ jscd.browserMajorVersion +
' (' + jscd.browserVersion + ')\n' +
'Mobile: ' + jscd.mobile + '\n' +
'Flash: ' + jscd.flashVersion + '\n' +
'Cookies: ' + jscd.cookies + '\n' +
'Screen Size: ' + jscd.screen + '\n\n' +
'Full User Agent: ' + navigator.userAgent
);
This is way I did it:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)
You can define your own sizes.
This CSS also shows a fixed height HTML table. It sets the height of the HTML tbody to 400 pixels and the HTML tbody scrolls when the it is larger, retaining the HTML thead as a non-scrolling element.
In addition, each th cell in the heading and each td cell the body should be styled for the desired fixed width.
#the-table {
display: block;
background: white; /* optional */
}
#the-table thead {
text-align: left; /* optional */
}
#the-table tbody {
display: block;
max-height: 400px;
overflow-y: scroll;
}
Use gson
for duplicating an object.
public static <T>T copyObject(Object object){
Gson gson = new Gson();
JsonObject jsonObject = gson.toJsonTree(object).getAsJsonObject();
return gson.fromJson(jsonObject,(Type) object.getClass());
}
Assume I have an object person
.So
Person copyPerson = copyObject(person);
Note: The performance is much slower.
You should always use audio/mpeg, because firefox cannot play audio/mpeg3 files
One thing I can suggest you is to extend the storage object to handle objects and arrays.
LocalStorage can handle only strings so you can achieve that using these methods
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
}
Using it every values will be converted to json string on set and parsed on get
There was conflict in java version. Resolved after using 1.8 for maven.
If ( You know Java ) {
Python code is converted into bytecode like java does.
That bytecode is executed again everytime you try to access it.
} else {
Python code is initially traslated into something called bytecode
that is quite
close to machine language but not actual machine code
so each time we access or run it that bytecode is executed again
}
IN your view insert
@Html.ValidationMessage("Error")
then in the controller after you use new in your model
var model = new yourmodel();
try{
[...]
}catch(Exception ex){
ModelState.AddModelError("Error", ex.Message);
return View(model);
}
I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.
The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to open it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.
So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!
<script type="text/javascript">
jQuery(document).ready( function(){
jQuery("#myButton").click( showDialog );
//variable to reference window
$myWindow = jQuery('#myDiv');
//instantiate the dialog
$myWindow.dialog({ height: 350,
width: 400,
modal: true,
position: 'center',
autoOpen:false,
title:'Hello World',
overlay: { opacity: 0.5, background: 'black'}
});
}
);
//function to show dialog
var showDialog = function() {
//if the contents have been hidden with css, you need this
$myWindow.show();
//open the dialog
$myWindow.dialog("open");
}
//function to close dialog, probably called by a button in the dialog
var closeDialog = function() {
$myWindow.dialog("close");
}
</script>
</head>
<body>
<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
<p>I am a modal dialog</p>
</div>
I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators
or CodeLens
, and can be located under
Tools ? Options ? Text Editor ? All Languages ? CodeLens
(for RC/final version)
or
Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators
(for preview version)
That was according to this link. It seems to be pretty well hidden.
In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:
documented in the Q&A section of the msdn CodeLens documentation
One more way:
CREATE OR REPLACE TYPE TYPE_TABLE_OF_VARCHAR2 AS TABLE OF VARCHAR(100);
-- ...
SELECT field1, field2, field3
FROM table1
WHERE name IN (
SELECT * FROM table (SELECT CAST(? AS TYPE_TABLE_OF_VARCHAR2) FROM dual)
);
I don't consider it's optimal, but it works. The hint /*+ CARDINALITY(...) */
would be very useful because Oracle does not understand cardinality of the array passed and can't estimate optimal execution plan.
As another alternative - batch insert into temporary table and using the last in subquery for IN
predicate.
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
You may also want to try st, a node module for serving static files. Setup is trivial.
npm install connect
npm install st
And here's how my server-dev.js file looks like:
var connect = require('connect');
var http = require('http');
var st = require('st');
var app = connect()
.use(st('app/dev'));
http.createServer(app).listen(8000);
or (with cache disabled):
var connect = require('connect');
var http = require('http');
var st = require('st');
var app = connect();
var mount = st({
path: 'app/dev',
cache: false
});
http.createServer(function (req, res) {
if (mount(req, res)) return;
}).listen(8000);
app.use(mount);
In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)
Perhaps you could try ([^ ]+) .*
, which should give you everything to the first blank in your first group.
If you need wait until the ajax call is completed all do you need is make your call synchronously.
Combination of @[macbirdie] and @[Adrian Borchardt] answer. Which proves to be very useful in production environment (not messing up previously existing warning, especially during cross-platform compile)
#if (_MSC_VER >= 1400) // Check MSC version
#pragma warning(push)
#pragma warning(disable: 4996) // Disable deprecation
#endif
//... // ...
strcat(base, cat); // Sample depreciated code
//... // ...
#if (_MSC_VER >= 1400) // Check MSC version
#pragma warning(pop) // Renable previous depreciations
#endif
You have to use a Class
instance because of the generic type erasure during compilation.
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch(ClassCastException e) {
return null;
}
}
The declaration of that method is:
public T cast(Object o)
This can also be used for array types. It would look like this:
final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);
Note that when someObject
is passed to convertToInstanceOfObject
it has the compile time type Object
.
Write it like this:
string[] files = Directory.GetFiles(@".\Archive", "*.zip");
. is for relative to the folder where you started your exe, and @ to allow \ in the name.
When using filters, you pass it as a second parameter. You can also add a third parameter to specify if you want to search recursively for the pattern.
In order to get the folder where your .exe actually resides, use:
var executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
I had to solve the same issue and this is what I used as solution.
To use this solution the source and destination table must be identical, and the must have an id unique and autoincrement in first table (so that the same id is never reused).
Lets say table1 and table2 have this structure
|id|field1|field2
You can make those two query :
INSERT INTO table2 SELECT * FROM table1 WHERE
DELETE FROM table1 WHERE table1.id in (SELECT table2.id FROM table2)
Open the php.ini
file in your server environment and remove ;
from ;extension=sockets
. if it's doesn't work, you have to download the socket
extension for PHP and put it into ext
directory in the php installation path. Restart your http server and everything should work.
Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/
URL. Upon success, it removes all items from dropdown list with id
= OfferTransModel_ItemID
and then it fills it with new items based on AJAX call's result:
if (productgrpid != 0) {
$.ajax({
type: "POST",
url: "/Ajax/_AjaxGetItemListHelp/",
data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
contentType: "application/json",
dataType: "json",
success: function (data) {
$("#OfferTransModel_ItemID").empty();
$.each(data, function () {
$("#OfferTransModel_ItemID").append($("<option>
</option>").val(this['ITEMID']).html(this['ITEMDESC']));
});
}
});
}
Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID
and ITEMDESC
elements. For example:
{
{
"ITEMID":"13",
"ITEMDESC":"About"
},
{
"ITEMID":"21",
"ITEMDESC":"Contact"
}
}
The OfferTransModel_ItemID
listbox is populated with above data and its code should look like:
<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
<option value="13">About</option>
<option value="21">Contact</option>
</select>
When user selects About
, form submits 13
as value for this field and 21
when user selects Contact
and so on.
Fell free to modify above code if your server returns URL in a different format.
I think what you want is called a fling. The MotionEvents can be used to determine the direction of the fling.
public class MainActivity extends Activity implements GestureDetector.OnGestureListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stellar_layout);
mDetector = new GestureDetectorCompat(this, this);
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.d(tag, "onFling:\n " + event1.toString()+ "\n " + event2.toString());
/* prints the following
MotionEvent { action=ACTION_DOWN, id[0]=0, x[0]=297.0, y[0]=672.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=488341979, downTime=488341979, deviceId=6, source=0x1002 }
MotionEvent { action=ACTION_UP, id[0]=0, x[0]=560.0, y[0]=583.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=488342047, downTime=488341979, deviceId=6, source=0x1002 }
*/
return true;
}
}
http://developer.android.com/training/gestures/detector.html
To include the direction along with the orderBy function:
ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"
where
defaultSortDirection = 0; // 0 = Ascending, 1 = Descending
I am using Android Studio 2.1 and I have better consistency of getting the lightbulb by clicking on the class Name and hover over it for a second.
something
{
something1
something2
}
something3
In Python
Something
something1
something2
something3
This is what I use for delaying repeated actions, it can be called in multiple places in your code:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Usage:
$(window).resize(function () {
debounce(function() {
//...
}, 500);
});
One important distinction between the two (which is visible in the Reflected code) is that SelectedValue will return an empty string if a nothing is selected, whereas SelectedItem.Value will throw a NullReference exception.
No one has mentioned it yet, so Symbols would also be a way to go:
Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date") // true
Symbol.for(new Date()) === Symbol.for("Invalid Date") // false
console.log('Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date")', Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date")) // true_x000D_
_x000D_
console.log('Symbol.for(new Date()) === Symbol.for("Invalid Date")', Symbol.for(new Date()) === Symbol.for("Invalid Date")) // false
_x000D_
Be aware of: https://caniuse.com/#search=Symbol
host just includes the port number if there is one specified. If there is no port number specifically in the URL, then it returns the same as hostname. You pick whether you care to match the port number or not. See https://developer.mozilla.org/en/window.location for more info.
I would assume you want hostname to just get the site name.
sleep
is a non-standard function.
<unistd.h>
. Sleep
is rather from <windows.h>
. In every case, check the documentation.
The previous answers didn't work in my case. However, creating an empty item in the menu does.
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
...
<item />
...
</menu>
This seems to be a binding issue.
The advice is don't bind to primitives.
Your ngRepeat
is iterating over strings inside a collection, when it should be iterating over objects. To fix your problem
<body ng-init="models = [{name:'Sam'},{name:'Harry'},{name:'Sally'}]">
<h1>Fun with Fields and ngModel</h1>
<p>names: {{models}}</p>
<h3>Binding to each element directly:</h3>
<div ng-repeat="model in models">
Value: {{model.name}}
<input ng-model="model.name">
</div>
jsfiddle: http://jsfiddle.net/jaimem/rnw3u/5/
Press F11 to Build and the Run the program. Once you run the program, you will have a list of classes. Select your main class from the list and click ok to run.
Here's a responsive way of doing it with jQuery.
$(window).resize(function () {
$('#YourRelativeDiv').css('margin-top', $('#YourFixedDiv').height());
});
Sadly there are no operation-assignment
operators in VBA.
(Addition-assignment +=
are available in VB.Net)
Pointless workaround;
Sub Inc(ByRef i As Integer)
i = i + 1
End Sub
...
Static value As Integer
inc value
inc value
If you want to check for any key at any depth on an object and account for falsey values consider this line for a utility function:
var keyExistsOn = (o, k) => k.split(".").reduce((a, c) => a.hasOwnProperty(c) ? a[c] || 1 : false, Object.assign({}, o)) === false ? false : true;
Results
var obj = {
test: "",
locals: {
test: "",
test2: false,
test3: NaN,
test4: 0,
test5: undefined,
auth: {
user: "hw"
}
}
}
keyExistsOn(obj, "")
> false
keyExistsOn(obj, "locals.test")
> true
keyExistsOn(obj, "locals.test2")
> true
keyExistsOn(obj, "locals.test3")
> true
keyExistsOn(obj, "locals.test4")
> true
keyExistsOn(obj, "locals.test5")
> true
keyExistsOn(obj, "sdsdf")
false
keyExistsOn(obj, "sdsdf.rtsd")
false
keyExistsOn(obj, "sdsdf.234d")
false
keyExistsOn(obj, "2134.sdsdf.234d")
false
keyExistsOn(obj, "locals")
true
keyExistsOn(obj, "locals.")
false
keyExistsOn(obj, "locals.auth")
true
keyExistsOn(obj, "locals.autht")
false
keyExistsOn(obj, "locals.auth.")
false
keyExistsOn(obj, "locals.auth.user")
true
keyExistsOn(obj, "locals.auth.userr")
false
keyExistsOn(obj, "locals.auth.user.")
false
keyExistsOn(obj, "locals.auth.user")
true
Also see this NPM package: https://www.npmjs.com/package/has-deep-value
That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.
Example. Suppose I write:
(function() {
var x = 2;
// do stuff with x
})();
Now other libraries cannot access the variable x
I created to use in my library.
Oneliner:
Thread.currentThread().getStackTrace()[2].getMethodName()
Note that you might need to replace the 2 with 1.
display: flex;
align-items: center;
There is a simpler way simply disable the error handler in your error handler if it does not match the error types you are doing and resume.
The handler below checks agains each error type and if none are a match it returns error resume to normal VBA ie GoTo 0 and resumes the code which then tries to rerun the code and the normal error block pops up.
On Error GoTo ErrorHandler
x = 1/0
ErrorHandler:
if Err.Number = 13 then ' 13 is Type mismatch (only used as an example)
'error handling code for this
end if
If err.Number = 1004 then ' 1004 is Too Large (only used as an example)
'error handling code for this
end if
On Error GoTo 0
Resume
Use mysql-connector-python. I prefer to install it with pip from PyPI:
pip install --allow-external mysql-connector-python mysql-connector-python
Have a look at its documentation and examples.
If you are going to use pooling make sure your database has enough connections available as the default settings may not be enough.
if you are using same date format and have select query where date in oracle :
select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';
To_DATE provided by oracle
<?PHP
echo "Firstline";
include('classes/connection.php');
echo "I will run if include but not on Require";
?>
A very simple Practical example with code. The first echo will be displayed. No matter you use include or require because its runs before include or required.
To check the result, In second line of a code intentionally provide the wrong path to the file or make error in file name. Thus the second echo to be displayed or not will be totally dependent on whether you use require or include.
If you use require the second echo will not execute but if you use include not matter what error comes you will see the result of second echo too.
$("#btnSubmit").click(function(){
alert("button");
});
Why make it difficult and hassle with locks? Use Dispatch Barriers.
A dispatch barrier creates a synchronization point within a concurrent queue.
While it’s running, no other block on the queue is allowed to run, even if it’s concurrent and other cores are available.
If that sounds like an exclusive (write) lock, it is. Non-barrier blocks can be thought of as shared (read) locks.
As long as all access to the resource is performed through the queue, barriers provide very cheap synchronization.
http://www.codeproject.com/KB/files/UserFileAccessRights.aspx
Very usefull Class, check for improved version in messages bellow.
I needed to rotate an object but have a call back function. Inspired by John Kern's answer I created this.
function animateRotate (object,fromDeg,toDeg,duration,callback){
var dummy = $('<span style="margin-left:'+fromDeg+'px;">')
$(dummy).animate({
"margin-left":toDeg+"px"
},
{
duration:duration,
step: function(now,fx){
$(object).css('transform','rotate(' + now + 'deg)');
if(now == toDeg){
if(typeof callback == "function"){
callback();
}
}
}
}
)};
Doing this you can simply call the rotate on the object like so... (in my case I'm doing it on a disclosure triangle icon that has already been rotated by default to 270 degress and I'm rotating it another 90 degrees to 360 degrees at 1000 milliseconds. The final argument is the callback after the animation has finished.
animateRotate($(".disclosure_icon"),270,360,1000,function(){
alert('finished rotate');
});
Just use date($format, strtotime($date,' LAST SUNDAY + 1 DAY'));
You need to invoke CreateInstanceAndUnwrap
before your proxy object will execute in the foreign application domain.
class Program
{
static void Main(string[] args)
{
AppDomainSetup domaininfo = new AppDomainSetup();
domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);
Type type = typeof(Proxy);
var value = (Proxy)domain.CreateInstanceAndUnwrap(
type.Assembly.FullName,
type.FullName);
var assembly = value.GetAssembly(args[0]);
// AppDomain.Unload(domain);
}
}
public class Proxy : MarshalByRefObject
{
public Assembly GetAssembly(string assemblyPath)
{
try
{
return Assembly.LoadFile(assemblyPath);
}
catch (Exception)
{
return null;
// throw new InvalidOperationException(ex);
}
}
}
Also, note that if you use LoadFrom
you'll likely get a FileNotFound
exception because the Assembly resolver will attempt to find the assembly you're loading in the GAC or the current application's bin folder. Use LoadFile
to load an arbitrary assembly file instead--but note that if you do this you'll need to load any dependencies yourself.
From project explorer ,just make sure that Servers is not closed
You can do it this with two replace's
//let stw be "John Smith $100,000.00 M"
sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"
sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"
sw.WriteLine(sb_trim);
After finding this StackOverflow question/answer
Complex type is getting null in a ApiController parameter
the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.
I already answered a really similar question here: Simple function to sort an array of objects
For that question I created this little function that might do what you want:
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
Download source code from here (Open Pdf from url in Android Programmatically)
MainActivity.java
package com.deepshikha.openpdf;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressBar progressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
webview.getSettings().setJavaScriptEnabled(true);
String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
progressbar.setVisibility(View.GONE);
}
});
}
}
Thanks!
All you have to do is read the code on getbootstrap.com:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<!-- Collect the nav links, forms, and other content for toggling -->_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="index.php">Home</a></li>_x000D_
<li><a href="about.php">About</a></li>_x000D_
<li><a href="#portfolio">Portfolio</a></li>_x000D_
<li><a href="#">Blog</a></li>_x000D_
<li><a href="contact.php">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>
_x000D_
After doing lots of analysis for my Ubuntu 20.04 I have found the solution
for me the error was /home/rk/Android/Sdk/tools/bin/sdkmanager
was missing write permission.
chmod +w home/rk/Android/Sdk/tools/bin/sdkmanager
Then run the below command.
flutter doctor --android-licenses
it automatically process the licences.
The Apache project has a library called POI which can be used to generate MS Office files. It is a Java library but the advantage is that it can run on Linux with no trouble. This library has its limitations but it may do the job for you, and it's probably simpler to use than trying to run Word.
Another option would be OpenOffice but I can't exactly recommend it since I've never used it.
The edit you posted was valid for an older version of React-router (v0.13) and doesn't work anymore.
Since version 1.0.0
you define optional parameters with:
<Route path="to/page(/:pathParam)" component={MyPage} />
and for multiple optional parameters:
<Route path="to/page(/:pathParam1)(/:pathParam2)" component={MyPage} />
You use parenthesis (
)
to wrap the optional parts of route, including the leading slash (/
). Check out the Route Matching Guide page of the official documentation.
Note: The :paramName
parameter matches a URL segment up to the next /
, ?
, or #
. For more about paths and params specifically, read more here.
React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.
Instead, you are instructed to define a path
parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?
).
As such, to define an optional parameter, you do:
<Route path="/to/page/:pathParam?" component={MyPage} />
and for multiple optional parameters:
<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />
Note: React Router v4 is incompatible with react-router-relay (read more here). Use version v3 or earlier (v2 recommended) instead.
I ported the C# sample to Objective-c and didn't see it in the responses:
//Usage
NSMutableArray* numberList = [[NSMutableArray alloc] init];
NSMutableArray* partial = [[NSMutableArray alloc] init];
int target = 16;
for( int i = 1; i<target; i++ )
{ [numberList addObject:@(i)]; }
[self findSums:numberList target:target part:partial];
//*******************************************************************
// Finds combinations of numbers that add up to target recursively
//*******************************************************************
-(void)findSums:(NSMutableArray*)numbers target:(int)target part:(NSMutableArray*)partial
{
int s = 0;
for (NSNumber* x in partial)
{ s += [x intValue]; }
if (s == target)
{ NSLog(@"Sum[%@]", partial); }
if (s >= target)
{ return; }
for (int i = 0;i < [numbers count];i++ )
{
int n = [numbers[i] intValue];
NSMutableArray* remaining = [[NSMutableArray alloc] init];
for (int j = i + 1; j < [numbers count];j++)
{ [remaining addObject:@([numbers[j] intValue])]; }
NSMutableArray* partRec = [[NSMutableArray alloc] initWithArray:partial];
[partRec addObject:@(n)];
[self findSums:remaining target:target part:partRec];
}
}
Example using std::vector
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main()
{
/// Initilaize vector using intitializer list ( requires C++11 )
std::vector<std::string> names = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
// Sort names using std::sort
std::sort(names.begin(), names.end() );
// Print using range-based and const auto& for ( both requires C++11 )
for(const auto& currentName : names)
{
std::cout << currentName << std::endl;
}
//... or by using your orignal for loop ( vector support [] the same way as plain arrays )
for(int y = 0; y < names.size(); y++)
{
std:: cout << names[y] << std::endl; // you were outputting name[z], but only increasing y, thereby only outputting element z ( 14 )
}
return 0;
}
This completely avoids using plain arrays, and lets you use the std::sort function. You might need to update you compiler to use the = {...}
You can instead add them by using vector.push_back("name")
You can use vim programmatically with the option -c {command} :
Dos to Unix:
vim file.txt -c "set ff=unix" -c ":wq"
Unix to dos:
vim file.txt -c "set ff=dos" -c ":wq"
"set ff=unix/dos" means change fileformat (ff) of the file to Unix/DOS end of line format
":wq" means write file to disk and quit the editor (allowing to use the command in a loop)
It would be inappropriate for it to be part of the setter - it's not like you're really setting the whole list of strings - you're just trying to add one.
There are a few options:
AddSubheading
and AddContent
methods in your class, and only expose read-only versions of the listsIn the second case, your code can be just:
public class Section
{
public String Head { get; set; }
private readonly List<string> _subHead = new List<string>();
private readonly List<string> _content = new List<string>();
// Note: fix to case to conform with .NET naming conventions
public IList<string> SubHead { get { return _subHead; } }
public IList<string> Content { get { return _content; } }
}
This is reasonably pragmatic code, although it does mean that callers can mutate your collections any way they want, which might not be ideal. The first approach keeps the most control (only your code ever sees the mutable list) but may not be as convenient for callers.
Making the setter of a collection type actually just add a single element to an existing collection is neither feasible nor would it be pleasant, so I'd advise you to just give up on that idea.
The thing I use is this:
In your template an alert area
<div id="alert-area"></div>
Then an jQuery function for showing an alert
function newAlert (type, message) {
$("#alert-area").append($("<div class='alert-message " + type + " fade in' data-alert><p> " + message + " </p></div>"));
$(".alert-message").delay(2000).fadeOut("slow", function () { $(this).remove(); });
}
newAlert('success', 'Oh yeah!');
creating or moving some/all reference containing worksheets (out and) into your workbook may solve it.
I had this issue after copying some sheets from "template" sheets/workbooks to some new "destination" workbook (the templates were provided by other users!):
I got:
project
on A1
)WbTempl2.Names("project").refersTo="C:\WbTempl1.xls]'WsTempl1RefDef!A1"
=project
)and wanted to create a WbDst to copy WsTempl1RefDef and WsTempl2RefUsr into it.
The following did not work:
Here as well the Ctrl(SHIFT)ALTF9 nor Application.CalculateFullRebuild
worked on WbDst.
The following worked:
For Query parameters like domain.com/test?format=json&type=mini
format, then you can easily receive it via - req.query.
app.get('/test', function(req, res){
var format = req.query.format,
type = req.query.type;
});
The best way is actually to create a new Project from scratch, then go into the folder with the project files you want to copy over (project, form1, everything except folders). Rename the files (Except for form1 files) for example: I copied Ch4Ex1 files into my Ch4Ex2 project but first renamed the files to Ch4Ex2. Copy and paste those files into the Solution Explorer for the new project in Visual Studio. Then just overwrite the files and you should be good to go!
Old thread but I hope it helps anyone looking for this answer!
Marco's answer above is correct, but just to expand on the question of "under what context"...
frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.
center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.
bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds]
on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.
Why is there an frame rectangle and an bounds rectangle in an UIView?
Hopefully this helps clarify the circumstances where each property might get used.
Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:
String to match: "my word"
String to search: "I'm searching for my funny words inside this text"
You need the following regex: /^(?=.*my)(?=.*word).*$/im
Explaining:
^ assert position at start of a line
?= Positive Lookahead
.* matches any character (except newline)
() Groups
$ assert position at end of a line
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
Test the Regex here: https://regex101.com/r/iS5jJ3/1
So, you can create a javascript function that:
Example:
function fullTextCompare(myWords, toMatch){_x000D_
//Replace regex reserved characters_x000D_
myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
//Split your string at spaces_x000D_
arrWords = myWords.split(" ");_x000D_
//Encapsulate your words inside regex groups_x000D_
arrWords = arrWords.map(function( n ) {_x000D_
return ["(?=.*"+n+")"];_x000D_
});_x000D_
//Create a regex pattern_x000D_
sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
//Execute the regex match_x000D_
return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
The shorter ES6 version of the answer:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
And then you can do:
delay(3000).then(() => console.log('Hello'));
What is the need of static method in interface, static methods are used basically when you don't have to create an instance of object whole idea of interface is to bring in OOP concepts with introduction of static method you're diverting from concept.
I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...
For example in order to change it's background to yellow:
$("#"+String(this.id)).css("background-color","yellow");
You can use any of the following:
\b #A word break and will work for both spaces and end of lines.
(^|\s) #the | means or. () is a capturing group.
/\b(stackoverflow)\b/
Also, if you don't want to include the space in your match, you can use lookbehind/aheads.
(?<=\s|^) #to look behind the match
(stackoverflow) #the string you want. () optional
(?=\s|$) #to look ahead.
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();
int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
MessageBox.show(i);
--Here i want to get the index or current row from the list
}
++i;
}
In python:
>>> 1.0 / 10
0.10000000000000001
Explain how some fractions cannot be represented precisely in binary. Just like some fractions (like 1/3) cannot be represented precisely in base 10.
If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:
$(document).ready(function() {
$("[id^=content]").hover(function() {
$(this).addClass('transition');
}, function() {
$(this).removeClass('transition');
});
});
Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.
You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :
window.open
then
window.close
will work. Or else not.
METHOD 1 ( Recommanded )
Library YouTubeExtractor
Add into your gradle file
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
And dependencies
compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
Add this small code and you done. Demo HERE
public class MainActivity extends AppCompatActivity {
private static final String YOUTUBE_ID = "ea4-5mrpGfE";
private final YouTubeExtractor mExtractor = YouTubeExtractor.create();
private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
@Override
public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
bindVideoResult(response.body());
}
@Override
public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
onError(t);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// For android youtube extractor library com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);
}
private void onError(Throwable t) {
t.printStackTrace();
Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
}
private void bindVideoResult(YouTubeExtractionResult result) {
// Here you can get download url link
Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());
Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
}
}
You can get download link in bindVideoResult() method.
METHOD 2
Using this library android-youtubeExtractor
Add into gradle file
repositories {
maven { url "https://jitpack.io" }
}
compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'
Here is the code for getting download url.
String youtubeLink = "http://youtube.com/watch?v=xxxx";
YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
@Override
public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
if (ytFiles != null) {
int itag = 22;
// Here you can get download url
String downloadUrl = ytFiles.get(itag).getUrl();
}
}
};
ytEx.execute(youtubeLink);
The functions below guard against empty strings,undefines,nulls, and max/min value ranges. The Javascript engine should have built in these functions from day one. :)
Enjoy!
function IsInteger(iVal) {
var iParsedVal; //our internal converted int value
iParsedVal = parseInt(iVal,10);
if (isNaN(iParsedVal) || Infinity == iParsedVal || -Infinity == iParsedVal) //sanity check - guard against empty strings and max/min values
return false;
else
return Number(iVal) === (iParsedVal | 0); //the 2nd operand group (intValue | 0), evaluates to true only if the intValue is an integer; so an int type will only return true
}
function IsFloat(fVal) {
var fParsedVal; //our internal converted float value
fParsedVal = parseFloat(fVal);
if (isNaN(fParsedVal) || Infinity == fParsedVal || -Infinity == fParsedVal) //sanity check - guard against empty strings and max/min values
return false;
else
return !!(fVal % 1); //true only if there is a fractional value after the mod op; the !! returns the opposite value of the op which reflects the function's return value
}
Following line in above code is not working
DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)
Correct line is:
DB_PASSWORD=`echo $PASSWORD|base64 -d`
And save the password in other file as PASSWORD.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ErrorDialog {
public static void main(String argv[]) {
String message = "\"The Comedy of Errors\"\n"
+ "is considered by many scholars to be\n"
+ "the first play Shakespeare wrote";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
JOptionPane.ERROR_MESSAGE);
}
}
In the spirit of providing functionality, go to your .profile
or .bashrc
file located at /home/usr/
and at the bottom add the line:
alias enw='emacs -nw'
Now each time you open a terminal session you just type, for example, enw
and you have the Emacs no-window option with three letters :).
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
In answer to your second question: What does this code do?...
This is fairly standard error-checking code for a Python script that accepts command-line arguments.
So the first if
statement translates to: if you haven't passed me an argument, I'm going to tell you how you should pass me an argument in the future, e.g. you'll see this on-screen:
Usage: myscript.py database-name
The next if
statement checks to see if the 'database-name' you passed to the script actually exists on the filesystem. If not, you'll get a message like this:
ERROR: Database database-name was not found!
From the documentation:
argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.
Writing that much data to a file is going to take a while.
You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).
You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?
You should also write a function to do the calculation; you could use an inline
function in C99 or later (or C++). The repetition in the code is excruciating to behold.
You should also use C99 notation for main()
, with the explicit return type (and preferably void
for the argument list when you are not using argc
or argv
):
int main(void)
Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 };
(thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static
in front of the functions, and the main array; file
becomes a local to main
; error check the fopen()
, etc.).
I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.
#include <stdio.h>
#define lambda 2.0
#define g 1.0
#define F0 1.0
#define h 0.1
#define e 0.00001
enum { ROWS = 1000, COLS = 10000 };
static double F[ROWS][COLS];
static void Inicio(double D[ROWS][COLS])
{
for (int i = 399; i < 600; i++) // Magic numbers!!
D[i][0] = F0;
}
enum { R = ROWS - 1 };
static inline int ko(int k, int n)
{
int rv = k + n;
if (rv >= R)
rv -= R;
else if (rv < 0)
rv += R;
return(rv);
}
static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
int ks2 = ko(k, -2);
int ks1 = ko(k, -1);
int kp1 = ko(k, +1);
int kp2 = ko(k, +2);
A[k][i] = A[k][i-1]
+ e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
+ 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
+ e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}
static void Iteration(double A[ROWS][COLS])
{
for (int i = 1; i < COLS; i++)
{
for (int k = 0; k < R; k++)
calculate_value(i, k, A);
A[999][i] = A[0][i];
}
}
int main(void)
{
FILE *file = fopen("P2.txt","wt");
if (file == 0)
return(1);
Inicio(F);
Iteration(F);
for (int i = 0; i < COLS; i++)
{
for (int j = 0; j < ROWS; j++)
{
fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
}
}
fclose(file);
return(0);
}
This program writes to P2.txt
instead of P1.txt
. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:
Original Modified
6.334s 6.367s
6.241s 6.231s
6.315s 10.778s
6.378s 6.320s
6.388s 6.293s
6.285s 6.268s
6.387s 10.954s
6.377s 6.227s
8.888s 6.347s
6.304s 6.286s
6.258s 10.302s
6.975s 6.260s
6.663s 6.847s
6.359s 6.313s
6.344s 6.335s
7.762s 6.533s
6.310s 9.418s
8.972s 6.370s
6.383s 6.357s
However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for
loop became:
for (int i = COLS - 1; i < COLS; i++)
the timings were vastly reduced and very much more consistent:
Original Modified
0.168s 0.165s
0.145s 0.165s
0.165s 0.166s
0.164s 0.163s
0.151s 0.151s
0.148s 0.153s
0.152s 0.171s
0.165s 0.165s
0.173s 0.176s
0.171s 0.165s
0.151s 0.169s
The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
var x = $('#h_v').val();
alert(x);
The best way is simply to have your client send a PING every X seconds, and for the server to assume it is disconnected after not having received one for a while.
I encountered the same issue as you when using sockets, and this was the only way I could do it. The socket.connected property was never correct.
In the end though, I switched to using WCF because it was far more reliable than sockets.
There is no native format in javascript for DD-Mon-YYYY
.
You will have to put it all together manually.
The answer is inspired from : How to format a JavaScript date
// Attaching a new function toShortFormat() to any instance of Date() class_x000D_
_x000D_
Date.prototype.toShortFormat = function() {_x000D_
_x000D_
let monthNames =["Jan","Feb","Mar","Apr",_x000D_
"May","Jun","Jul","Aug",_x000D_
"Sep", "Oct","Nov","Dec"];_x000D_
_x000D_
let day = this.getDate();_x000D_
_x000D_
let monthIndex = this.getMonth();_x000D_
let monthName = monthNames[monthIndex];_x000D_
_x000D_
let year = this.getFullYear();_x000D_
_x000D_
return `${day}-${monthName}-${year}`; _x000D_
}_x000D_
_x000D_
// Now any Date object can be declared _x000D_
let anyDate = new Date(1528578000000);_x000D_
_x000D_
// and it can represent itself in the custom format defined above._x000D_
console.log(anyDate.toShortFormat()); // 10-Jun-2018_x000D_
_x000D_
let today = new Date();_x000D_
console.log(today.toShortFormat()); // today's date
_x000D_
Use the javascript parseInt method (http://www.w3schools.com/jsref/jsref_parseint.asp)
var number = parseInt($(this).find('.number').text(), 10);
var current = 600;
if (current > number){
// do something
}
Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.
As in Internet Explorer, the javascript method "includes" doesn't support which is leading to the error as below
dijit.form.FilteringSelect TypeError: Object doesn't support property or method 'includes'
So I have changed the JavaScript string method from "includes" to "indexOf" as below
//str1 doesn't match str2 w.r.t index, so it will try to add object
var str1="acd", str2="b";
if(str1.indexOf(str2) == -1)
{
alert("add object");
}
else
{
alert("object not added");
}
You have to add a CSP meta tag in the head section of your app's index.html
As per https://github.com/apache/cordova-plugin-whitelist#content-security-policy
Content Security Policy
Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly).
On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g.
<video>
& WebSockets are not blocked). So, in addition to the whitelist, you should use a Content Security Policy<meta>
tag on all of your pages.On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView).
Here are some example CSP declarations for your
.html
pages:<!-- Good default declaration: * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: * Enable inline JS: add 'unsafe-inline' to default-src * Enable eval(): add 'unsafe-eval' to default-src --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *"> <!-- Allow requests to foo.com --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com"> <!-- Enable all requests, inline styles, and eval() --> <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"> <!-- Allow XHRs via https only --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' https:"> <!-- Allow iframe to https://cordova.apache.org/ --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">
parseInt()
is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers
, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Beware if you do decide to use parseInt()
! parseInt()
doesn't support good internationalization, so you have to jump through even more hoops:
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
To do this job in storyboard (Interface Builder Inspector)
With help of IBDesignable
, we can add more options to Interface Builder Inspector for UIButton
and tweak them on storyboard. First, add the following code to your project.
@IBDesignable extension UIButton {
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
@IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
Then simply set the attributes for buttons on storyboard.
following @tony's approach, changed the getTableHeight() function to
<div id="grid1" ui-grid="$ctrl.gridOptions" class="grid" ui-grid-auto-resize style="{{$ctrl.getTableHeight()}}"></div>
getTableHeight() {
var offsetValue = 365;
return "height: " + parseInt(window.innerHeight - offsetValue ) + "px!important";
}
the grid would have a dynamic height with regards to window height as well.
You can get posted form data from request.form
and query string data from request.args
.
myvar = request.form["myvar"]
myvar = request.args["myvar"]
I have just tested in Postgres 9.1 a solution which is close to Oracle ROWNUM:
select row_number() over() as id, t.*
from information_schema.tables t;
Yes, you can access it through GET
and POST
(trying this simple task would have made you aware of that).
Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.
This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.
It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.
You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.
To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator
property of the current culture's NumberFormatInfo
.
Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString()
to output the format you want, without worrying about changing the culture each time you output a number.
(Note that a neutral culture cannot have its decimal separator changed.)
Make sure you have enabled USB debugging on your device
Depending on the version of Android you're using, proceed as follows:
Return to the main Settings menu to find Developer options at the bottom. In the Developer options menu, scroll down and enable USB debugging.
In my case the issue was related to View Binding. It couldn't generate binding classes due to an invalid xml
layout file. In the file I had a Switch
with an id switch
, which is a Java keyword. Renaming the Switch
id resolved the issue.
You can use dirname
:
os.path.dirname(path)
Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().
And given the full path, then you can split normally to get the last portion of the path. For example, by using basename
:
os.path.basename(path)
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string ('').
All together:
>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'
Since Java9, both interfaces are deprecated, meaning you should not use them anymore. See Observer is deprecated in Java 9. What should we use instead of it?
However, you might still get interview questions about them...
for bootstrap4 vertical center of few items
d-flex for flex rules
flex-column for vertical direction on items
justify-content-center for centering
style='height: 300px;' must have for set points where center be calc or use h-100 class
then for horizontal center div d-flex justify-content-center and some container
so we have hierarhy of 3 tag: div-column -> div-row -> div-container
<div class="d-flex flex-column justify-content-center bg-secondary"
style="height: 300px;">
<div class="d-flex justify-content-center">
<div class=bg-primary>Flex item</div>
</div>
<div class="d-flex justify-content-center">
<div class=bg-primary>Flex item</div>
</div>
</div>
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
export function getFormattedDateAndTime(startDate) {
if (startDate != null) {
var launchDate = new Date(startDate);
var day = launchDate.getUTCDate();
var month = monthNames[launchDate.getMonth()];
var year = launchDate.getFullYear();
var min = launchDate.getMinutes();
var hour = launchDate.getHours();
var time = launchDate.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
return day + " " + month + " " + year + " - " + time + "" ;
}
return "";
}
Typically, I would suggest that you use the <optgroup>
option, as that gives some nice styling and indenting to the element.
The HTML element creates a grouping of options within a element. (Source: MDN Web Docs:
<optgroup>
.
But, since an <optgroup>
cannot be a selected value, you can make an <option selected disabled>
and then stylize it with CSS so that it behaves like an <optgroup>
....
.optionGroup {
font-weight: bold;
font-style: italic;
}
_x000D_
<select>
<option class="optionGroup" selected disabled>Choose one</option>
<option value="sydney" class="optionChild"> Sydney</option>
<option value="melbourne" class="optionChild"> Melbourne</option>
<option value="cromwell" class="optionChild"> Cromwell</option>
<option value="queenstown" class="optionChild"> Queenstown</option>
</select>
_x000D_
Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview
Below are the descriptions of different keystores from the post:
JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.
JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.
PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.
PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.
Use TRY_CAST function in exact same way of CAST function. TRY_CAST takes a string and tries to cast it to a data type specified after the AS keyword. If the conversion fails, TRY_CAST returns a NULL instead of failing.
A variable cannot be both null
and undefined
at the same time. However, the direct answer to your question is:
if (variable != null)
One =
, not two.
There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null
and the other being undefined
, and the result is true
for ==
and false
for !=
. Thus if the value of the variable is undefined
, it's not != null
, and if it's not null, it's obviously not != null
.
Now, the case of an identifier not being defined at all, either as a var
or let
, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:
var isDefined = false;
try {
(variable);
isDefined = true;
}
catch (x) {}
I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window
property (in browser JavaScript):
var isJqueryAvailable = window.jQuery != null;
or
var isJqueryAvailable = "jQuery" in window;
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
You can't cast a base object to a derived type - it isn't of that type.
If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:
DerivedType D;
BaseType B;
BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type
DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL
The problem is from regional Options . The decimal separator in win 7 for european countries is coma . You have to open Control Panel -> Regional and Language Options -> Aditional Settings -> Decimal Separator : click to enter a dot (.) and to List Separator enter a coma (,) . This is !
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
You'll need to compile it using:
g++ inputfile.cpp -o outputbinary
The file you are referring has a missing #include <cstdlib>
directive, if you also include that in your file, everything shall compile fine.
.NET does this for you. In your AssemblyInfo.cs file, set your assembly version to major.minor.* (for example: 1.0.*).
When you build your project the version is auto generated.
The build and revision numbers are generated based on the date, using the unix epoch, I believe. The build is based on the current day, and the revision is based on the number of seconds since midnight.
I get the same error on my JSP and the bad rated answer was correct
I had the folowing line:
<c:forEach var="agent" items=" ${userList}" varStatus="rowCounter">
and get the folowing error:
javax.el.PropertyNotFoundException: Property 'agent' not found on type java.lang.String
deleting the space before ${userList} solved my problem
If some have the same problem, he will find quickly this post and does not waste 3 days in googeling to find help.
Groupby A:
In [0]: grp = df.groupby('A')
Within each group, sum over B and broadcast the values using transform. Then sort by B:
In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
B
2 -2.829710
5 -2.829710
1 0.253651
4 0.253651
0 0.551377
3 0.551377
Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:
In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]
In [3]: sort1
Out[3]:
A B C
2 baz -0.528172 False
5 baz -2.301539 True
1 bar -0.611756 True
4 bar 0.865408 False
0 foo 1.624345 False
3 foo -1.072969 True
Finally, sort the 'C' values within groups of 'A' using the sort=False
option to preserve the A sort order from step 1:
In [4]: f = lambda x: x.sort('C', ascending=False)
In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)
In [6]: sort2
Out[6]:
A B C
A
baz 5 baz -2.301539 True
2 baz -0.528172 False
bar 1 bar -0.611756 True
4 bar 0.865408 False
foo 3 foo -1.072969 True
0 foo 1.624345 False
Clean up the df index by using reset_index
with drop=True
:
In [7]: sort2.reset_index(0, drop=True)
Out[7]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
Choose one you need:
>>> s = "Rajasekar SP def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP def')
I manually started mysql in the system preferences pane by initialising the database and then starting it. This solved my problem.
Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?
var ele = /*Your Form Element*/;
if(ele.addEventListener){
ele.addEventListener("submit", callback, false); //Modern browsers
}else if(ele.attachEvent){
ele.attachEvent('onsubmit', callback); //Old IE
}
callback
is a function that you want to call when the form is being submitted.
About EventTarget.addEventListener
, check out this documentation on MDN.
To cancel the native submit
event (prevent the form from being submitted), use .preventDefault()
in your callback function,
document.querySelector("#myForm").addEventListener("submit", function(e){
if(!isValid){
e.preventDefault(); //stop form from submitting
}
});
submit
event with librariesIf for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:
jQuery
$(ele).submit(callback);
Where ele
is the form element reference, and callback
being the callback function reference. Reference
<iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
_x000D_
AngularJS (1.x)
<form ng-submit="callback()">
$scope.callback = function(){ /*...*/ };
Very straightforward, where $scope
is the scope provided by the framework inside your controller. Reference
React
<form onSubmit={this.handleSubmit}>
class YourComponent extends Component {
// stuff
handleSubmit(event) {
// do whatever you need here
// if you need to stop the submit event and
// perform/dispatch your own actions
event.preventDefault();
}
// more stuff
}
Simply pass in a handler to the onSubmit
prop. Reference
Other frameworks/libraries
Refer to the documentation of your framework.
You can always do your validation in JavaScript, but with HTML5 we also have native validation.
<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">
You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.
Strings are immutable objects so you can copy them just coping the reference to them, because the object referenced can't change ...
So you can copy as in your first example without any problem :
String s = "hello";
String backup_of_s = s;
s = "bye";
Simply, the "Real Time" priority class is higher than "High" priority class. I don't think there's much more to it than that. Oh yeah - you have to have the SeIncreaseBasePriorityPrivilege
to put a thread into the Real Time class.
Windows will sometimes boost the priority of a thread for various reasons, but it won't boost the priority of a thread into another priority class. It also won't boost the priority of threads in the real-time priority class. So a High priority thread won't get any automatic temporary boost into the Real Time priority class.
Russinovich's "Inside Windows" chapter on how Windows handles priorities is a great resource for learning how this works:
Note that there's absolutely no problem with a thread having a Real-time priority on a normal Windows system - they aren't necessarily for special processes running on dedicatd machines. I imagine that multimedia drivers and/or processes might need threads with a real-time priority. However, such a thread should not require much CPU - it should be blocking most of the time in order for normal system events to get processing.
I settled for the limitation (to some people a benefit) of having my rows only one line of text high. The CSS to contain long strings then becomes:
.datatable td {
overflow: hidden; /* this is what fixes the expansion */
text-overflow: ellipsis; /* not supported in all browsers, but I accepted the tradeoff */
white-space: nowrap;
}
[edit to add:] After using my own code and initially failing, I recognized a second requirement that might help people. The table itself needs to have a fixed layout or the cells will just keep trying to expand to accomodate contents no matter what. If DataTables styles or your own styles don't already do so, you need to set it:
table.someTableClass {
table-layout: fixed
}
Now that text is truncated with ellipses, to actually "see" the text that is potentially hidden you can implement a tooltip plugin or a details button or something. But a quick and dirty solution is to use JavaScript to set each cell's title to be identical to its contents. I used jQuery, but you don't have to:
$('.datatable tbody td').each(function(index){
$this = $(this);
var titleVal = $this.text();
if (typeof titleVal === "string" && titleVal !== '') {
$this.attr('title', titleVal);
}
});
DataTables also provides callbacks at the row and cell rendering levels, so you could provide logic to set the titles at that point instead of with a jQuery.each
iterator. But if you have other listeners that modify cell text, you might just be better off hitting them with the jQuery.each
at the end.
This entire truncation method will ALSO have a limitation you've indicated you're not a fan of: by default columns will have the same width. I identify columns that are going to be consistently wide or consistently narrow, and explicitly set a percentage-based width on them (you could do it in your markup or with sWidth). Any columns without an explicit width get even distribution of the remaining space.
That might seem like a lot of compromises, but the end result was worth it for me.
look at the _.keys() and _.values() functions in either lodash or underscore
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";
This is a problem with your remote. When you do git push origin master
, origin
is the remote and master
is the branch you're pushing.
When you do this:
git remote
I bet the list does not include origin
. To re-add the origin remote:
git remote add origin [email protected]:your_github_username/your_github_app.git
Or, if it exists but is formatted incorrectly:
git remote rm origin
git remote add origin [email protected]:your_github_username/your_github_app.git
In case anyone else runs into this - the cause, in my case, was that I was using the (deprecated) docker compose
approach to push images. Switching to the expected docker push
resolved the issue for me.
You can specify USER
in the Dockerfile. All subsequent actions will be performed using that account. You can specify USER
one line before the CMD
or ENTRYPOINT
if you only want to use that user when launching a container (and not when building the image). When you start a container from the resulting image, you will attach as the specified user.
by using linkify: Linkify take a piece of text and a regular expression and turns all of the regex matches in the text into clickable links
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("http://www.domain.com");
Linkify.addLinks(textView, Linkify.WEB_URLS);
Don't forget to
import android.widget.TextView;
Localization with default language:
extension String {
func localized() -> String {
let defaultLanguage = "en"
let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
let bundle = Bundle(path: path!)
return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
}
}
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
Yes, it's possible. But first read, "What happens when I change my username?"
To change your username, click your profile picture in the top right corner, then click Settings
. On the left side, click Account
. Then click Change username
.
You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task
or Task<T>
, if you return nothing and you want your method will be run asyncronously you should define your method like this:
private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); }
And in Main method you can't await for DoDownloadAsync
, because you can't use await keyword in non-async function, and you can't make Main
async. So consider this:
var result = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); result.Wait();
You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".
A really simple line of Javascript can get the "non-taggy" text in all main browsers...
var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);
I have found the solution else where:
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)
In Java
, the mod operation can be performed as such:
Math.floorMod(a, b)
Note:
The mod operation is different from the remainder operation. In Java
, the remainder operation can be performed as such:
a % b
I had the same exception and I was excluding javassist
because of its issue with powermock
. Then I was adding it again as below but it was not working:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
<scope>test</scope>
</dependency>
Finally I found out that I have to remove <scope>test</scope>
from javassist
dependency. Hope it helps someone.
here is my solution. base on spring-boot.1.2.5.RELEASE.
application.properties
first.datasource.driver-class-name=com.mysql.jdbc.Driver
first.datasource.url=jdbc:mysql://127.0.0.1:3306/test
first.datasource.username=
first.datasource.password=
first.datasource.validation-query=select 1
second.datasource.driver-class-name=com.mysql.jdbc.Driver
second.datasource.url=jdbc:mysql://127.0.0.1:3306/test2
second.datasource.username=
second.datasource.password=
second.datasource.validation-query=select 1
DataSourceConfig.java
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix="first.datasource")
public DataSource firstDataSource() {
DataSource ds = DataSourceBuilder.create().build();
return ds;
}
@Bean
@ConfigurationProperties(prefix="second.datasource")
public DataSource secondDataSource() {
DataSource ds = DataSourceBuilder.create().build();
return ds;
}
}
If your app is a Scala app, it must have a build.sbt
in the root directory, and that file must be checked into Git. You can confirm this by running:
$ git ls-files build.sbt
If that file exists and is checked into Git, try running this command:
$ heroku buildpacks:set heroku/scala
Try this::
$(document).on("click",function(){
alert(event.target);
});
Although it is quite an old post but as i did some research on the topic so thought of sharing it.
hibernate.hbm2ddl.auto
As per the documentation it can have four valid values:
create | update | validate | create-drop
Following is the explanation of the behaviour shown by these value:
Following are the important points worth noting:
Table not found:<table name>
In case if i give any value to this property(say abc, instead of above four values discussed above) or it is just left blank. It shows following behaviour:
-If schema is not present in the DB:- It creates the schema
-If schema is present in the DB:- update the schema.
I've had this problem. See The Python "Connection Reset By Peer" Problem.
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a time.sleep(0.01)
placed strategically.
"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.
Finally found the answer.
@using MyNamespace
For VB.Net:
@Imports Mynamespace
Take a look at @ravy amiry's answer if you want to include a namespace across the app.
My approach was to make a virtual attribute instead of adding database columns.
class Choice
belongs_to :user
belongs_to :answer
# ------- Helpers -------
def question
answer.question
end
# extra sugar
def question_id
answer.question_id
end
end
This approach is pretty simple, but comes with tradeoffs. It requires Rails to load answer
from the db, and then question
. This can be optimized later by eager loading the associations you need (i.e. c = Choice.first(include: {answer: :question})
), however, if this optimization is necessary, then stephencelis' answer is probably a better performance decision.
There's a time and place for certain choices, and I think this choice is better when prototyping. I wouldn't use it for production code unless I knew it was for an infrequent use case.
protected $primaryKey = 'SongID';
After adding to my model to tell the primary key because it was taking id(SongID) by default
No, because there's no precompiler. However, in your case you could achieve the same thing as follows:
class MyClass
{
private static final int PROTEINS = 0;
...
MyArray[] foo = new MyArray[PROTEINS];
}
The compiler will notice that PROTEINS
can never, ever change and so will inline it, which is more or less what you want.
Note that the access modifier on the constant is unimportant here, so it could be public
or protected
instead of private, if you wanted to reuse the same constant across multiple classes.
Technically any static variable or Property on a class, anywhere in your project, will be a Global variable e.g.
public static class MyGlobalVariables
{
public static string MyGlobalString { get; set; }
}
But as @SLaks says, they can 'potentially' be bad practice and dangerous, if not handled correctly. For instance, in that above example, you would have multiple requests (threads) trying to access the same Property, which could be an issue if it was a complex type or a collection, you would have to implement some form of locking.
This is my take on expanding @klimat answer to not losing filtering animation.
public void filter(String query){
int completeListIndex = 0;
int filteredListIndex = 0;
while (completeListIndex < completeList.size()){
Movie item = completeList.get(completeListIndex);
if(item.getName().toLowerCase().contains(query)){
if(filteredListIndex < filteredList.size()) {
Movie filter = filteredList.get(filteredListIndex);
if (!item.getName().equals(filter.getName())) {
filteredList.add(filteredListIndex, item);
notifyItemInserted(filteredListIndex);
}
}else{
filteredList.add(filteredListIndex, item);
notifyItemInserted(filteredListIndex);
}
filteredListIndex++;
}
else if(filteredListIndex < filteredList.size()){
Movie filter = filteredList.get(filteredListIndex);
if (item.getName().equals(filter.getName())) {
filteredList.remove(filteredListIndex);
notifyItemRemoved(filteredListIndex);
}
}
completeListIndex++;
}
}
Basically what it does is looking through a complete list and adding/removing items to a filtered list one by one.
There is a static nested class, this [static nested] class does not need an instance of the enclosing class in order to be instantiated itself.
These classes [static nested ones] can access only the static members of the enclosing class [since it does not have any reference to instances of the enclosing class...]
code sample:
public class Test {
class A { }
static class B { }
public static void main(String[] args) {
/*will fail - compilation error, you need an instance of Test to instantiate A*/
A a = new A();
/*will compile successfully, not instance of Test is needed to instantiate B */
B b = new B();
}
}
jdk-7u80-macosx-x64.dmg fix this problem.
This worked for me:
for n in tf.get_default_graph().as_graph_def().node:
print('\n',n)
There is an article on javaworld.com that explains the difference => Which ClassLoader should you use
(1)
Thread context classloaders provide a back door around the classloading delegation scheme.
Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.
(2) from the same source:
This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:
- JNDI uses context classloaders
- Class.getResource() and Class.forName() use the current classloader
- JAXP uses context classloaders (as of J2SE 1.4)
- java.util.ResourceBundle uses the caller's current classloader
- URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
- Java Serialization API uses the caller's current classloader by default
This is a function snippet I wrote to scan the user input for a string and then store that string on an array of the same size as the user input. Note that I initialize j to the value of 2 to be able to store the '\0' character.
char* dynamicstring() {
char *str = NULL;
int i = 0, j = 2, c;
str = (char*)malloc(sizeof(char));
//error checking
if (str == NULL) {
printf("Error allocating memory\n");
exit(EXIT_FAILURE);
}
while((c = getc(stdin)) && c != '\n')
{
str[i] = c;
str = realloc(str,j*sizeof(char));
//error checking
if (str == NULL) {
printf("Error allocating memory\n");
free(str);
exit(EXIT_FAILURE);
}
i++;
j++;
}
str[i] = '\0';
return str;
}
In main(), you can declare another char* variable to store the return value of dynamicstring() and then free that char* variable when you're done using it.
You could also consider using getting the indexes of last elements in each specified dimensions using this as following;
int x = ary.GetUpperBound(0);
int y = ary.GetUpperBound(1);
Keep in mind that this gets the value of index as 0-based.
socket.gethostname()
could do
As of the latest versions of SQLite 3 you can issue:
.fullschema
to see all of your create statements.
Complete answer:
1. Is there a function available in SQL?
Yes, the SQL 92 spec, Oct 97, pg. 171, section 6.16 specifies this functions:
CURRENT_TIME Time of day at moment of evaluation
CURRENT_DATE Date at moment of evaluation
CURRENT_TIMESTAMP Date & Time at moment of evaluation
2. It is implementation depended so each database has its own function for this?
Each database has its own implementations, but they have to implement the three function above if they comply with the SQL 92 specification (but depends on the version of the spec)
3. What is the function available in MySQL?
NOW() returns 2009-08-05 15:13:00
CURDATE() returns 2009-08-05
CURTIME() returns 15:13:00
change this {% if loop.counter == 1 %}
to {% if forloop.counter == 1 %} {#your code here#} {%endfor%}
and this from {{ user }} {{loop.counter}}
to {{ user }} {{forloop.counter}}
if you open localhost/phpmyadmin
you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.
Could not commit JPA transaction: Transaction marked as rollbackOnly
This exception occurs when you invoke nested methods/services also marked as @Transactional
. JB Nizet explained the mechanism in detail. I'd like to add some scenarios when it happens as well as some ways to avoid it.
Suppose we have two Spring services: Service1
and Service2
. From our program we call Service1.method1()
which in turn calls Service2.method2()
:
class Service1 {
@Transactional
public void method1() {
try {
...
service2.method2();
...
} catch (Exception e) {
...
}
}
}
class Service2 {
@Transactional
public void method2() {
...
throw new SomeException();
...
}
}
SomeException
is unchecked (extends RuntimeException) unless stated otherwise.
Scenarios:
Transaction marked for rollback by exception thrown out of method2
. This is our default case explained by JB Nizet.
Annotating method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating both method1
and method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating method2
with @Transactional(noRollbackFor = SomeException)
prevents marking transaction for rollback (no exception thrown when exiting from method1
).
Suppose method2
belongs to Service1
. Invoking it from method1
does not go through Spring's proxy, i.e. Spring is unaware of SomeException
thrown out of method2
. Transaction is not marked for rollback in this case.
Suppose method2
is not annotated with @Transactional
. Invoking it from method1
does go through Spring's proxy, but Spring pays no attention to exceptions thrown. Transaction is not marked for rollback in this case.
Annotating method2
with @Transactional(propagation = Propagation.REQUIRES_NEW)
makes method2
start new transaction. That second transaction is marked for rollback upon exit from method2
but original transaction is unaffected in this case (no exception thrown when exiting from method1
).
In case SomeException
is checked (does not extend RuntimeException), Spring by default does not mark transaction for rollback when intercepting checked exceptions (no exception thrown when exiting from method1
).
See all scenarios tested in this gist.
Multiple Image upload using php full source code and preview available at the below Link.
Sample code:
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) { //loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i])); //explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path.md5(uniqid()).
".".$ext[count($ext) - 1]; //set the target path with a new name of image
$j = $j + 1; //increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) { //if file moved to uploads folder
echo $j.
').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { //if file was not moved.
echo $j.
').<span id="error">please try again!.</span><br/><br/>';
}
} else { //if file size and file type was incorrect.
echo $j.
').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
http://www.allinworld99.blogspot.com/2015/05/php-multiple-file-upload.html
To give a modern approach to this question. This works well, including Ctrl+v. GlobalEventHandlers.oninput.
var onChange = function(evt) {
console.info(this.value);
// or
console.info(evt.target.value);
};
var input = document.getElementById('some-id');
input.addEventListener('input', onChange, false);
If you are testing this on your local WAMP you might need to set up the temporary folder for file uploads. You can do this in your PHP.ini file:
upload_tmp_dir = "c:\mypath\mytempfolder\"
You will need to grant permissions on the folder to allow the upload to take place - the permission you need to grant vary based on your operating system.
& is bitwise AND operator comparing bits of each operand.
For example,
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.
This worked for me:
$scanresults = Invoke-Expression "& 'C:\Program Files (x86)\Nmap\nmap.exe' -vv -sn 192.168.1.1-150 --open"
Press CTRL+F11
to rotate the screen.
Kompare is fine for diff, but I use dirdiff. Although it looks ugly, dirdiff can do 3-way merge - and you can get everything done inside the tool (both diff and merge).