You have to set classpath for mysql-connector.jar
In eclipse, use the build path
If you are developing any web app, you have to put mysql-connector to the lib folder of WEB-INF Directory of your web-app
Sounds like you probably want a simple method like this:
public String getValueOrDefault(String value, String defaultValue) {
return isNotNullOrEmpty(value) ? value : defaultValue;
}
Then:
String result = getValueOrDefault(System.getProperty("XYZ"), "default");
At this point, you don't need temp
... you've effectively used the method parameter as a way of initializing the temporary variable.
If you really want temp
and you don't want an extra method, you can do it in one statement, but I really wouldn't:
public class Test {
public static void main(String[] args) {
String temp, result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
System.out.println("result: " + result);
System.out.println("temp: " + temp);
}
private static boolean isNotNullOrEmpty(String str) {
return str != null && !str.isEmpty();
}
}
Go to the folder where eclipse is installed
open eclipse.ini file
look for the line -vmargs
put -Djava.net.preferIPv4Stack=true below the -vmargs line and restart eclipse
all answers are wrong. "Opera" and "Chrome" are same in all cases.
(edited part)
here is the right answer
if (window.chrome && window.chrome.webstore) {
// this is Chrome
}
This is my html code for solution. It works for Chrome-Safari-Internet Explorer. I created new font which all characters seem as "?". Then I use this font for my password text. Note: My font name is "passwordsecretregular".
<style type="text/css">
#login_parola {
font-family: 'passwordsecretregular' !important;
-webkit-text-security: disc !important;
font-size: 22px !important;
}
</style>
<input type="text" class="w205 has-keyboard-alpha" name="login_parola" id="login_parola" onkeyup="checkCapsWarning(event)"
onfocus="checkCapsWarning(event)" onblur="removeCapsWarning()" onpaste="return false;" maxlength="32"/>
My fix for this on Mountain Lion was: -
npm install -g grunt-cli
Saw it on http://gruntjs.com/getting-started
According to Fixture finalization / executing teardown code, the current best practice for setup and teardown is to use yield
instead of return
:
import pytest
@pytest.fixture()
def resource():
print("setup")
yield "resource"
print("teardown")
class TestResource:
def test_that_depends_on_resource(self, resource):
print("testing {}".format(resource))
Running it results in
$ py.test --capture=no pytest_yield.py
=== test session starts ===
platform darwin -- Python 2.7.10, pytest-3.0.2, py-1.4.31, pluggy-0.3.1
collected 1 items
pytest_yield.py setup
testing resource
.teardown
=== 1 passed in 0.01 seconds ===
Another way to write teardown code is by accepting a request
-context object into your fixture function and calling its request.addfinalizer
method with a function that performs the teardown one or multiple times:
import pytest
@pytest.fixture()
def resource(request):
print("setup")
def teardown():
print("teardown")
request.addfinalizer(teardown)
return "resource"
class TestResource:
def test_that_depends_on_resource(self, resource):
print("testing {}".format(resource))
Check "Virtualization" status under performance option in your task manager. If you already have enabled it in your BIOS and still status is "Disabled", then go to bios, disable it and save & exit. Restart or shut down again. Enable it in BIOS again and save & exit. This time you'll see the status changed to "Enabled", It took me 3 attempts (don't know why it took that much time, but finally it worked).
You are making an ajax request which is asynchronous therefore your console log of the list length occurs before the ajax request has completed.
The only way of achieving what you want is changing the ajax call to be synchronous. You can do this by using the .ajax and passing in asynch : false however this is not recommended as it locks the UI up until the call has returned, if it fails to return the user has to crash out of the browser.
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
AStyle can be customized in great detail for C++ and Java (and others too)
This is a source code formatting tool.
clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.
It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).
It can be configured with a variety of options listed here.
When using config files (named .clang-format
) styles can be per directory - the closest such file in parent directories shall be used for a particular file.
Styles can be inherited from a preset (say LLVM or Google) and can later override different options
It is used by Google and others and is production ready.
Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.
Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.
@Wardenclyffe and @SColvin, you both are trying to save image using the canvas, not by using canvas's context. both you should try to ctx.toDataURL(); Try This:
var canvas1 = document.getElementById("yourCanvasId"); <br>
var ctx = canvas1.getContext("2d");<br>
var img = new Image();<br>
img.src = ctx.toDataURL('image/png');<br>
ctx.drawImage(img,200,150);<br>
Also you may refer to following links:
http://tutorials.jenkov.com/html5-canvas/todataurl.html
http://www.w3.org/TR/2012/WD-html5-author-20120329/the-canvas-element.html#the-canvas-element
demo - http://jsfiddle.net/victor_007/ywevz8ra/
added border for better view (testing)
more info about white-space
table{
width:100%;
}
table td{
white-space: nowrap; /** added **/
}
table td:last-child{
width:100%;
}
table {_x000D_
width: 100%;_x000D_
}_x000D_
table td {_x000D_
white-space: nowrap;_x000D_
}_x000D_
table td:last-child {_x000D_
width: 100%;_x000D_
}
_x000D_
<table border="1">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column A</th>_x000D_
<th>Column B</th>_x000D_
<th>Column C</th>_x000D_
<th class="absorbing-column">Column D</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data A.1 lorem</td>_x000D_
<td>Data B.1 ip</td>_x000D_
<td>Data C.1 sum l</td>_x000D_
<td>Data D.1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.2 ipsum</td>_x000D_
<td>Data B.2 lorem</td>_x000D_
<td>Data C.2 some data</td>_x000D_
<td>Data D.2 a long line of text that is long</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.3</td>_x000D_
<td>Data B.3</td>_x000D_
<td>Data C.3</td>_x000D_
<td>Data D.3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
Try this
span {
display: block;
width: 150px;
}
One way would be to use Array reduce..
const max = data.reduce(function(prev, current) {
return (prev.y > current.y) ? prev : current
}) //returns object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce http://caniuse.com/#search=reduce (IE9 and above)
If you don't need to support IE (only Edge), or can use a pre-compiler such as Babel you could use the more terse syntax.
const max = data.reduce((prev, current) => (prev.y > current.y) ? prev : current)
Since I see lots of comments about people having problems with the plugin, I thought I'd mention the work around that I use.
I just use one of the online sites for XML viewing (I use https://codebeautify.org/xmlviewer, but there are plenty out there) as follows:
I don't know if it qualifies as answering the OP's question exactly, but it's very simple and easy for anyone who is having problems with the plugin.
Yes we can change that but with some more attention
Now add this in your build.gradle in your project while make sure you have checked the build variant of your project like release or Debug
so here I have set my build variant as release
but you may select as Debug as well.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig getSigningConfig()
applicationVariants.all { variant ->
variant.outputs.each { output ->
def date = new Date();
def formattedDate = date.format('yyyyMMddHHmmss')
output.outputFile = new File(output.outputFile.parent,
output.outputFile.name.replace("-release", "-" + formattedDate)
//for Debug use output.outputFile = new File(output.outputFile.parent,
// output.outputFile.name.replace("-debug", "-" + formattedDate)
)
}
}
}
}
You may Do it With different Approach Like this
defaultConfig {
applicationId "com.myapp.status"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
setProperty("archivesBaseName", "COMU-$versionName")
}
Using Set property method in build.gradle and Don't forget to sync the gradle before running the projects Hope It will solve your problem :)
A New approach to handle this added recently by google update You may now rename your build according to flavor or Variant output //Below source is from developer android documentation For more details follow the above documentation link
Using the Variant API to manipulate variant outputs is broken with the new plugin. It still works for simple tasks, such as changing the APK name during build time, as shown below:
// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.name}-${variant.versionName}.apk"
}
}
Renaming .aab bundle This is nicely answered by David Medenjak
tasks.whenTaskAdded { task ->
if (task.name.startsWith("bundle")) {
def renameTaskName = "rename${task.name.capitalize()}Aab"
def flavor = task.name.substring("bundle".length()).uncapitalize()
tasks.create(renameTaskName, Copy) {
def path = "${buildDir}/outputs/bundle/${flavor}/"
from(path)
include "app.aab"
destinationDir file("${buildDir}/outputs/renamedBundle/")
rename "app.aab", "${flavor}.aab"
}
task.finalizedBy(renameTaskName)
}
//@credit to David Medenjak for this block of code
}
Is there need of above code
What I have observed in the latest version of the android studio 3.3.1
The rename of .aab bundle is done by the previous code there don't require any task rename at all.
Hope it will help you guys. :)
you can:
use integer;
it is explained by Michael Ratanapintha or else use manually:
$a=3.7;
$b=2.1;
$c=int(int($a)/int($b));
notice, 'int' is not casting. this is function for converting number to integer form. this is because Perl 5 does not have separate integer division. exception is when you 'use integer'. Then you will lose real division.
Straight from the docs
join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
This means that the main thread which spawns t
and d
, waits for t
to finish until it finishes.
Depending on the logic your program employs, you may want to wait until a thread finishes before your main thread continues.
Also from the docs:
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left.
A simple example, say we have this:
def non_daemon():
time.sleep(5)
print 'Test non-daemon'
t = threading.Thread(name='non-daemon', target=non_daemon)
t.start()
Which finishes with:
print 'Test one'
t.join()
print 'Test two'
This will output:
Test one
Test non-daemon
Test two
Here the master thread explicitly waits for the t
thread to finish until it calls print
the second time.
Alternatively if we had this:
print 'Test one'
print 'Test two'
t.join()
We'll get this output:
Test one
Test two
Test non-daemon
Here we do our job in the main thread and then we wait for the t
thread to finish. In this case we might even remove the explicit joining t.join()
and the program will implicitly wait for t
to finish.
I suspect that the xcopy
command is the magic bullet you're looking for.
It can copy files, directories, and even entire drives while preserving the original directory hierarchy. There are also a handful of additional options available, compared to the basic copy
command.
Check out the documentation here.
If your batch file only needs to run on Windows Vista or later, you can use robocopy
instead, which is an even more powerful tool than xcopy
, and is now built into the operating system. It's documentation is available here.
Use the Array#join
method (the argument to join
is what to insert between the strings - in this case a space):
@arr.join(" ")
Do it like this:
TextField(
decoration: new InputDecoration.collapsed(
hintText: 'Username'
),
),
or if you need other stuff like icon, set the border with InputBorder.none
InputDecoration(
border: InputBorder.none,
hintText: 'Username',
),
),
While Large Text File Viewer works great for just looking at a large file (and is free!), if the file is either a delimited or fixed-width file, then you should check out File Query. Not only can it open a file of any size (I have personally opened a 280GB file, but it can go larger), but it lets you query the file as though it was in a database as well, finding out any sort of information you could want from it.
It is not free though, so it is more for people that work with large files a lot, but if you have a one-off problem, you can just use the 30-day trial for free.
it will load ViewWillAppear
everytime you open the view. above is the link to the picture View Controller Lifecycle.
viewWillAppear()—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen. Despite the name, just because the system calls this method, it does not guarantee that the content view will become visible. The view may be obscured by other views or hidden. This method simply indicates that the content view is about to be added to the app’s view hierarchy.
@Hung Tran's answer works perfect. As an improvement, I would suggest not showing values that are 0. Say you have 5 elements and 2 of them are 0 and rest of them have values, the solution above will show 0 and 0%. It is better to filter that out with a not equal to 0 check!
var val = dataset.data[i]; var percent = String(Math.round(val/total*100)) + "%"; if(val != 0) { ctx.fillText(dataset.data[i], model.x + x, model.y + y); // Display percent in another line, line break doesn't work for fillText ctx.fillText(percent, model.x + x, model.y + y + 15); }
Updated code below:
var data = {
datasets: [{
data: [
11,
16,
7,
3,
14
],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
]
};
var pieOptions = {
events: false,
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle)/2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i == 3){ // Darker text color for lighter background
ctx.fillStyle = '#444';
}
var val = dataset.data[i];
var percent = String(Math.round(val/total*100)) + "%";
if(val != 0) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
}
});
}
}
};
var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pieOptions
});
Sending data from Activity into Fragments linked by XML
If you create a fragment in Android Studio using one of the templates e.g. File > New > Fragment > Fragment (List), then the fragment is linked via XML. The newInstance method is created in the fragment but is never called so can't be used to pass arguments.
Instead in the Activity override the method onAttachFragment
@Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof DetailsFragment) {
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
}
}
Then read the arguments in the fragment onCreate method as per the other answers
Another way to read/write Excel files is to use Windmill. It provides a fluent API to process Excel and CSV files.
try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) {
rowStream
// skip the header row that contains the column names
.skip(1)
.forEach(row -> {
System.out.println(
"row n°" + row.rowIndex()
+ " column 'User login' value : " + row.cell("User login").asString()
+ " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based
);
});
}
Windmill
.export(Arrays.asList(bean1, bean2, bean3))
.withHeaderMapping(
new ExportHeaderMapping<Bean>()
.add("Name", Bean::getName)
.add("User login", bean -> bean.getUser().getLogin())
)
.asExcel()
.writeTo(new FileOutputStream("Export.xlsx"));
stats = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv")
The Output of stats:
A B C
0 0.120064 0.785538 0.465853
1 0.431655 0.436866 0.640136
2 0.445904 0.311565 0.934073
3 0.981609 0.695210 0.911697
4 0.008632 0.629269 0.226454
5 0.577577 0.467475 0.510031
6 0.580909 0.232846 0.271254
7 0.696596 0.362825 0.556433
8 0.738912 0.932779 0.029723
9 0.834706 0.002989 0.333436
just use skipfooter=1
skipfooter : int, default 0
Number of lines at bottom of file to skip
stats_2 = pd.read_csv("C:\\py\\programs\\second pandas\\ex.csv", skipfooter=1, engine='python')
Output of stats_2
A B C
0 0.120064 0.785538 0.465853
1 0.431655 0.436866 0.640136
2 0.445904 0.311565 0.934073
3 0.981609 0.695210 0.911697
4 0.008632 0.629269 0.226454
5 0.577577 0.467475 0.510031
6 0.580909 0.232846 0.271254
7 0.696596 0.362825 0.556433
8 0.738912 0.932779 0.029723
If your computer has python, you can try this from the shell:
python -c "print len(open('test.txt').read().split('\n'))"
This uses python -c
to pass in a command, which is basically reading the file, and splitting by the "newline", to get the count of newlines, or the overall length of the file.
bash-3.2$ sed -n '$=' test.txt
519
Using the above:
bash-3.2$ python -c "print len(open('test.txt').read().split('\n'))"
519
In addition, you can build the binary package using the --binary option.
R CMD build --binary RJSONIO_0.2-3.tar.gz
First, use the bounding boxes as described by Jonathan Holland to find if you may have a collision.
From the (multi-color) sprites, create black and white versions. You probably already have these if your sprites are transparent (i.e. there are places which are inside the bounding box but you can still see the background). These are "masks".
Use Image.getRGB()
on the mask to get at the pixels. For each pixel which isn't transparent, set a bit in an integer array (playerArray
and enemyArray
below). The size of the array is height
if width <= 32
pixels, (width+31)/32*height
otherwise. The code below is for width <= 32
.
If you have a collision of the bounding boxes, do this:
// Find the first line where the two sprites might overlap
int linePlayer, lineEnemy;
if (player.y <= enemy.y) {
linePlayer = enemy.y - player.y;
lineEnemy = 0;
} else {
linePlayer = 0;
lineEnemy = player.y - enemy.y;
}
int line = Math.max(linePlayer, lineEnemy);
// Get the shift between the two
x = player.x - enemy.x;
int maxLines = Math.max(player.height, enemy.height);
for ( line < maxLines; line ++) {
// if width > 32, then you need a second loop here
long playerMask = playerArray[linePlayer];
long enemyMask = enemyArray[lineEnemy];
// Reproduce the shift between the two sprites
if (x < 0) playerMask << (-x);
else enemyMask << x;
// If the two masks have common bits, binary AND will return != 0
if ((playerMask & enemyMask) != 0) {
// Contact!
}
}
Links: JGame, Framework for Small Java Games
If you are on OSX and have compiled python from source:
Install openssl using brew brew install openssl
Make sure to follow the instructions brew gives you about setting your CPPFLAGS
and LDFLAGS
. In my case I am using the [email protected]
brew formula and I need these 3 settings for the python build process to correctly link to my SSL library:
export LDFLAGS="-L/usr/local/opt/[email protected]/lib"
export CPPFLAGS="-I/usr/local/opt/[email protected]/include"
export PKG_CONFIG_PATH="/usr/local/opt/[email protected]/lib/pkgconfig"
Assuming the library is installed at that location.
You can use
"CamelCasedName".tableize.singularize
Or just
"CamelCasedName".underscore
Both options ways will yield "camel_cased_name"
. You can check more details it here.
With integers, it's preference.
If the loop variable is a class/object, it can make a difference (only profiling can tell you if it's a significant difference), because the post-increment version requires that you create a copy of that object that gets discarded.
If creating that copy is an expensive operation, you're paying that expense once for every time you go through the loop, for no reason at all.
If you get into the habit of always using ++i
in for loops, you don't need to stop and think about whether what you're doing in this particular situation makes sense. You just always are.
If you're sure you configure your aws correctly, just make sure the user of the project can read from ./aws or just run your project as a root
Even once you fixed the mis-cased if
and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in
. Here's how you'd do it (and note that if
is all lowercase and that the code within the if
block is indented one level).
One approach:
if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
print("this will do the calculation")
Another:
if answer.lower() in ['y', 'yes']:
print("this will do the calculation")
It looks like you correct: The Migration Toolkit is due to be integrated with MySQL Workbench - but I do not think this has been completed yet. See the End-of-life announcement for MySQL GUI Tools (which included the Migration Toolkit):
http://www.mysql.com/support/eol-notice.html
MySQL maintain archives of the MySQL GUI Tools packages:
This:
<img onerror="this.src='/images/image.png'" src="...">
The solution for me was to change the .NET framework version in the Application Pools from v4.0 to v2.0 for the Default App Pool:
(1) Your <script>
tag should be placed before the closing </body>
tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
<script type="text/javascript">
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
</script>
</body>
I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'MyTable'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
some_col = Column(String(500))
def __init__(self, some_col):
self.some_col = some_col
engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
for class_instance in session.query(MyTable).all():
print(vars(class_instance))
session.close()
If you can't change the datatype on the table itself to use varchar(max), then change your query to this:
SELECT *
FROM [Village]
WHERE CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'
1) It looks possible. This info on Github describes how to create a java program to send a message using the whatsapp encryption protocol from WhisperSystems.
2) No. See the whatsapp security white paper.
3) See #1.
The question did not specify if command line command named curl
was meant or the whole cURL library.
The following PHP code using cURL library uses first parameter as HTTP method (e.g. "GET", "POST", "OPTIONS") and second parameter as URL.
<?php
$ch = curl_init();
$f = tmpfile(); # will be automatically removed after fclose()
curl_setopt_array($ch, array(
CURLOPT_CUSTOMREQUEST => $argv[1],
CURLOPT_URL => $argv[2],
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 0,
CURLOPT_VERBOSE => 1,
CURLOPT_HEADER => 0,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_STDERR => $f,
));
$response = curl_exec($ch);
fseek($f, 0);
echo fread($f, 32*1024); # output up to 32 KB cURL verbose log
fclose($f);
curl_close($ch);
echo $response;
Example usage:
php curl-test.php OPTIONS https://google.com
Note that the results are nearly identical to following command line
curl -v -s -o - -X OPTIONS https://google.com
This option works only if you can open the DB in a DB Browser like DB Browser for SQLite.
In DB Browser for SQLite:
Here is another FastRGB implementation found here:
public class FastRGB {
public int width;
public int height;
private boolean hasAlphaChannel;
private int pixelLength;
private byte[] pixels;
FastRGB(BufferedImage image) {
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
width = image.getWidth();
height = image.getHeight();
hasAlphaChannel = image.getAlphaRaster() != null;
pixelLength = 3;
if (hasAlphaChannel)
pixelLength = 4;
}
short[] getRGB(int x, int y) {
int pos = (y * pixelLength * width) + (x * pixelLength);
short rgb[] = new short[4];
if (hasAlphaChannel)
rgb[3] = (short) (pixels[pos++] & 0xFF); // Alpha
rgb[2] = (short) (pixels[pos++] & 0xFF); // Blue
rgb[1] = (short) (pixels[pos++] & 0xFF); // Green
rgb[0] = (short) (pixels[pos++] & 0xFF); // Red
return rgb;
}
}
What is this?
Reading an image pixel by pixel through BufferedImage's getRGB method is quite slow, this class is the solution for this.
The idea is that you construct the object by feeding it a BufferedImage instance, and it reads all the data at once and stores them in an array. Once you want to get pixels, you call getRGB
Dependencies
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
Considerations
Although FastRGB makes reading pixels much faster, it could lead to high memory usage, as it simply stores a copy of the image. So if you have a 4MB BufferedImage in the memory, once you create the FastRGB instance, the memory usage would become 8MB. You can however, recycle the BufferedImage instance after you create the FastRGB.
Be careful to not fall into OutOfMemoryException when using it on devices such as Android phones, where RAM is a bottleneck
You could also use Format$(Now(), "Short Date") or whatever date format you want. Be aware, this function will return the Date as a string, so using Date() is a better approach.
Okay so it goes like this:
You have created a virtual environment and django module belongs to that environment only.Since virtualenv isolates itself from everything else,hence you are seeing this.
go through this for further assistance:
1.You can switch to the directory where your virtual environment is stored and then run the django module.
2.Alternatively you can install django globally to your python->site-packages by either running pip or easy_install
Command using pip: pip install django
then do this:
import django print (django.get_version()) (depending on which version of python you use.This for python 3+ series)
and then you can run this: python manage.py runserver and check on your web browser by typing :localhost:8000 and you should see django powered page.
Hope this helps.
Had several modules complain about patch does not apply. One thing I was missing out was that the branches had become stale. After the git merge master
generated the patch files using git diff master BRANCH > file.patch
. Going to the vanilla branch was able to apply the patch with git apply file.patch
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
One stupid mistake I did awhile ago that might help some people.
Keep in mind that if you are using ":" in an event like this, the value will not change
var ondrag = (function(event, ui) {
...
nub0x: event.target.offsetLeft + event.target.clientWidth/2;
nub0y = event.target.offsetTop + event.target.clientHeight/2;
...
});
So "nub0x" will initialize with the first event that happens and will never change its value. But "nub0y" will change during the next events.
It was weird that no one suggested KVM.
It is gonna provide you almost native performance and it is built-in Linux. Go and check it out.
you will feel like u are using mac only and then install Xcode there u may even choose to directly boot into the OSX GUI instead of Linux one on startup
From http://en.wikipedia.org/wiki/Byte-order_mark:
The byte order mark (BOM) is a Unicode character used to signal the endianness (byte order) of a text file or stream. Its code point is U+FEFF. BOM use is optional, and, if used, should appear at the start of the text stream. Beyond its specific use as a byte-order indicator, the BOM character may also indicate which of the several Unicode representations the text is encoded in.
Always using a BOM in your file will ensure that it always opens correctly in an editor which supports UTF-8 and BOM.
My real problem with the absence of BOM is the following. Suppose we've got a file which contains:
abc
Without BOM this opens as ANSI in most editors. So another user of this file opens it and appends some native characters, for example:
abg-aß?
Oops... Now the file is still in ANSI and guess what, "aß?" does not occupy 6 bytes, but 3. This is not UTF-8 and this causes other problems later on in the development chain.
I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:
dig @ns1.nameserver1.com domain.com txt
Use the start command as follows.
start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.google.com
It will be better to close chrome instances before you open a new one. You can do that as follows:
taskkill /IM chrome.exe
start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.google.com
That'll work for you.
Try to insert this:
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
before getting the JDBC Connection.
Use the following command to clear screen in sqlplus.
SQL > clear scr
.
System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
; For Windows Users to back to temp directory
set backup
set backupdir=C:\WINDOWS\Temp
set backupskip=C:\WINDOWS\Temp\*
set directory=C:\WINDOWS\Temp
set writebackup
FORMAT()
is slower than CONVERT()
. This answer is slightly better than @jpx's answer because it only does a replace on the time part of the date.
112 = yyyymmdd - no format change needed
108 = hh:mm:ss - remove :
SELECT CONVERT(VARCHAR, GETDATE(), 112) +
REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '')
it is a known issue
I think the workaround should be set it as
.card-img-top {
width: 100%;
}
The easiest way is probably to create an std::bitset
representing the value, then stream that to cout
.
#include <bitset>
...
char a = -58;
std::bitset<8> x(a);
std::cout << x << '\n';
short c = -315;
std::bitset<16> y(c);
std::cout << y << '\n';
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
You can avoid the repetition with an attribute test instead:
a/b/*[local-name()='c' or local-name()='d' or local-name()='e']
Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self::
axis is namespace restrictive, local-name()
is not. If the OP's intention is to capture c|d|e
regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.
You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.
if you are not able to find the rails process to kill it might actually be not running. Delete the tmp folder and its sub-folders from where you are running the rails server and try again.
How about using fn:replace(string,pattern,replace) instead?
XPATH is very often used in XSLTs and if you are in that situation and does not have XPATH 2.0 you could use:
<xsl:choose>
<xsl:when test="condition1">
condition1-statements
</xsl:when>
<xsl:when test="condition2">
condition2-statements
</xsl:when>
<xsl:otherwise>
otherwise-statements
</xsl:otherwise>
</xsl:choose>
Looks like the type is boolean and therefore can never be null and should be false by default.
use setRawInputType and setKeyListener
editTextNumberPicker.setRawInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_NUMBER_FLAG_SIGNED );
editTextNumberPicker.setKeyListener(DigitsKeyListener.getInstance(false,true));//set decimals and positive numbers.
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript">
function omtCallFromAjax(urlVariable)
{
alert("omt:"+urlVariable);
$("#omtDiv").load("omtt.php?"+urlVariable);
}
</script>
try this it work for me
Completeness
You need to check both $mysqli
and $statement
. If they are false, you need to output $mysqli->error
or $statement->error
respectively.
Efficiency
For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.
Usage example 1: Simple script
# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);
Usage example 2: Application
# This is part of an application
class FuzDatabaseException extends Exception {
}
class Foo {
public $mysqli;
public function __construct(mysqli $mysqli) {
$this->mysqli = $mysqli;
}
public function updateBar() {
$q = "UPDATE foo SET bar=1";
$statement = $this->mysqli->prepare($q);
if (!$statement) {
throw new FuzDatabaseException($mysqli->error);
}
if (!$statement->execute()) {
throw new FuzDatabaseException($statement->error);
}
}
}
$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
$foo->updateBar();
} catch (FuzDatabaseException $e)
$msg = $e->getMessage();
// Now send warning emails, write log
}
It's a been a while since asked, and I haven't tested this on older browsers but it seems to me a much simpler answer is
$("#selectID").val([]);
.val() works for select as well http://api.jquery.com/val/
I faced the same problem when connecting to EC2, the issue was with Security Group, I solved by adding the allowed IPs at port 5432
This is the way to add more file extentions, in the example given by Roy M J in the top of this page.
var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J
In this example I have added more contains.
If you don't like split()
and you don't like matrix()
(with its dangling NAs), there's this:
chunk <- function(x, n) (mapply(function(a, b) (x[a:b]), seq.int(from=1, to=length(x), by=n), pmin(seq.int(from=1, to=length(x), by=n)+(n-1), length(x)), SIMPLIFY=FALSE))
Like split()
, it returns a list, but it doesn't waste time or space with labels, so it may be more performant.
Correct final syntax for [Mr. C]s answer.
With the release of VS2017RC and its C#7 support it works this way:
switch(message)
{
case string a when a.Contains("test2"): return "no";
case string b when b.Contains("test"): return "yes";
}
You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.
What about a simple write.table()
?
text = c("Hello", "World")
write.table(text, file = "output.txt", col.names = F, row.names = F, quote = F)
The parameters col.names = FALSE
and row.names = FALSE
make sure to exclude the row and column names in the txt, and the parameter quote = FALSE
excludes those quotation marks at the beginning and end of each line in the txt.
To read the data back in, you can use text = readLines("output.txt")
.
Below worked for me.
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
This code will work for python 3 and above
file=open("filename.txt")
f=file.readlines() #reads all lines from the file
EOF=-1 #represents end of file
temp=0
for k in range(len(f)-1,-1,-1):
if temp==0:
if f[k]=="\n":
EOF=k
else:
temp+=1
print("Given file has",EOF,"lines")
file.close()
Bill Horst's - Converting SQL to LINQ is a very good resource for this task (as well as LINQPad).
LINQ Tools has a decent list of tools as well but I do not believe there is anything else out there that can do what Linqer did.
Generally speaking, LINQ is a higher-level querying language than SQL which can cause translation loss when trying to convert SQL to LINQ. For one, LINQ emits shaped results and SQL flat result sets. The issue here is that an automatic translation from SQL to LINQ will often have to perform more transliteration than translation - generating examples of how NOT to write LINQ queries. For this reason, there are few (if any) tools that will be able to reliably convert SQL to LINQ. Analogous to learning C# 4 by first converting VB6 to C# 4 and then studying the resulting conversion.
or you can set pointer-events:none
to your a
element and pointer-event:all
to your a:before
element, and then add hover CSS to a element
a{
pointer-events:none;
}
a:before{
pointer-events:all
}
a:hover:before{
background:blue;
}
It doesn't work in IE5, but that's not a big issue.
However, cacheing headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.
This is the shortest way I've found (needs jQuery1.6+)
HTML:
<input type="checkbox" id="checkAll"/>
JS:
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
I'm using .prop as .attr doesn't work for checkboxes in jQuery 1.6+ unless you've explicitly added a checked attribute to your input tag.
Example-
$("#checkAll").change(function () {_x000D_
$("input:checkbox").prop('checked', $(this).prop("checked"));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form action="#">_x000D_
<p><label><input type="checkbox" id="checkAll"/> Check all</label></p>_x000D_
_x000D_
<fieldset>_x000D_
<legend>Loads of checkboxes</legend>_x000D_
<p><label><input type="checkbox" /> Option 1</label></p>_x000D_
<p><label><input type="checkbox" /> Option 2</label></p>_x000D_
<p><label><input type="checkbox" /> Option 3</label></p>_x000D_
<p><label><input type="checkbox" /> Option 4</label></p>_x000D_
</fieldset>_x000D_
</form>
_x000D_
As of SQL Server 2016 you have
DROP TABLE IF EXISTS [foo];
<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
<br />
<a href="/hello.html">go to with html</a>
Try this yourself and find that they are not exactly the same.
$_SERVER['DOCUMENT_ROOT']
renders an actual file path (on my computer running as it's own server, C:/wamp/www/
HTML's /
renders the root of the server url, in my case, localhost/
But C:/wamp/www/hello.html
and localhost/hello.html
are in fact the same file
The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.
WITH PivotCTE AS
(
select * from mytransactions
pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
numericmonth,
chardate,
SUM(totalamount) AS totalamount,
SUM(ISNULL(Australia, 0)) AS Australia,
SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate
The ISNULL
is to stop a NULL
value from nullifying the sum (because NULL
+ any value = NULL
)
One more to thing to think about when daemonizing in python:
If your are using python logging and you want to continue using it after daemonizing, make sure to call close()
on the handlers (particularly the file handlers).
If you don't do this the handler can still think it has files open, and your messages will simply disappear - in other words make sure the logger knows its files are closed!
This assumes when you daemonise you are closing ALL the open file descriptors indiscriminatingly - instead you could try closing all but the log files (but it's usually simpler to close all then reopen the ones you want).
Your condition is wrong. myChar != 'n' || myChar != 'N'
will always be true.
Use myChar != 'n' && myChar != 'N'
instead
You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.
You can have a look at here for more information.
Firebase is designed for real-time updates. It easily integrates with angular. Both are NoSQL databases. MongoDB can also do this with Angular through Socket.io integration. Meteor.js also makes use of MongoDB with an open socket connection for real-time updates.
MongoDB can be run locally, or hosted on many different cloud based providers. Firebase, in my opinion is great for smaller apps, very quick to get up and running. MongoDB is ideal for more robust larger apps, real-time integration is possible but it takes a bit more work.
I think my answer to my own question here is the simplest solution to what you are trying to do:
Select the cell where the first line of text from the file should be.
Use the Data
/Get External Data
/From File
dialog to select the text file to import.
Format the imported text as required.
In the Import Data
dialog that opens, click on Properties...
Uncheck the Prompt for file name on refresh
box.
Whenever the external file changes, click the Data
/Get External Data
/Refresh All
button.
Note: in your case, you should probably want to skip step #5.
go to dosbox installation directory (on my machine that is C:\Program Files (x86)\DOSBox-0.74 ) as you see the version number is part of the installation directory name.
run "DOSBox 0.74 Options.bat"
the script starts notepad with configuration file: here change
windowresolution=1600x800
output=ddraw
(the resolution can't be changed if output=surface - that's the default).
A variant of Thomas' solution: CSS element>element selectors can be handy here:
CSS
.paddedAnchor{
position: relative;
}
.paddedAnchor > a{
position: absolute;
top: -100px;
}
HTML
<a href="#myAnchor">Click Me!</a>
<span class="paddedAnchor"><a name="myAnchor"></a></span>
A click on the link will move the scroll position to 100px above wherever the element with a class of paddedAnchor
is positioned.
Supported in non-IE browsers, and in IE from version 9. For support on IE 7 and 8, a <!DOCTYPE>
must be declared.
It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.
MyClass myClass = new MyClass();
once you've added that line you can then call your method
myClass.myMethod();
Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.
You can use --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') to include entire folder of Jars. So, spark-submit -- class com.yourClass \ --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') \ ...
Without knowing all the information... You could bind a reset trigger to your model or controller:
this.bind("reset", this.updateView);
and when you want to reset the views, trigger a reset.
For your callback, do something like:
updateView: function() {
view.remove();
view.render();
};
This variable can be set using value="${val1}"
inside c:set
if you have used jquery in your system.
Try this:
npm install -g gulp-sass
or
npm install --save gulp-sass
When you click on compose email in Gmail notice that the url changes from https://mail.google.com/mail/u/0/#inbox to https://mail.google.com/mail/u/0/#inbox?compose=new. Now when you enter say a email id [email protected] , the value for compose changes now the url became https://mail.google.com/mail/u/0/#inbox?compose=150b0f7ffb682642.
So this is working fine with my html hyperlink until the account is signed in, but if the account is not signed in it would take me the login page and when I enter the credentials somehow this compose value is lost and this does not work.
If you like to avoid both changes()=0
and INSERT OR IGNORE
even if you cannot afford deleting the row - You can use this logic;
First, insert (if not exists) and then update by filtering with the unique key.
-- Table structure
CREATE TABLE players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR (255) NOT NULL
UNIQUE,
age INTEGER NOT NULL
);
-- Insert if NOT exists
INSERT INTO players (user_name, age)
SELECT 'johnny', 20
WHERE NOT EXISTS (SELECT 1 FROM players WHERE user_name='johnny' AND age=20);
-- Update (will affect row, only if found)
-- no point to update user_name to 'johnny' since it's unique, and we filter by it as well
UPDATE players
SET age=20
WHERE user_name='johnny';
Notice: I haven't tested it to see the which triggers are being called, but I assume the following:
in this way you can have a single SQL command
-- Table structure
CREATE TABLE players (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_name VARCHAR (255) NOT NULL
UNIQUE,
age INTEGER NOT NULL
);
-- Single command to insert or update
INSERT OR REPLACE INTO players
(id, user_name, age)
VALUES ((SELECT id from players WHERE user_name='johnny' AND age=20),
'johnny',
20);
Edit: added option 2.
Right click on project - >BuildPath - >Configure BuildPath - >Libraries tab - >
Double click on JRE SYSTEM LIBRARY - >Then select alternate JRE
fireTableStructureChanged();
will default the resize behavior ! If this method is called somewhere in your code AFTER you did set the column resize properties all your settings will be reset. This side effect can happen indirectly. F.e. as a consequence of the linked data model being changed in a way this method is called, after properties are set.
If all other solutions did not work for your device try this guide how to make a truly universal adb and fastboot driver out of Google USB driver. The resulting driver works for adb
, recovery
and fastboot
modes in all versions of Windows.
I solved that problem.
I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>
) and its states (state pattern, forward declaration).
The solution is as follows:
In the *.cpp
file, you must include the Header file that you forward, i.e.
ifndef STATE_H_
#define STATE_H_
#include <stdlib.h>
#include "Frame.h"
template <class T>
class LinkFrame;
using namespace std;
template <class T>
class State {
protected:
LinkFrame<int> *myFrame;
}
Its cpp:
#include "State.h"
#include "Frame.h"
#include "LinkFrame.h"
template <class T>
bool State<T>::replace(Frame<T> *f){
And... another class.
As Umesh Patil answer have comment say that there is problem. I try to edit answer and get reject. And get suggest to post new answer. This code should solve problem they have (Shashi Roy, Gaven, John Higgins).
<html>
<head>
<script type="text/javascript">
function CheckColors(val){
var element=document.getElementById('othercolor');
if(val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</head>
<body>
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="othercolor" id="othercolor" style='display:none;'/>
</body>
</html>
You can use get methods:
var fullDate = new Date();_x000D_
console.log(fullDate);_x000D_
var twoDigitMonth = fullDate.getMonth() + "";_x000D_
if (twoDigitMonth.length == 1)_x000D_
twoDigitMonth = "0" + twoDigitMonth;_x000D_
var twoDigitDate = fullDate.getDate() + "";_x000D_
if (twoDigitDate.length == 1)_x000D_
twoDigitDate = "0" + twoDigitDate;_x000D_
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear(); console.log(currentDate);
_x000D_
After deserializing the JSON, you have a python object. Use the regular object methods.
In this case you have a list made of dictionaries:
json_object[0].items()
json_object[0]["title"]
etc.
CTRL-C generally sends a SIGINT signal to the process so you can simply do:
kill -INT <processID>
from the command line (or a script), to affect the specific processID
.
I say "generally" because, as with most of UNIX, this is near infinitely configurable. If you execute stty -a
, you can see which key sequence is tied to the intr
signal. This will probably be CTRL-C but that key sequence may be mapped to something else entirely.
The following script shows this in action (albeit with TERM
rather than INT
since sleep
doesn't react to INT
in my environment):
#!/usr/bin/env bash
sleep 3600 &
pid=$!
sleep 5
echo ===
echo PID is $pid, before kill:
ps -ef | grep -E "PPID|$pid" | sed 's/^/ /'
echo ===
( kill -TERM $pid ) 2>&1
sleep 5
echo ===
echo PID is $pid, after kill:
ps -ef | grep -E "PPID|$pid" | sed 's/^/ /'
echo ===
It basically starts an hour-log sleep
process and grabs its process ID. It then outputs the relevant process details before killing the process.
After a small wait, it then checks the process table to see if the process has gone. As you can see from the output of the script, it is indeed gone:
===
PID is 28380, before kill:
UID PID PPID TTY STIME COMMAND
pax 28380 24652 tty42 09:26:49 /bin/sleep
===
./qq.sh: line 12: 28380 Terminated sleep 3600
===
PID is 28380, after kill:
UID PID PPID TTY STIME COMMAND
===
You can directly apply slice()
to the variable. StackBlitz Demo
<li *ngFor="let item of list.slice(0, 10);">
{{item.text}}
</li>
URL url = new File("src/main/java/ua/adeptius/goit/sample.fxml").toURI().toURL();
Parent root = FXMLLoader.load(url);
That is helped for me because
getClass.getResource("path")
always returns me null;
Use <f:convertDateTime>
. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat
.
<h:outputText value="#{someBean.dateField}" >
<f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>
I had this problem because I changed the name of the class in a model, and it did not match the name of the file.
"Model class names use CamelCase. These are singular, and will map automatically to the plural database table name.
Model files go in app/models/#{singular_model_name}.rb."
https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e#model
Just write
ProcessStartInfo psi= new ProcessStartInfo("cmd.exe");
......
psi.CreateNoWindow = true;
Try using the :input
selector, along with a parent selector:
$("#parent-selector :input").attr("disabled", true);
Please use kafka-topics.sh --list --bootstrap-server localhost:9092
to list down all topics
You can use Func which encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.
void Method()
{
Func<string,string> inlineFunction = source =>
{
// add your functionality here
return source ;
};
// call the inline function
inlineFunction("prefix");
}
Another approach can be manually using batch rename option
Right click on the file -> File Custom Commands -> Batch Rename and you can replace h. with half.
This will work for linux based gui using WinSCP etc
Inline content leaves space at the bottom for characters that descend (j, y, q):
https://developer.mozilla.org/en-US/docs/Images,_Tables,_and_Mysterious_Gaps
There are a couple fixes:
Use display: block;
<img style="display:block;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
or use vertical-align: bottom;
<img style="vertical-align: bottom;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
The whole idea of a keytool is to sign your apk with a unique identifier indicating the source of that apk. A keystore file (from what I understand) is used for debuging so your apk has the functionality of a keytool without signing your apk for production. So yes, for debugging purposes you should be able to sign multiple apk's with a single keystore. But understand that, upon pushing to production you'll need unique keytools as identifiers for each apk you create.
Sounds like you should stay with the defaults ;-)
Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.
See here how to configure...
Tomcat 9: https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html
Tomcat 8: https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html
Tomcat 7: https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html
Tomcat 6: https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html
I would go with unset because it might give the garbage collector a better hint so that the memory can be available again sooner. Be careful that any things the object points to either have other references or get unset first or you really will have to wait on the garbage collector since there would then be no handles to them.
It was my own stupidity:
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
Putting this inside onCreate()
method fixed my problem.
You can use the utility method in Collections
class
public static <T extends Comparable<? super T>> void sort(List<T> list)
or
public static <T> void sort(List<T> list,Comparator<? super T> c)
Refer to Comparable
and Comparator
interfaces for more flexibility on sorting the object.
This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.
ViewModel looks like this:
public class MyViewModel
{
public List<Person> Persons{get;set;}
}
View(with BeginForm of course):
@model MyViewModel
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
@Html.HiddenFor(m => m.Persons[i].PersonId)
@Html.EditorFor(m => m.Persons[i].FirstName)
@Html.EditorFor(m => m.Persons[i].LastName)
}
Action:
[HttpPost]public ViewResult(MyViewModel vm)
{
...
Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.
Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
if(i != 4)//conditionally hide 5th item,
{ //but BUG occurs on postback, all items after 5th will not be bound to the the list
@Html.HiddenFor(m => m.Persons[i].PersonId)
@Html.EditorFor(m => m.Persons[i].FirstName)
@Html.EditorFor(m => m.Persons[i].LastName)
}
}
They're essentially the same... They both use swig for templating, they both use karma and mocha for tests, passport integration, nodemon, etc.
Why so similar? Mean.js is a fork of Mean.io and both initiatives were started by the same guy... Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about the reasons here.
Now... main (or little) differences you can see right now are:
SCAFFOLDING AND BOILERPLATE GENERATION
Mean.io uses a custom cli tool named 'mean'
Mean.js uses Yeoman Generators
MODULARITY
Mean.io uses a more self-contained node packages modularity with client and server files inside the modules.
Mean.js uses modules just in the front-end (for angular), and connects them with Express. Although they were working on vertical modules as well...
BUILD SYSTEM
Mean.io has recently moved to gulp
Mean.js uses grunt
DEPLOYMENT
Both have Dockerfiles in their respective repos, and Mean.io has one-click install on Google Compute Engine, while Mean.js can also be deployed with one-click install on Digital Ocean.
DOCUMENTATION
Mean.io has ok docs
Mean.js has AWESOME docs
COMMUNITY
Mean.io has a bigger community since it was the original boilerplate
Mean.js has less momentum but steady growth
On a personal level, I like more the philosophy and openness of MeanJS and more the traction and modules/packages approach of MeanIO. Both are nice, and you'll end probably modifying them, so you can't really go wrong picking one or the other. Just take them as starting point and as a learning exercise.
MEAN is a generic way (coined by Valeri Karpov) to describe a boilerplate/framework that takes "Mongo + Express + Angular + Node" as the base of the stack. You can find frameworks with this stack that use other denomination, some of them really good for RAD (Rapid Application Development) and building SPAs. Eg:
You also have Hackathon Starter. It doesn't have A of MEAN (it is 'MEN'), but it rocks..
Have fun!
If you would like to perform it dynamically try this:
using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;
using NUnit.Framework;
namespace ExampleConsoleApplication
{
enum DebugLevel : int
{
Fatal_Msgs = 0 ,
Fatal_Error_Msgs = 1 ,
Fatal_Error_Warn_Msgs = 2 ,
Fatal_Error_Warn_Info_Msgs = 3 ,
Fatal_Error_Warn_Info_Debug_Msgs = 4
}
class TestClass
{
private static readonly ILog logger = LogManager.GetLogger(typeof(TestClass));
static void Main ( string[] args )
{
TestClass objTestClass = new TestClass ();
Console.WriteLine ( " START " );
int shouldLog = 4; //CHANGE THIS FROM 0 TO 4 integer to check the functionality of the example
//0 -- prints only FATAL messages
//1 -- prints FATAL and ERROR messages
//2 -- prints FATAL , ERROR and WARN messages
//3 -- prints FATAL , ERROR , WARN and INFO messages
//4 -- prints FATAL , ERROR , WARN , INFO and DEBUG messages
string srtLogLevel = String.Empty;
switch (shouldLog)
{
case (int)DebugLevel.Fatal_Msgs :
srtLogLevel = "FATAL";
break;
case (int)DebugLevel.Fatal_Error_Msgs:
srtLogLevel = "ERROR";
break;
case (int)DebugLevel.Fatal_Error_Warn_Msgs :
srtLogLevel = "WARN";
break;
case (int)DebugLevel.Fatal_Error_Warn_Info_Msgs :
srtLogLevel = "INFO";
break;
case (int)DebugLevel.Fatal_Error_Warn_Info_Debug_Msgs :
srtLogLevel = "DEBUG" ;
break ;
default:
srtLogLevel = "FATAL";
break;
}
objTestClass.SetLogingLevel ( srtLogLevel );
objTestClass.LogSomething ();
Console.WriteLine ( " END HIT A KEY TO EXIT " );
Console.ReadLine ();
} //eof method
/// <summary>
/// Activates debug level
/// </summary>
/// <sourceurl>http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx</sourceurl>
private void SetLogingLevel ( string strLogLevel )
{
string strChecker = "WARN_INFO_DEBUG_ERROR_FATAL" ;
if (String.IsNullOrEmpty ( strLogLevel ) == true || strChecker.Contains ( strLogLevel ) == false)
throw new Exception ( " The strLogLevel should be set to WARN , INFO , DEBUG ," );
log4net.Repository.ILoggerRepository[] repositories = log4net.LogManager.GetAllRepositories ();
//Configure all loggers to be at the debug level.
foreach (log4net.Repository.ILoggerRepository repository in repositories)
{
repository.Threshold = repository.LevelMap[ strLogLevel ];
log4net.Repository.Hierarchy.Hierarchy hier = (log4net.Repository.Hierarchy.Hierarchy)repository;
log4net.Core.ILogger[] loggers = hier.GetCurrentLoggers ();
foreach (log4net.Core.ILogger logger in loggers)
{
( (log4net.Repository.Hierarchy.Logger)logger ).Level = hier.LevelMap[ strLogLevel ];
}
}
//Configure the root logger.
log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository ();
log4net.Repository.Hierarchy.Logger rootLogger = h.Root;
rootLogger.Level = h.LevelMap[ strLogLevel ];
}
private void LogSomething ()
{
#region LoggerUsage
DOMConfigurator.Configure (); //tis configures the logger
logger.Debug ( "Here is a debug log." );
logger.Info ( "... and an Info log." );
logger.Warn ( "... and a warning." );
logger.Error ( "... and an error." );
logger.Fatal ( "... and a fatal error." );
#endregion LoggerUsage
}
} //eof class
} //eof namespace
The app config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="LogTest2.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header] \r\n" />
<param name="Footer" value="[Footer] \r\n" />
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=ysg;initial catalog=DBGA_DEV;integrated security=true;persist security info=True;" />
<commandText value="INSERT INTO [DBGA_DEV].[ga].[tb_Data_Log] ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%thread" />
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout" value="%level" />
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%logger" />
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout" value="%messag2e" />
</parameter>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="ColoredConsoleAppender" />
</root>
</log4net>
</configuration>
The references in the csproj file:
<Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\Log4Net\log4net-1.2.10\bin\net\2.0\release\log4net.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" />
<div id="invocieContainer">
<div class="row">
...Your html Page content here....
</div>
</div>
<script src="/Scripts/printThis.js"></script>
<script>
$(document).on("click", "#btnPrint", function(e) {
e.preventDefault();
e.stopPropagation();
$("#invocieContainer").printThis({
debug: false, // show the iframe for debugging
importCSS: true, // import page CSS
importStyle: true, // import style tags
printContainer: true, // grab outer container as well as the contents of the selector
loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
pageTitle: "", // add title to print page
removeInline: false, // remove all inline styles from print elements
printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
header: null, // prefix to html
formValues: true // preserve input/form values
});
});
</script>
For printThis.js souce code, copy and pase below URL in new tab https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js
Try: moment({ // Options here }).format('HHmm')
. That should give you the time in a 24 hour format.
Read the data:
foo <- read.table(text="1 349
1 393
1 392
4 459
3 49
3 32
2 94")
And sort:
foo[order(foo$V1),]
This relies on the fact that order
keeps ties in their original order. See ?order
.
You need to turn on Show All Files
option on solution pane toolbar and include this file manually.
This is my solution for something similar to this problem:
System.Windows.Forms.WebBrowser www;
void VerificarWebSites()
{
www = new System.Windows.Forms.WebBrowser();
www.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_login);
www.Navigate(new Uri("http://www.meusite.com.br"));
}
void www_DocumentCompleted_login(object sender, WebBrowserDocumentCompletedEventArgs e)
{
www.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_login);
www.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_logado);
www.Document.Forms[0].All["tbx_login"].SetAttribute("value", "Gostoso");
www.Document.Forms[0].All["tbx_senha"].SetAttribute("value", "abcdef");
www.Document.GetElementById("btn_login").Focus();
www.Document.GetElementById("btn_login").InvokeMember("click");
}
void www_DocumentCompleted_logado(object sender, WebBrowserDocumentCompletedEventArgs e)
{
System.IO.StreamWriter sw = new StreamWriter("c:\\saida_teste.txt");
sw.Write(www.DocumentText);
sw.Close();
MessageBox.Show(e.Url.AbsolutePath);
}
You can declare SqlConnection
and SqlCommand
instances at global level so that you can use it through out the class. Connection string is in Web.Config
.
SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();
Now you can use the below method to pass values to Stored Procedure and get the DataSet
.
public DataSet GetDataSet(string paramValue)
{
sqlcomm.Connection = sqlConn;
using (sqlConn)
{
try
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
// This will be your input parameter and its value
sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);
// You can retrieve values of `output` variables
var returnParam = new SqlParameter
{
ParameterName = "@Error",
Direction = ParameterDirection.Output,
Size = 1000
};
sqlcomm.Parameters.Add(returnParam);
// Name of stored procedure
sqlcomm.CommandText = "StoredProcedureName";
da.SelectCommand = sqlcomm;
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
}
}
catch (SQLException ex)
{
Console.WriteLine("SQL Error: " + ex.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
return new DataSet();
}
The following is the sample of connection string in config file
<connectionStrings>
<add name="SqlConnector"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>
First thing first, button()
is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:
$("#filter").click(function(){
alert('clicked!');
});
Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func)
which execute the callback once the DOM is ready.
Usage:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
So even if the order is this it will work:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
<input type="button" id="filter" name="filter" value="Filter" />
I just think the whole example would be useful. This is the example for this problem.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Collections.Generic;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GoogleSearchResults g1 = new GoogleSearchResults();
const string json = @"{""responseData"": {""results"":[{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.cheese.com/"",""url"":""http://www.cheese.com/"",""visibleUrl"":""www.cheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:bkg1gwNt8u4J:www.cheese.com"",""title"":""\u003cb\u003eCHEESE\u003c/b\u003e.COM - All about \u003cb\u003echeese\u003c/b\u003e!."",""titleNoFormatting"":""CHEESE.COM - All about cheese!."",""content"":""\u003cb\u003eCheese\u003c/b\u003e - everything you want to know about it. Search \u003cb\u003echeese\u003c/b\u003e by name, by types of milk, by textures and by countries.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://en.wikipedia.org/wiki/Cheese"",""url"":""http://en.wikipedia.org/wiki/Cheese"",""visibleUrl"":""en.wikipedia.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:n9icdgMlCXIJ:en.wikipedia.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e - Wikipedia, the free encyclopedia"",""titleNoFormatting"":""Cheese - Wikipedia, the free encyclopedia"",""content"":""\u003cb\u003eCheese\u003c/b\u003e is a food consisting of proteins and fat from milk, usually the milk of cows, buffalo, goats, or sheep. It is produced by coagulation of the milk \u003cb\u003e...\u003c/b\u003e""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.ilovecheese.com/"",""url"":""http://www.ilovecheese.com/"",""visibleUrl"":""www.ilovecheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:GBhRR8ytMhQJ:www.ilovecheese.com"",""title"":""I Love \u003cb\u003eCheese\u003c/b\u003e!, Homepage"",""titleNoFormatting"":""I Love Cheese!, Homepage"",""content"":""The American Dairy Association\u0026#39;s official site includes recipes and information on nutrition and storage of \u003cb\u003echeese\u003c/b\u003e.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.gnome.org/projects/cheese/"",""url"":""http://www.gnome.org/projects/cheese/"",""visibleUrl"":""www.gnome.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:jvfWnVcSFeQJ:www.gnome.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e"",""titleNoFormatting"":""Cheese"",""content"":""\u003cb\u003eCheese\u003c/b\u003e uses your webcam to take photos and videos, applies fancy special effects and lets you share the fun with others. It was written as part of Google\u0026#39;s \u003cb\u003e...\u003c/b\u003e""}],""cursor"":{""pages"":[{""start"":""0"",""label"":1},{""start"":""4"",""label"":2},{""start"":""8"",""label"":3},{""start"":""12"",""label"":4},{""start"":""16"",""label"":5},{""start"":""20"",""label"":6},{""start"":""24"",""label"":7},{""start"":""28"",""label"":8}],""estimatedResultCount"":""14400000"",""currentPageIndex"":0,""moreResultsUrl"":""http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den-GB\u0026q\u003dcheese""}}, ""responseDetails"": null, ""responseStatus"": 200}";
g1 = JSONHelper.Deserialise<GoogleSearchResults>(json);
foreach (Pages x in g1.responseData.cursor.pages)
{
// Anything you want to get
Response.Write(x.label);
}
}
}
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
}
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
[DataMember]
public string responseStatus { get; set; }
}
public class ResponseData
{
[DataMember]
public Cursor cursor { get; set; }
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Cursor
{
[DataMember]
public IEnumerable<Pages> pages { get; set; }
}
[DataContract]
public class Pages
{
[DataMember]
public string start { get; set; }
[DataMember]
public string label { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Based SQL Server CSV Import
1) The CSV file data may have
,
(comma) in between (Ex: description), so how can I make import handling these data?
Solution
If you're using ,
(comma) as a delimiter, then there is no way to differentiate between a comma as a field terminator and a comma in your data. I would use a different FIELDTERMINATOR
like ||
. Code would look like and this will handle comma and single slash perfectly.
2) If the client create the csv from excel then the data that have comma are enclosed within
" ... "
(double quotes) [as the below example] so how do the import can handle this?
Solution
If you're using BULK insert then there is no way to handle double quotes, data will be
inserted with double quotes into rows.
after inserting the data into table you could replace those double quotes with ''.
update table
set columnhavingdoublequotes = replace(columnhavingdoublequotes,'"','')
3) How do we track if some rows have bad data, which import skips? (does import skips rows that are not importable)?
Solution
To handle rows which aren't loaded into table because of invalid data or format, could be handle using ERRORFILE property, specify the error file name, it will write the rows having error to error file. code should look like.
BULK INSERT SchoolsTemp
FROM 'C:\CSVData\Schools.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'C:\CSVDATA\SchoolsErrorRows.csv',
TABLOCK
)
After you created a Bridging header, go to Build Setting => Search for "Objective-C Bridging Header".
Just below you will find the ""Objective-C Generated Interface Header Name" file.
Import that file in your view controller.
Example: In my case: "Dauble-Swift.h"
In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\
I would like to improve answer from chris-b a little bit more.
See below for my code:
from threading import Thread, Lock
import threading
mutex = Lock()
def processData(data, thread_safe):
if thread_safe:
mutex.acquire()
try:
thread_id = threading.get_ident()
print('\nProcessing data:', data, "ThreadId:", thread_id)
finally:
if thread_safe:
mutex.release()
counter = 0
max_run = 100
thread_safe = False
while True:
some_data = counter
t = Thread(target=processData, args=(some_data, thread_safe))
t.start()
counter = counter + 1
if counter >= max_run:
break
In your first run if you set thread_safe = False
in while loop, mutex will not be used, and threads will step over each others in print method as below;
but, if you set thread_safe = True
and run it, you will see all the output comes perfectly fine;
hope this helps.
I'm using CSS Dig. It is made for chrome, but I think it is a great tool!
It should work with:
.modal:before{
opacity:0.001 !important;
}
Here is a solution I made using the above ideas that can be used for TextBoxFor and PasswordFor:
public static class HtmlHelperEx
{
public static MvcHtmlString TextBoxWithPlaceholderFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return htmlHelper.TextBoxFor(expression, htmlAttributes.AddAttribute("placeholder", metadata.Watermark));
}
public static MvcHtmlString PasswordWithPlaceholderFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return htmlHelper.PasswordFor(expression, htmlAttributes.AddAttribute("placeholder", metadata.Watermark));
}
}
public static class HtmlAttributesHelper
{
public static IDictionary<string, object> AddAttribute(this object htmlAttributes, string name, object value)
{
var dictionary = htmlAttributes == null ? new Dictionary<string, object>() : htmlAttributes.ToDictionary();
if (!String.IsNullOrWhiteSpace(name) && value != null && !String.IsNullOrWhiteSpace(value.ToString()))
dictionary.Add(name, value);
return dictionary;
}
public static IDictionary<string, object> ToDictionary(this object obj)
{
return TypeDescriptor.GetProperties(obj)
.Cast<PropertyDescriptor>()
.ToDictionary(property => property.Name, property => property.GetValue(obj));
}
}
Full Coding Structure
postgresql function
CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
item_head_list int[])
RETURNS TABLE(item_display_id integer)
LANGUAGE 'sql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
$BODY$;
Model
public class CampaignCreator
{
public int item_display_id { get; set; }
public List<int> pitem_head_id { get; set; }
}
.NET CORE function
DynamicParameters _parameter = new DynamicParameters();
_parameter.Add("@item_head_list",obj.pitem_head_id);
string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);
I had a similar question, but wasn't satisfied with the answer (or any I could find on the net), so I tried it in practice and here is what I got:
init
does not cause layoutSubviews
to
be called (duh) addSubview:
causes
layoutSubviews
to be called on the
view being added, the view it’s being
added to (target view), and all the
subviews of the targetsetFrame
intelligently calls layoutSubviews
on
the view having its frame set only
if the size parameter of the frame is
differentlayoutSubviews
to be called on
the scrollView, and its superviewlayoutSubview
on the parent view (the
responding viewControllers primary
view)layoutSubviews
on its superviewMy results - http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/
Using AWS Management Console:
You can use pure Python to do it:
import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'
You could try with OpenNew and then with Write but that's a bit strange use of that class. More info on MSDN.
In some environments, NSLog() will be unresponsive. But there are other ways to get output...
NSString* url = @"someurlstring";
printf("%s", [url UTF8String]);
By using printf
with the appropriate parameters, we can display things this way. This is the only way I have found to work on online Objective-C sandbox environments.
Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");
try this instead
Note:This is using Ajax Toolkit
First add Ajax Script Manager and use the below Code to apply filter to the textbox
Provide the Namespace at the beginning of the asp.net page
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:TextBox ID="TxtBox" runat="server"></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" Enabled="True" TargetControlID="TxtBox" FilterType="Numbers" FilterMode="ValidChars">
</cc1:FilteredTextBoxExtender>
You can read about the keyword unsigned in the C++ Reference.
There are two different types in this matter, signed and un-signed. The default for integers is signed which means that they can have negative values.
On a 32-bit system an integer is 32 Bit which means it can contain a value of ~4 billion.
And when it is signed, this means you need to split it, leaving -2 billion to +2 billion.
When it is unsigned however the value cannot contain any negative numbers, so for integers this would mean 0 to +4 billion.
There is a bit more informationa bout this on Wikipedia.
install these ==>> pip install -U scikit-learn scipy matplotlib if still getting the same error then , make sure that your imoprted statment should be correct. i made the mistike while writing ensemble so ,(check spelling) its should be >>> from sklearn.ensemble import RandomForestClassifier
This problem had been bugging me for years the only workaround for me was to ask our networks team to make exceptions on our firewall so that certain URL requests didn't need to be authenticated on the proxy which is not ideal.
Recently I upgraded the project to .NET 4 from 3.5 and the code just started working using the default credentials for the proxy, no hardcoding of credentials etc.
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
public static List<HtmlNode> GetTagsWithClass(string html,List<string> @class)
{
// LoadHtml(html);
var result = htmlDocument.DocumentNode.Descendants()
.Where(x =>x.Attributes.Contains("class") && @class.Contains(x.Attributes["class"].Value)).ToList();
return result;
}
Current thinking seems to be to "tolerate" nulls, that is, to allow them in general, although some operations are less tolerant and may end up throwing NPE. See the discussion of nulls on the Lambda Libraries expert group mailing list, specifically this message. Consensus around option #3 subsequently emerged (with a notable objection from Doug Lea). So yes, the OP's concern about pipelines blowing up with NPE is valid.
It's not for nothing that Tony Hoare referred to nulls as the "Billion Dollar Mistake." Dealing with nulls is a real pain. Even with classic collections (without considering lambdas or streams) nulls are problematic. As fge mentioned in a comment, some collections allow nulls and others do not. With collections that allow nulls, this introduces ambiguities into the API. For example, with Map.get(), a null return indicates either that the key is present and its value is null, or that the key is absent. One has to do extra work to disambiguate these cases.
The usual use for null is to denote the absence of a value. The approach for dealing with this proposed for Java SE 8 is to introduce a new java.util.Optional
type, which encapsulates the presence/absence of a value, along with behaviors of supplying a default value, or throwing an exception, or calling a function, etc. if the value is absent. Optional
is used only by new APIs, though, everything else in the system still has to put up with the possibility of nulls.
My advice is to avoid actual null references to the greatest extent possible. It's hard to see from the example given how there could be a "null" Otter. But if one were necessary, the OP's suggestions of filtering out null values, or mapping them to a sentinel object (the Null Object Pattern) are fine approaches.
First some code, then the explanaition. The official docs describing this are here.
import { trigger, transition, animate, style } from '@angular/animations'
@Component({
...
animations: [
trigger('slideInOut', [
transition(':enter', [
style({transform: 'translateY(-100%)'}),
animate('200ms ease-in', style({transform: 'translateY(0%)'}))
]),
transition(':leave', [
animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
])
])
]
})
In your template:
<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>
I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.
The animations part in human language:
->then animate the translateY value until we are at 0%, where the element would naturally be.
When the element is removed, animate the translateY value (currently 0), to -100% (off screen).
The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.
Hope this helps!
Its also possible to use dynamic SQL and execute it with the exec command:
declare @sql nvarchar(200), @count int
set @count = 10
set @sql = N'select top ' + cast(@count as nvarchar(4)) + ' * from table'
exec (@sql)
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
Netscape ANSI encoded files use 0D 0D 0A for their line breaks.
You can probably safely ignore the error messages in this case. Failing to add a comment to the public schema and installing plpgsql (which should already be installed) aren't going to cause any real problems.
However, if you want to do a complete re-install you'll need a user with appropriate permissions. That shouldn't be the user your application routinely runs as of course.
BeRecursive's answer is the one I used, so that we could standardize on Json.Net (we have MVC5 and WebApi 5 -- WebApi 5 already uses Json.Net), but I found an issue. When you have parameters in your route to which you're POSTing, MVC tries to call the model binder for the URI values, and this code will attempt to bind the posted JSON to those values.
Example:
[HttpPost]
[Route("Customer/{customerId:int}/Vehicle/{vehicleId:int}/Policy/Create"]
public async Task<JsonNetResult> Create(int customerId, int vehicleId, PolicyRequest policyRequest)
The BindModel
function gets called three times, bombing on the first, as it tries to bind the JSON to customerId
with the error: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.
I added this block of code to the top of BindModel
:
if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) {
return base.BindModel(controllerContext, bindingContext);
}
The ValueProvider, fortunately, has route values figured out by the time it gets to this method.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Button is Working",Toast.LENGTH_LONG).show();
}
}
Use FB static method getCurrentProfile() of Profile class to retrieve those info.
Profile profile = Profile.getCurrentProfile();
String firstName = profile.getFirstName());
System.out.println(profile.getProfilePictureUri(20,20));
System.out.println(profile.getLinkUri());
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
You can use in-place operator new. This would be a bit horrible, and I'd recommend keeping in a factory.
Car* createCars(unsigned number)
{
if (number == 0 )
return 0;
Car* cars = reinterpret_cast<Car*>(new char[sizeof(Car)* number]);
for(unsigned carId = 0;
carId != number;
++carId)
{
new(cars+carId) Car(carId);
}
return cars;
}
And define a corresponding destroy so as to match the new used in this.
Another way to do that is comment everything in Initial Class,between Up and Down Methods.Then run update-database, after running seed method was successful so run update-database again.It maybe helpful to some friends.
If you like to have the timestamp without the timezone but local timezone do
git log -1 --format=%cd --date=local
Which gives this depending on your location
Mon Sep 28 12:07:37 2015
Yes, if bar is not None
is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar:
will execute if bar
is any kind of zero or empty container, or False
.
Many people do use not bar
where they really do mean bar is not None
.
Although it is too late to answer this question. Here are my answer on the same.
If you are using CodeIgniter then you can use inbuilt methods defined in query_builder class.
$this->db->insert_batch()
Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:
$data = array(
array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
),
array(
'title' => 'Another title',
'name' => 'Another Name',
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
The first parameter will contain the table name, the second is an associative array of values.
You can find more details about query_builder here
Let me describe my situation.
First, check the current config
$ nvm use --delete-prefix v10.7.0
$ npm config list
Then, I found the error config in output:
; project config /mnt/c/Users/paul/.npmrc
prefix = "/mnt/c/Users/paul/C:\\Program Files\\nodejs"
So, I deleted the C:\\Program Files\\nodejs
in /mnt/c/Users/paul/.npmrc.
First download and install Team Explorer plugin in your system and then go to the Source Control Explorer. In the navigation pane find the Workspace field and click on Workspaces option. After clicking on Workspaces option, you will see all the workspaces that are mapped. Click on the remove button and the remove the mapping for required workspaces.
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
In Snow Leopard and later Mac OS versions, it isn't enough to codesign the gdb
executable.
You have to follow this guide to make it work: http://www.opensource.apple.com/source/lldb/lldb-69/docs/code-signing.txt
The guide explains how to do it for lldb
, but the process is exactly the same for gdb
.
In addition to @obscur's answer, here is an example of how you can access both the key
and value
from the @View.
Pipe:
@Pipe({
name: 'keyValueFilter'
})
export class keyValueFilterPipe {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(function(key) {
let pair = {};
let k = 'key';
let v = 'value'
pair[k] = key;
pair[v] = value[key];
return pair;
});
}
}
View:
<li *ngFor="let u of myObject |
keyValueFilter">First Name: {{u.key}} <br> Last Name: {{u.value}}</li>
So if the object were to look like:
myObject = {
Daario: Naharis,
Victarion: Greyjoy,
Quentyn: Ball
}
The generated outcome would be:
First name: Daario
Last Name: Naharis
First name: Victarion
Last Name: Greyjoy
First name: Quentyn
Last Name: Ball
Try something like this:
int main()
{
printf("%x %x %x %x %x %x %x %x\n",
0xC0, 0xC0, 0x61, 0x62, 0x63, 0x31, 0x32, 0x33);
}
Which produces this:
$ ./foo
c0 c0 61 62 63 31 32 33
In the middle of the stack trace, lost in the "reflection" junk, you can find the root cause:
The specified datastore driver ("com.mysql.jdbc.Driver") was not found in the CLASSPATH. Please check your CLASSPATH specification, and the name of the driver.
Check for a static version of your page in /public and delete it if it's there. When Rails 3.x caches pages, it leaves a static version in your public folder and loads that when users hit your site. This will remain even after you clear your cache.
ARIA does not change functionality, it only changes the presented roles/properties to screen reader users. WebAIM’s WAVE toolbar identifies ARIA roles on the page.
Try putting the following class on your second button
.div-button
{
margin-left: 20px;
}
Edit:
If you want your first button to be spaced from the div as well as from the second button, then apply this class to your first button also.
add {3,5}
to your expression which means length between 3 to 5
/^([a-zA-Z0-9_-]){3,5}$/
Is there a way to limit a regex to 100 characters WITH regex?
Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:
If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,
\d{3}-\d{3}-\d{4}
will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.
Likewise, you can set upper or lower limits:
\d{5,10}
means "at least 5, but not more than 10 digits".
Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.
function getCaretPosition() {
var x = 0;
var y = 0;
var sel = window.getSelection();
if(sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
if(range.getClientRects()) {
range.collapse(true);
var rect = range.getClientRects()[0];
if(rect) {
y = rect.top;
x = rect.left;
}
}
}
return {
x: x,
y: y
};
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];
headerView.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
headerView.layer.borderColor=[UIColor blackColor].CGColor;
headerView.layer.borderWidth=1.0f;
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,100,20)];
headerLabel.textAlignment = NSTextAlignmentRight;
headerLabel.text = @"LeadCode ";
//headerLabel.textColor=[UIColor whiteColor];
headerLabel.backgroundColor = [UIColor clearColor];
[headerView addSubview:headerLabel];
UILabel *headerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];
headerLabel1.textAlignment = NSTextAlignmentRight;
headerLabel1.text = @"LeadName";
headerLabel.textColor=[UIColor whiteColor];
headerLabel1.backgroundColor = [UIColor clearColor];
[headerView addSubview:headerLabel1];
return headerView;
}
Unloading and reloading the problem project solved it for me.
You can also use
SELECT @curRow := ifnull(@curRow,0) + 1 Row, ...
to initialise the counter variable.
In your case don't need casting, you need call toString().
Integer i = 33;
String s = i.toString();
//or
s = String.valueOf(i);
//or
s = "" + i;
Casting. How does it work?
Given:
class A {}
class B extends A {}
(A)
|
(B)
B b = new B(); //no cast
A a = b; //upcast with no explicit cast
a = (A)b; //upcast with an explicit cast
b = (B)a; //downcast
A and B in the same inheritance tree and we can this:
a = new A();
b = (B)a; // again downcast. Compiles but fails later, at runtime: java.lang.ClassCastException
The compiler must allow things that might possibly work at runtime. However, if the compiler knows with 100% that the cast couldn't possibly work, compilation will fail.
Given:
class A {}
class B1 extends A {}
class B2 extends A {}
(A)
/ \
(B1) (B2)
B1 b1 = new B1();
B2 b2 = (B2)b1; // B1 can't ever be a B2
Error: Inconvertible types B1 and B2. The compiler knows with 100% that the cast couldn't possibly work. But you can cheat the compiler:
B2 b2 = (B2)(A)b1;
but anyway at runtime:
Exception in thread "main" java.lang.ClassCastException: B1 cannot be cast to B2
in your case:
(Object)
/ \
(Integer) (String)
Integer i = 33;
//String s = (String)i; - compiler error
String s = (String)(Object)i;
at runtime: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
This three steps are good to have and store in this post.
1) How to port native c code on android
3) http://mindtherobot.com/blog/452/android-beginners-ndk-setup-step-by-step/
...
) and keys method[ ...Array(N).keys() ].map( i => i+1);
Array(N).fill().map((_, i) => i+1);
Array.from(Array(N), (_, i) => i+1)
{ length: N }
hackArray.from({ length: N }, (_, i) => i+1)
All the forms above can produce arrays initialised to pretty much any desired values by changing i+1
to expression required (e.g. i*2
, -i
, 1+i*2
, i%2
and etc). If expression can be expressed by some function f
then the first form becomes simply
[ ...Array(N).keys() ].map(f)
Array.from({length: 5}, (v, k) => k+1);
// [1,2,3,4,5]
Since the array is initialized with undefined
on each position, the value of v
will be undefined
let demo= (N) => {_x000D_
console.log(_x000D_
[ ...Array(N).keys() ].map(( i) => i+1),_x000D_
Array(N).fill().map((_, i) => i+1) ,_x000D_
Array.from(Array(N), (_, i) => i+1),_x000D_
Array.from({ length: N }, (_, i) => i+1)_x000D_
)_x000D_
}_x000D_
_x000D_
demo(5)
_x000D_
f
i.e.[ ...Array(N).keys() ].map((i) => f(i))
or even simpler
[ ...Array(N).keys() ].map(f)
let demo= (N,f) => {_x000D_
console.log(_x000D_
[ ...Array(N).keys() ].map(f),_x000D_
Array(N).fill().map((_, i) => f(i)) ,_x000D_
Array.from(Array(N), (_, i) => f(i)),_x000D_
Array.from({ length: N }, (_, i) => f(i))_x000D_
)_x000D_
}_x000D_
_x000D_
demo(5, i=>2*i+1)
_x000D_
This one, using circular reference, works for me
//a test-object with circular reference :
var n1 = { id:0, text:"aaaaa", parent:undefined}
var n2 = { id:1, text:"zzzzz", parent:undefined }
var o = { arr:[n1,n2], parent:undefined }
n1.parent = n2.parent = o;
var obj = { a:1, b:2, o:o }
o.parent = obj;
function deepClone(o,output){
if(!output) output = {};
if(o.______clone) return o.______clone;
o.______clone = output.______clone = output;
for(var z in o){
var obj = o[z];
if(typeof(obj) == "object") output[z] = deepClone(obj)
else output[z] = obj;
}
return output;
}
console.log(deepClone(obj));
You need to make the extension as .php to run a php code BUT if you can't change the extension you could use Ajax to run the php externally and get the result
For eg:
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url:'php_File_with_php_code.php',
type:'GET',
data:"parameter=some_parameter",
success:function(data)
{
$("#thisdiv").html(data);
}
});
});
</script>
</head>
<body>
<div id="thisdiv"></div>
</body>
</html>
Here, the JQuery is loaded and as soon as the pages load, the ajax call a php file from where the data is taken, the data is then put in the div
Hope This Helps
$('.offer').click(function(){
if ($(this).find(':checkbox').is(':checked'))
{
$(this).find(':checkbox').attr('checked', false);
}else{
$(this).find(':checkbox').attr('checked', true);
}
});
Well there are lot of answeres already provided and lot are making sense too.
Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.
I came across similar situation today and here is very simple query I came up with...
declare
begin
execute immediate '
create table "TBL" ("ID" number not null)';
exception when others then
if SQLCODE = -955 then null; else raise; end if;
end;
/
955 is failure code.
This is simple, if exception come while running query it will be suppressed. and you can use same for SQL
or Oracle
.
When you starting application 'Run as administrator'.This way I avoided this error.
Try this in your forth column
=COUNTIF(B:B; ">" & B2) + 1
Replace B2 with B3 for next row and so on.
What this does is it counts how many records have more points then current one and then this adds current record position (+1 part).
The lazy-init="default"
setting on a bean only refers to what is set by the default-lazy-init
attribute of the enclosing beans element. The implicit default value of default-lazy-init
is false
.
If there is no lazy-init
attribute specified on a bean, it's always eagerly instantiated.
Using .NET 4.5 trying to perform form POST file upload. Tried most of the methods above but to no avail. Found the solution here https://www.c-sharpcorner.com/article/upload-any-file-using-http-post-multipart-form-data
But I am not not keen as I do not understand why we still need to deal with such low level programming in these common usages (should be handled nicely by framework)
Install a handler for SIGALRM
, then use alarm()
or ualarm()
before a regular blocking recv()
. If the alarm goes off, the recv()
will return an error with errno
set to EINTR
.
If you want an index, you can use std::find
in combination with std::distance
.
auto it = std::find(Names.begin(), Names.end(), old_name_);
if (it == Names.end())
{
// name not in vector
} else
{
auto index = std::distance(Names.begin(), it);
}
In version r82 of Three.js TextureLoader is the object to use for loading a texture.
Extract (test.js):
var scene = new THREE.Scene();
var ratio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,
0.1, 50);
var renderer = ...
[...]
/**
* Will be called when load completes.
* The argument will be the loaded texture.
*/
var onLoad = function (texture) {
var objGeometry = new THREE.BoxGeometry(20, 20, 20);
var objMaterial = new THREE.MeshPhongMaterial({
map: texture,
shading: THREE.FlatShading
});
var mesh = new THREE.Mesh(objGeometry, objMaterial);
scene.add(mesh);
var render = function () {
requestAnimationFrame(render);
mesh.rotation.x += 0.010;
mesh.rotation.y += 0.010;
renderer.render(scene, camera);
};
render();
}
// Function called when download progresses
var onProgress = function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};
// Function called when download errors
var onError = function (xhr) {
console.log('An error happened');
};
var loader = new THREE.TextureLoader();
loader.load('texture.jpg', onLoad, onProgress, onError);
In this example the textures are loaded inside the constructor of the mesh, multiple texture are loaded using Promises.
Extract (Globe.js):
Create a new container using Object3D
for having two meshes in the same container:
var Globe = function (radius, segments) {
THREE.Object3D.call(this);
this.name = "Globe";
var that = this;
// instantiate a loader
var loader = new THREE.TextureLoader();
A map called textures
where every object contains the url
of a texture file and val
for storing the value of a Three.js texture object.
// earth textures
var textures = {
'map': {
url: 'relief.jpg',
val: undefined
},
'bumpMap': {
url: 'elev_bump_4k.jpg',
val: undefined
},
'specularMap': {
url: 'wateretopo.png',
val: undefined
}
};
The array of promises, for each object in the map called textures
push a new Promise in the array texturePromises
, every Promise will call loader.load
. If the value of entry.val
is a valid THREE.Texture
object, then resolve the promise.
var texturePromises = [], path = './';
for (var key in textures) {
texturePromises.push(new Promise((resolve, reject) => {
var entry = textures[key]
var url = path + entry.url
loader.load(url,
texture => {
entry.val = texture;
if (entry.val instanceof THREE.Texture) resolve(entry);
},
xhr => {
console.log(url + ' ' + (xhr.loaded / xhr.total * 100) +
'% loaded');
},
xhr => {
reject(new Error(xhr +
'An error occurred loading while loading: ' +
entry.url));
}
);
}));
}
Promise.all
takes the promise array texturePromises
as argument. Doing so makes the browser wait for all the promises to resolve, when they do we can load the geometry and the material.
// load the geometry and the textures
Promise.all(texturePromises).then(loadedTextures => {
var geometry = new THREE.SphereGeometry(radius, segments, segments);
var material = new THREE.MeshPhongMaterial({
map: textures.map.val,
bumpMap: textures.bumpMap.val,
bumpScale: 0.005,
specularMap: textures.specularMap.val,
specular: new THREE.Color('grey')
});
var earth = that.earth = new THREE.Mesh(geometry, material);
that.add(earth);
});
For the cloud sphere only one texture is necessary:
// clouds
loader.load('n_amer_clouds.png', map => {
var geometry = new THREE.SphereGeometry(radius + .05, segments, segments);
var material = new THREE.MeshPhongMaterial({
map: map,
transparent: true
});
var clouds = that.clouds = new THREE.Mesh(geometry, material);
that.add(clouds);
});
}
Globe.prototype = Object.create(THREE.Object3D.prototype);
Globe.prototype.constructor = Globe;