Maybe this work for you!! This works for me...
initSelection: function (element, callback) {
callback({ id: 1, text: 'Text' });
}
Check very well that code is correctly spelled, my issue was in the initSelection
, I had initselection
If your data is already in array form, it's really simple using jQuery:
$(data.msg).each(function()
{
alert(this.value);
alert(this.label);
//this refers to the current item being iterated over
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('#myDropDown').append(option);
});
.ajax()
is more flexible than .getJSON()
- for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().
The easiest way only if you don't need return something it'ts just return null
You have to use the viewWithTag
function to find the view with the given tag
.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let point = touch.locationInView(self.view)
if let viewWithTag = self.view.viewWithTag(100) {
print("Tag 100")
viewWithTag.removeFromSuperview()
} else {
print("tag not found")
}
}
If someone views on my answer, you maybe in this condition:
1. Trying to get a map screenshot in canvas using openlayers (version >= 3)
2. And viewed the example of exporting map
3. Using ol.source.XYZ to render map layer
Bingo!
Using ol.source.XYZ.crossOrigin = 'Anonymous' to solve your confuse. Or like following code:
var baseLayer = new ol.layer.Tile({
name: 'basic',
source: new ol.source.XYZ({
url: options.baseMap.basic,
crossOrigin: "Anonymous"
})
});
There's an easy, old-fashioned way to store user credentials in an HTTPS URL:
https://user:[email protected]/...
You can change the URL with git remote set-url <remote-repo> <URL>
The obvious downside to that approach is that you have to store the password in plain text. You can still just enter the user name (https://[email protected]/...
) which will at least save you half the hassle.
You might prefer to switch to SSH or to use the GitHub client software.
if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"
If you want a query to use currently selected database. simply copy paste this query. (No modification required)
SELECT table_name ,
round(((data_length + index_length) / 1024 / 1024), 2) as SIZE_MB
FROM information_schema.TABLES
WHERE table_schema = DATABASE() ORDER BY SIZE_MB DESC;
In my case url contained wrong chars like spaces . Overall log your url and in some cases use browser.
When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication.
By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs:
To fix this issue add following lines After Return and Before Begin statement:
READS SQL DATA
DETERMINISTIC
For Example :
CREATE FUNCTION f2()
RETURNS CHAR(36) CHARACTER SET utf8
/*ADD HERE */
READS SQL DATA
DETERMINISTIC
BEGIN
For more detail about this issue please read Here
David: Great direction, but you missed \r. this worked for me:
$array = preg_split("/(\r\n|\n|\r)/", $string);
That is because you are only checking the current checkbox.
Change it to
function checkUncheck() {
$('.pChk').click(function() {
if ( $('.pChk:checked').length > 0) {
$("#ProjectListButton").show();
} else {
$("#ProjectListButton").hide();
}
});
}
to check if any of the checkboxes is checked (lots of checks in this line..).
reference: http://api.jquery.com/checked-selector/
[x for x in L if 'ab' in x]
I just created this js function using the jQuery size function http://api.jquery.com/size/
function classCount(name){
alert($('.'+name).size())
}
It alerts out the number of times the class name occurs in the document.
You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.
Also, I don't think you can use NOW()
as default value in OrderDate. Try to use the following:
OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored files(x > 0 for x in list)
in that function call creates a generator expression eg.
>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
print x
True
True
False
True
False
Which any
uses, and shortcircuits on encountering the first object that evaluates True
This is my solution:
public static bool OverlappingPeriods(DateTime aStart, DateTime aEnd,
DateTime bStart, DateTime bEnd)
{
if (aStart > aEnd)
throw new ArgumentException("A start can not be after its end.");
if(bStart > bEnd)
throw new ArgumentException("B start can not be after its end.");
return !((aEnd < bStart && aStart < bStart) ||
(bEnd < aStart && bStart < aStart));
}
I unit tested it with 100% coverage.
Just open MySQL Workbench and choose [Instance] Startup/Shutdown and click on start server. It worked for me
Here are some custom utility classes:
hr.dashed {
border-top: 2px dashed #999;
}
hr.dotted {
border-top: 2px dotted #999;
}
hr.solid {
border-top: 2px solid #999;
}
hr.hr-text {
position: relative;
border: none;
height: 1px;
background: #999;
}
hr.hr-text::before {
content: attr(data-content);
display: inline-block;
background: #fff;
font-weight: bold;
font-size: 0.85rem;
color: #999;
border-radius: 30rem;
padding: 0.2rem 2rem;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/*
*
* ==========================================
* FOR DEMO PURPOSES
* ==========================================
*
*/
body {
min-height: 100vh;
background-color: #fff;
color: #333;
}
.text-uppercase {
letter-spacing: .1em;
}
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">
<div class="container py-5">
<!-- For Demo Purpose -->
<header class="py-5 text-center">
<h1 class="display-4">Bootstrap Divider</h1>
<p class="lead mb-0">Some divider variants using <hr> element. </p>
</header>
<div class="row">
<div class="col-lg-8 mx-auto">
<div class="mb-4">
<h6 class=" text-uppercase">Dashed</h6>
<!-- Dashed divider -->
<hr class="dashed">
</div>
<div class="mb-4">
<h6 class=" text-uppercase">Dotted</h6>
<!-- Dotted divider -->
<hr class="dotted">
</div>
<div class="mb-4">
<h6 class="text-uppercase">Solid</h6>
<!-- Solid divider -->
<hr class="solid">
</div>
<div class="mb-4">
<h6 class=" text-uppercase">Text content</h6>
<!-- Gradient divider -->
<hr data-content="AND" class="hr-text">
</div>
</div>
</div>
</div>
_x000D_
Here is my solution:
/^(2[0-9]{3})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (0[0-9]|1[0-9]|2[0123])\:([012345][0-9])\:([012345][0-9])$/u
If you want to accomplish the same in Gecko (NS6+, Mozilla, etc) and IE4+ simultaneously, I believe this should do the trick:V
body {
overflow: -moz-scrollbars-vertical;
overflow-x: hidden;
overflow-y: auto;
}
This will be applied to entire body tag, please update it to your relevant css and apply this properties.
Yet another alternative is double brace initialization, e.g.
new ArrayList<String>() {{ add(s); }};
but it is inefficient and obscure. Therefore only suitable:
If you used rbenv
to install it, you can use
rbenv versions
to see which versions you have installed.
Then, use the uninstall command:
rbenv uninstall [-f|--force] <version>
for example:
rbenv uninstall 2.4.0 # Uninstall Ruby 2.4.0
If you installed Rails, it will be removed, too.
Don't know why but in my case it doesn't work the way suggested earlier. But it works like this:
Time.now.change(offset: "-3000")
Of course you need to change offset
value to yours.
Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage
, supported by all browsers
We do this sort of thing all the time for Accelerate.framework, a heavily vectorized OS X / iOS library, where we have to pay attention to alignment all the time. There are quite a few options, one or two of which I didn't see mentioned above.
The fastest method for a small array like this is just stick it on the stack. With GCC / clang:
void my_func( void )
{
uint8_t array[1024] __attribute__ ((aligned(16)));
...
}
No free() required. This is typically two instructions: subtract 1024 from the stack pointer, then AND the stack pointer with -alignment. Presumably the requester needed the data on the heap because its lifespan of the array exceeded the stack or recursion is at work or stack space is at a serious premium.
On OS X / iOS all calls to malloc/calloc/etc. are always 16 byte aligned. If you needed 32 byte aligned for AVX, for example, then you can use posix_memalign:
void *buf = NULL;
int err = posix_memalign( &buf, 32 /*alignment*/, 1024 /*size*/);
if( err )
RunInCirclesWaivingArmsWildly();
...
free(buf);
Some folks have mentioned the C++ interface that works similarly.
It should not be forgotten that pages are aligned to large powers of two, so page-aligned buffers are also 16 byte aligned. Thus, mmap() and valloc() and other similar interfaces are also options. mmap() has the advantage that the buffer can be allocated preinitialized with something non-zero in it, if you want. Since these have page aligned size, you will not get the minimum allocation from these, and it will likely be subject to a VM fault the first time you touch it.
Cheesy: Turn on guard malloc or similar. Buffers that are n*16 bytes in size such as this one will be n*16 bytes aligned, because VM is used to catch overruns and its boundaries are at page boundaries.
Some Accelerate.framework functions take in a user supplied temp buffer to use as scratch space. Here we have to assume that the buffer passed to us is wildly misaligned and the user is actively trying to make our life hard out of spite. (Our test cases stick a guard page right before and after the temp buffer to underline the spite.) Here, we return the minimum size we need to guarantee a 16-byte aligned segment somewhere in it, and then manually align the buffer afterward. This size is desired_size + alignment - 1. So, In this case that is 1024 + 16 - 1 = 1039 bytes. Then align as so:
#include <stdint.h>
void My_func( uint8_t *tempBuf, ... )
{
uint8_t *alignedBuf = (uint8_t*)
(((uintptr_t) tempBuf + ((uintptr_t)alignment-1))
& -((uintptr_t) alignment));
...
}
Adding alignment-1 will move the pointer past the first aligned address and then ANDing with -alignment (e.g. 0xfff...ff0 for alignment=16) brings it back to the aligned address.
As described by other posts, on other operating systems without 16-byte alignment guarantees, you can call malloc with the larger size, set aside the pointer for free() later, then align as described immediately above and use the aligned pointer, much as described for our temp buffer case.
As for aligned_memset, this is rather silly. You only have to loop in up to 15 bytes to reach an aligned address, and then proceed with aligned stores after that with some possible cleanup code at the end. You can even do the cleanup bits in vector code, either as unaligned stores that overlap the aligned region (providing the length is at least the length of a vector) or using something like movmaskdqu. Someone is just being lazy. However, it is probably a reasonable interview question if the interviewer wants to know whether you are comfortable with stdint.h, bitwise operators and memory fundamentals, so the contrived example can be forgiven.
Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.
In my case the bean has been initialized using @Autowired annotation instead of @MockBean
So in this way mocking of DAOs and Services throws such exception
And I like this way:
$cars = array
(
array("Volvo",22),
array("BMW",15),
array("Saab",5),
array("Land Rover",17)
);
The other big difference is Abandon does not remove items immediately, but when it does then cleanup it does a loop over session items to check for STA COM objects it needs to handle specially. And this can be a problem.
Under high load it's possible for two (or more) requests to make it to the server for the same session (that is two requests with the same session cookie). Their execution will be serialized, but since Abandon doesn't clear out the items synchronously but rather sets a flag it's possible for both requests to run, and both requests to schedule a work item to clear out session "later". Both these work items can then run at the same time, and both are checking the session objects, and both are clearing out the array of objects, and what happens when you have two things iterating over a list and changing it?? Boom! And since this happens in a queueuserworkitem callback and is NOT done in a try/catch (thanks MS), it will bring down your entire app domain. Been there.
Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.
Minimal working example:
import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class DateTestCase {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String firstdate = s.nextLine();
System.out.print("Insert second date: ");
String seconddate = s.nextLine();
// Formatter
DateTimeFormatter dateStringFormat = DateTimeFormat
.forPattern("dd MM yyyy");
DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
int days = Days.daysBetween(new LocalDate(firstTime),
new LocalDate(secondTime)).getDays();
System.out.println("Days between the two dates " + days);
}
}
A great alternative that hasn't been mentioned is to use the entity framework, which uses an object that is the table - to get data into an array you can do things like:
var rows = db.someTable.SqlQuery("SELECT col1,col2 FROM someTable").ToList().ToArray();
for info on getting started with Entity Framework see https://msdn.microsoft.com/en-us/library/aa937723(v=vs.113).aspx
Even more useful, if you have multiple parameters you can access any/all of them with:
_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
.Returns((string a, string b, string c) => string.Concat(a,b,c));
You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.
Most of the above work, but for me, this was the easiest.
Install the plugin, log out, log in, system, advanced, front end links manager, check and uncheck the options you want to show. It also works on any of the front end navigation's on your site.
http://www.magentocommerce.com/magento-connect/frontend-links-manager.html
Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw
for width: 100%
to get rid of the horizontal scrollbar.
I usualy use <li>
to include <a>
link. I disabled click action writing like this;
You may not include <a>
link, then you will ignore my post.
a.noclick {_x000D_
pointer-events: none;_x000D_
}
_x000D_
<a class="noclick" href="#">this is disabled</a>
_x000D_
Install express using npm: https://expressjs.com/en/starter/installing.html
Create a file named server.js at the same level of your index.html with this content:
var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(8080);
If you wish to put it in a different location, set the path on the third line:
server.use('/', express.static(__dirname + '/public'));
CD to the folder containing your file and run node from the console with this command:
node server.js
Browse to localhost:8080
There is one rule that is set by font-awesome.css
, which you need to override.
You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline;
by default and which I've corrected here:
<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:
I've downsized the font-size of the icon above in this instance to 30px
, as it feels too big at 40px
for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:
Maybe you forgot to change the permissions of app/cache app/log
I'm using Ubuntu so
sudo chmod -R 777 app/cache
sudo chmod -R 777 app/logs
sudo setfacl -dR -m u::rwX app/cache app/logs
Hope it helps..
I also had the same problem, and I saw a good solution in quora, using
sudo kill -9 PID.
see https://www.quora.com/How-do-I-kill-all-the-computer-processes-shown-in-nvidia-smi
I tried the solutions here, and as? [String:AnyObject] worked for me:
do{
if let json = stringToParse.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["id"] as! String
...
}
}
}catch {
print(error.localizedDescription)
}
=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )
Explanation:
(MONTH($A$2:$A$6)=1)
creates an array of 1 and 0, it's 1 when the
month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]
SUMPRODUCT
first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6)
, then it sums them. Hence in
your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)
This works also in OpenOffice and Google Spreadsheets
SELECT *
FROM people
WHERE names ='SMITH'
ORDER BY names asc
limit 10
If you need add group by clause. If you search Smith you would have to sort on something else.
Using the Promise pattern:
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
})
}
And when calling the function we can handle its response or error quite neatly.
getImage('imgUrl').then(function(successUrl){
//do stufff
}).catch(function(errorUrl){
//do stuff
})
Please use a <pre>
tag
demo : http://jsfiddle.net/K83cK/
var data = {_x000D_
"data": {_x000D_
"x": "1",_x000D_
"y": "1",_x000D_
"url": "http://url.com"_x000D_
},_x000D_
"event": "start",_x000D_
"show": 1,_x000D_
"id": 50_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
_x000D_
<pre id="json"></pre>
_x000D_
Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.
class A {
protected int minWeeklySalary;
protected int maxWeeklySalary;
protected static final int MIN = 1000;
protected static final int MAX = 2000;
public A() {
setSalaryRange();
}
protected void setSalaryRange() {
throw new RuntimeException("not implemented");
}
public void pr() {
System.out.println("minWeeklySalary: " + minWeeklySalary);
System.out.println("maxWeeklySalary: " + maxWeeklySalary);
}
}
class B extends A {
private int factor = 1;
public B(int _factor) {
this.factor = _factor;
}
@Override
protected void setSalaryRange() {
this.minWeeklySalary = MIN * this.factor;
this.maxWeeklySalary = MAX * this.factor;
}
}
public static void main(String[] args) {
B b = new B(2);
b.pr();
}
The result would actually be:
minWeeklySalary: 0
maxWeeklySalary: 0
This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.
I hope that would help someone.
If you need to both get the raw content from the request, but also need to use a bound model version of it in the controller, you will likely get this exception.
NotSupportedException: Specified method is not supported.
For example, your controller might look like this, leaving you wondering why the solution above doesn't work for you:
public async Task<IActionResult> Index(WebhookRequest request)
{
using var reader = new StreamReader(HttpContext.Request.Body);
// this won't fix your string empty problems
// because exception will be thrown
reader.BaseStream.Seek(0, SeekOrigin.Begin);
var body = await reader.ReadToEndAsync();
// Do stuff
}
You'll need to take your model binding out of the method parameters, and manually bind yourself:
public async Task<IActionResult> Index()
{
using var reader = new StreamReader(HttpContext.Request.Body);
// You shouldn't need this line anymore.
// reader.BaseStream.Seek(0, SeekOrigin.Begin);
// You now have the body string raw
var body = await reader.ReadToEndAsync();
// As well as a bound model
var request = JsonConvert.DeserializeObject<WebhookRequest>(body);
}
It's easy to forget this, and I've solved this issue before in the past, but just now had to relearn the solution. Hopefully my answer here will be a good reminder for myself...
Float: left, display: inline-block will both fail to align the elements horizontally if they exceed the width of the container.
It's important to note that the container should not wrap if the elements MUST display horizontally:
white-space: nowrap
Manually creating a DB cluster solved it in my case.
For some reason, when I installed postgres, the "initial DB" wasn't created. Executing initdb
did the trick for me.
This solution is provided in the PostgreSQL Wiki - First steps:
initdb
Typically installing postgres to your OS creates an "initial DB" and starts the postgres server daemon running. If not then you'll need to run initdb
You can use array_walk_recursive
:
array_walk_recursive($array, function ($item, $key) {
echo "$key holds $item\n";
});
It is possibly because the value of val
is actually the string "null"
rather than the value null
.
According to the javadoc a Scanner
does not seem to be intended for reading single characters. You attach a Scanner
to an InputStream
(or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.
Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.
You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.
if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098 extract it to your php folder or ext in xampp folder then add this on the end of the line in your php.ini file
extension=php_pdo_sqlsrv_55_ts.dll
extension=php_sqlsrv_55_ts.dll
im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll
if you are using xampp version 5.5 dll files is not included in the link...hope it helps
for example
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class ComboboxExample {
private JFrame frame = new JFrame("Test");
private JComboBox comboBox = new JComboBox();
public ComboboxExample() {
createGui();
}
private void createGui() {
comboBox.addItem("One");
comboBox.addItem("Two");
comboBox.addItem("Three");
JButton button = new JButton("Show Selected");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Selected item: " + comboBox.getSelectedItem());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.requestFocus();
comboBox.requestFocusInWindow();
}
});
}
});
JButton button1 = new JButton("Append Items");
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendCbItem();
}
});
JButton button2 = new JButton("Reduce Items");
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
reduceCbItem();
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(4, 1));
frame.add(comboBox);
frame.add(button);
frame.add(button1);
frame.add(button2);
frame.setLocation(200, 200);
frame.pack();
frame.setVisible(true);
selectFirstItem();
}
public void appendCbItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.addItem("Four");
comboBox.addItem("Five");
comboBox.addItem("Six");
comboBox.setSelectedItem("Six");
requestCbFocus();
}
});
}
public void reduceCbItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.removeItem("Four");
comboBox.removeItem("Five");
comboBox.removeItem("Six");
selectFirstItem();
}
});
}
public void selectFirstItem() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.setSelectedIndex(0);
requestCbFocus();
}
});
}
public void requestCbFocus() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
comboBox.requestFocus();
comboBox.requestFocusInWindow();
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ComboboxExample comboboxExample = new ComboboxExample();
}
});
}
}
\w
matches a word character. \b
is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)
\w
matches a
, b
, c
, d
, e
, and f
in "abc def"
\b
matches the (zero-width) position before a
, after c
, before d
, and after f
in "abc def"
I think groupby should work.
df.groupby(['A', 'B']).max()['C']
If you need a dataframe back you can chain the reset index call.
df.groupby(['A', 'B']).max()['C'].reset_index()
input:-webkit-autofill { background: #fff !important; }
I came to this question needing to prevent text wrapping at the hyphen.
This is how I did it:
<td><nobr>Table Text</nobr></td>
Reference:
So now assume the Customer wants to change his name in the webui - then there will be some controller action, where there will be the updated DTO with the old ID and the new name.
Normally, you have the following workflow:
P.S. This operation will inevitably issue 2 queries: select and update. Again, 2 queries, even if you wanna update a single field. However, if you utilize Hibernate's proprietary @DynamicUpdate annotation on top of entity class, it will help you not to include into update statement all the fields, but only those that actually changed.
P.S. If you do not wanna pay for first select statement and prefer to use Spring Data's @Modifying query, be prepared to lose L2C cache region related to modifiable entity; even worse situation with native update queries (see this thread) and also of course be prepared to write those queries manually, test them and support them in the future.
A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form
The simplest way to get tooltips in most browsers is to set some text in the title attribute.
eg.
<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />
produces (hover your mouse over the image):
a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg
Title attributes can be applied to most HTML elements.
This will not work if you try to import the file into EXCEL.
Associate the file extension csv with EXCEL.EXE so you will be able to invoke EXCEL by double-clicking the csv file.
Here I place some text followed by the NewLine Char followed by some more text AND enclosing the whole string with double quotes.
Do not use a CR since EXCEL will place part of the string in the next cell.
""text" + NL + "text""
When you invoke EXCEL, you will see this. You may have to auto size the height to see it all. Where the line breaks will depend on the width of the cell.
2
DATE
Here's the code in Basic
CHR$(34,"2", 10,"DATE", 34)
Short oneliner for CamelCases when you have spaces also included (doesn't work correctly if you have a word inbetween with small starting-letter):
a = "Test String"
a.gsub(' ', '').underscore
=> "test_string"
Maybe this old topic but i found this library is very helpful and easy to use
example for using it in android
Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
Watch every 5 seconds ...
watch -n 5 ls -l
If you wish to have visual confirmation of changes, append --differences
prior to the ls
command.
According to the OSX man page, there's also
The --cumulative option makes highlighting "sticky", presenting a running display of all positions that have ever changed. The -t or --no-title option turns off the header showing the interval, command, and current time at the top of the display, as well as the following blank line.
Linux/Unix man page can be found here
By using the page source you will get the whole HTML code.
So first decide the block of code or tag in which you require to retrieve the data or to click the element..
options = driver.find_elements_by_name_("XXX")
for option in options:
if option.text == "XXXXXX":
print(option.text)
option.click()
You can find the elements by name, XPath, id, link and CSS path.
Take a look at cavaj.
If you only want to know if any item of d
is contained in paid[j]
, as you literally say:
if any(x in paid[j] for x in d): ...
If you also want to know which items of d
are contained in paid[j]
:
contained = [x for x in d if x in paid[j]]
contained
will be an empty list if no items of d
are contained in paid[j]
.
There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d
contained in paid[j]
(and None
if no item is so contained):
firstone = next((x for x in d if x in paid[j]), None)
BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in
'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j]
into some more sophisticated predicate such as somere.search(paid[j])
for an appropriate RE object somere
.
(Python 2.6 or better -- slight differences in 2.5 and earlier).
If your intention is something else again, such as getting one or all of the indices in d
of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).
I want to add one Hello, World! example that explains the basics of slices for the very beginners. It helped me a lot.
Let's have a list with six values ['P', 'Y', 'T', 'H', 'O', 'N']
:
+---+---+---+---+---+---+
| P | Y | T | H | O | N |
+---+---+---+---+---+---+
0 1 2 3 4 5
Now the simplest slices of that list are its sublists. The notation is [<index>:<index>]
and the key is to read it like this:
[ start cutting before this index : end cutting before this index ]
Now if you make a slice [2:5]
of the list above, this will happen:
| |
+---+---|---+---+---|---+
| P | Y | T | H | O | N |
+---+---|---+---+---|---+
0 1 | 2 3 4 | 5
You made a cut before the element with index 2
and another cut before the element with index 5
. So the result will be a slice between those two cuts, a list ['T', 'H', 'O']
.
Find out the web server user
open up terminal and type
lsof -i tcp:80
This will show you the user of the web server process Here is an example from a raspberry pi running debian:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 7478 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7664 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7794 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
The user is www-data
If you give ownership of the web files to the web server:
chown www-data:www-data -R /opt/lamp/htdocs
And chmod 755 for good measure:
chmod 755 -R /opt/lamp/htdocs
Let me know how you go, maybe you need to use 'sudo' before the command, i.e.
sudo chown www-data:www-data -R /opt/lamp/htdocs
if it doesn't work, please give us the output of:
ls -al /opt/lamp/htdocs
You can use pyuic4
command on shell:
pyuic4 input.ui -o output.py
Have you tried using the JQuery
change event?
$("#g01-01").change(function() {
if(this.checked) {
//Do stuff
}
});
Then you can also remove onchange="doalert(this.id)"
from your checkbox :)
Edit:
I don't know if you are using JQuery
, but if you're not yet using it, you will need to put the following script in your page so you can use it:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
If you already have a bitmap, you could use the following code to resize:
Bitmap originalBitmap = <original initialization>;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
originalBitmap, newWidth, newHeight, false);
Try the following code :
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];
changing style with jquery
Try This
$('#selector_id').css('display','none');
You can also change multiple attribute in a single query
Try This
$('#replace-div').css({'padding-top': '5px' , 'margin' : '10px'});
You can do this by disabling the long press of the EditText
To implement it, just add the following line in the xml -
android:longClickable="false"
If you run into this issue in a fairly complex app it can be cumbersome to refactor all your imports. PyCharm offers a quickfix for this that will automatically change all usage of the imported symbols as well.
Similar to @Rikki, I solved this problem by upgrading matplotlib
with pip install matplotlib --upgrade
. If you can't upgrade uninstalling and reinstalling may work.
pip uninstall matplotlib
pip install matplotlib
Use mousedown
$('#checkbox1').mousedown(function() {
if (!$(this).is(':checked')) {
this.checked = confirm("Are you sure?");
$(this).trigger("change");
}
});
QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li
tag) to get all of the li
present inside the div with navbar
element.
let navbar = document_x000D_
.getElementById("navbar")_x000D_
.querySelectorAll('li');_x000D_
_x000D_
navbar.forEach((item, index) => {_x000D_
console.log({ index, item })_x000D_
});
_x000D_
_x000D_
<div id="navbar">_x000D_
<ul>_x000D_
<li id="navbar-One">One</li>_x000D_
<li id="navbar-Two">Two</li>_x000D_
<li id="navbar-Three">Three</li>_x000D_
<li id="navbar-Four">Four</li>_x000D_
<li id="navbar-Five">Five</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
I would suggest not to use @CachelookUp
for Selenium WebDriver for StaleElementReferenceException
.
If you are using @FindBy
annotation and have @CacheLookUp
, just comment it out and check.
try using
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.info);
...
linearLayout.addView(valueTV);
also make sure that the layout params you're creating are LinearLayout.LayoutParams...
function callServlet()
{
document.getElementById("adminForm").action="./Administrator";
document.getElementById("adminForm").method = "GET";
document.getElementById("adminForm").submit();
}
<button type="submit" onclick="callServlet()" align="center"> Register</button>
if you want to get the data in the entire row, you can use this combination below
tableModel.getDataVector().elementAt(jTable.getSelectedRow());
Where "tableModel" is the model for the table that can be accessed like so
(DefaultTableModel) jTable.getModel();
this will return the entire row data.
I hope this helps somebody
In case you don't have permission to 'Modify', you can install a free tool called "SQL Search" (by Redgate). I use it to search for keywords that I know will be in the SP and it returns a preview of the SP code with the keywords highlighted.
Ingenious! I then copy this code into my own SP.
Application.Exit
End
will work like a charm The "END" immediately terminates further execution while "Application.Exit" closes all forms and calls.
Best regrads,
This strange bug was solved through Interface Builder parameters as the other answers did not resolve the issue.
All I did was make the default label size larger than the content potentially could be and have it reflected in the estimatedRowHeight
height too. Previously, I set the default row height in Interface Builder to 88px
and reflected it like so in my controller viewDidLoad()
:
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 88.0
But that didn't work. So I realized that content wouldn't ever become larger than maybe 100px
, so I set the default cell height to 108px
(larger than the potential content) and reflected it like so in the controller viewDidLoad()
:
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 108.0
This actually allowed the code to shrink down the initial labels to the correct size. In other words, it never expanded out to a larger size, but could always shrink down... Also, no additional self.tableView.reloadData()
was needed in viewWillAppear()
.
I know this does not cover highly variable content sizes, but this worked in my situation where the content had a maximum possible character count.
Not sure if this is a bug in Swift or Interface Builder but it works like a charm. Give it a try!
For --driver-class-path
option you can use :
as delimeter to pass multiple jars.
Below is the example with spark-shell
command but I guess the same should work with spark-submit
as well
spark-shell --driver-class-path /path/to/example.jar:/path/to/another.jar
Spark version: 2.2.0
prop.table is a nice friendly way of obtaining proportions of tables.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Leaving margin blank gives you proportions of the whole table
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Giving it 1 gives you row proportions
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
And 2 is column proportions
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
Let us say we are migrating Jenkins LTS from PC1 to PC2 (irrispective of LTS version is same of upgraded). It is easy to use ThinBackUp Plugin for migration or Upgrade of Jenkins version.
Step1: Prepare PC1 for migration
Note: This Thinbackup will also take Plugin Backup which is optional.
Step2: Install Jenkins (Install using .war file or Paste archived version) in PC2.
sc create <Jenkins_PC2Servicename> binPath="<Path_to_Jenkinsexe>/jenkins.exe"
NOTE: If you are using Database setting of SCM in your Jenkins jobs then you need to take extra care as all SCM plugins do not support to carry Database settings with the help of ThinbackUp plugin. e.g. If you are using PTC Integrity SCM Plugin, and some Jenkins jobs are using DB using Integrity, then it will create a directory JENKINS_Home/IntegritySCM, ThinbackUp will not include this DB while taking backup.
Solution: Directly Copy this JENKINS_Home/IntegritySCM folder from PC1 to PC2.
I prefer this way
Using ajaxStop
+ setInterval
,, this will refresh the page after any XHR[ajax] request in the same page
$(document).ajaxStop(function() {
setInterval(function() {
location.reload();
}, 3000);
});
I don't understand what the meaning of ordering with the same column ASC
and DESC
in the same ORDER BY
, but this how you can do it: naam DESC, naam ASC
like so:
ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC
Relative : Relative to it’s current position, but can be moved. Or A RELATIVE positioned element is positioned relative to ITSELF.
Absolute : An ABSOLUTE positioned element is positioned relative to IT'S CLOSEST POSITIONED PARENT. if one is present, then it works like fixed.....relative to the window.
<div style="position:relative"> <!--2nd parent div-->
<div> <!--1st parent div-->
<div style="position:absolute;left:10px;....."> <!--Middle div-->
Md. Arif
</div>
</div>
</div>
Here, 2nd parent div
position is relative so the middle div
will changes it's position with respect to 2nd parent div
. If 1st parent div
position would relative then the Middle div
would changes it's position with respect to 1st parent div
. Details
If you want to get the last day of the current month you can do it with the following code.
$last_day_this_month = date('F jS Y', strtotime(date('F t Y')));
Change it to this:
switch (enumExample) {
case VALUE_A: {
//..
break;
}
}
The clue is in the error. You don't need to qualify case
labels with the enum type, just its value.
What you are doing is to look for (0) or (1) results.
(cnt >= 10 && cnt <= 20) returns either true or false.
--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--
You can use the sys.dm_tran_locks
view, which returns information about the currently active lock manager resources.
Try this
SELECT
SessionID = s.Session_id,
resource_type,
DatabaseName = DB_NAME(resource_database_id),
request_mode,
request_type,
login_time,
host_name,
program_name,
client_interface_name,
login_name,
nt_domain,
nt_user_name,
s.status,
last_request_start_time,
last_request_end_time,
s.logical_reads,
s.reads,
request_status,
request_owner_type,
objectid,
dbid,
a.number,
a.encrypted ,
a.blocking_session_id,
a.text
FROM
sys.dm_tran_locks l
JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
LEFT JOIN
(
SELECT *
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
) a ON s.session_id = a.session_id
WHERE
s.session_id > 50
The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.
Yes, but it's not a div
, it's a fieldset
fieldset {
border: 1px solid #000;
}
_x000D_
<fieldset>
<legend>AAA</legend>
</fieldset>
_x000D_
I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:
class AMLed
{
private:
uint8_t _ledPin;
long _turnOffTime;
public:
AMLed(uint8_t pin);
void setOn();
void setOff();
// Turn the led on for a given amount of time (relies
// on a call to check() in the main loop()).
void setOnForTime(int millis);
void check();
};
And here is the main source
AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
pinMode(_ledPin, OUTPUT);
}
void AMLed::setOn()
{
digitalWrite(_ledPin, HIGH);
}
void AMLed::setOff()
{
digitalWrite(_ledPin, LOW);
}
void AMLed::setOnForTime(int p_millis)
{
_turnOffTime = millis() + p_millis;
setOn();
}
void AMLed::check()
{
if (_turnOffTime != 0 && (millis() > _turnOffTime))
{
_turnOffTime = 0;
setOff();
}
}
It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html
To use, I simply do something like this in the .pde file:
#include "AM_Led.h"
#define TIME_LED 12 // The port for the LED
AMLed test(TIME_LED);
None of the current answers helped me here. We were getting something like:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:
#.#.#:compile (default-compile) on project Streaming_Test: Compilation failure
[ERROR] Unable to locate the Javac Compiler in:
[ERROR] /opt/java/J7.0/../lib/tools.jar
This happens because the Java installation has determined that it is a JRE installation. It's expecting there to be JDK stuff above the JRE subdirectory, hence the ../lib
in the path. Our tools.jar
is in $JAVA_HOME/lib/tools.jar
not in $JAVA_HOME/../lib/tools.jar
.
Unfortunately, we do not have an option to install a JDK on our OS (don't ask) so that wasn't an option. I fixed the problem by adding the following to the maven pom.xml
:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<fork>true</fork> <!-- not sure if this is also needed -->
<executable>${JAVA_HOME}/bin/javac</executable>
<!-- ^^^^^^^^^^^^^^^^^^^^^^ -->
</configuration>
</plugin>
By pointing the executable to the right place this at least got past our compilation failures.
In Java 8:
Map<Integer, String> sortedMap =
unsortedMap.entrySet().stream()
.sorted(Entry.comparingByValue())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
You can use .removeClass
and .addClass
. More in http://api.jquery.com.
I think the best way would be using a SimpleDateFormat
object.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here
run Android SDK Manager as administrator. that solved my problem
sudo android
Python script:
import re
text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)
Output:
text1
text2
text3
text4
text5
text6
Test this code here.
Another way to accomplish this if you still have that issue is by doing the following :
Thanks, Sufian.
To only strip whitespaces (in my case spaces and tabs) from lines with at least one non-whitespace character (this way empty indented lines are not touched):
sed -i -r 's/([^ \t]+)[ \t]+$/\1/' "$file"
$('#submit1, #submit2').click(function () {
if (this.id == 'submit1') {
alert('Submit 1 clicked');
}
else if (this.id == 'submit2') {
alert('Submit 2 clicked');
}
});
Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.
To answer your question:
Not sure if it's what you mean, but you can do this:
plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])
which then gives you the graph:
For Drupal 8 users looking for solution for DB import failure:
At end of sql dump file there can commands inserting data to "webprofiler" table. That's I guess some debug log file and is not really important for site to work so all this can be removed. I deleted all those inserts including LOCK TABLES and UNLOCK TABLES (and everything between). It's at very bottom of the sql file. Issue is described here:
https://www.drupal.org/project/devel/issues/2723437
But there is no solution for it beside truncating that table.
BTW I tried all solutions from answers above and nothing else helped.
Asking for purpose, there are different answers:
Using JSON to serialize objects (JavaScriptObjectNotation), each dictionary element maps to an indivual object property, so different entries defining a value for the same property has no meaning.
However, I came over the same question from a very specific use case: Writing JSON samples for API testing, I was wondering how to add comments into our JSON file without breaking the usability. The JSON spec does not know comments, so I came up with a very simple approach:
To use duplicate keys to comment our JSON samples. Example:
{
"property1" : "value1", "REMARK" : "... prop1 controls ...",
"property2" : "value2", "REMARK" : "... value2 raises an exception ...",
}
The JSON serializers which we are using have no problems with these "REMARK" duplicates and our application code simply ignores this little overhead.
So, even though there is no meaning on the application layer, these duplicates for us provide a valuable workaround to add comments to our testing samples without breaking the usability of the JSON.
if you just want the number of occurences then you can do this, $ grep -c "string_to_count" file_name
sudo service mysql stop
sudo mysqld --skip-grant-tables &
mysql -u root mysql
Change MYSECRET with your new root password
UPDATE user SET Password=PASSWORD('MYSECRET') WHERE User='root'; FLUSH PRIVILEGES; exit;
I meet the same problem and I solved with a solution like the following code:
var drfs = new Array();
var external = $.Deferred();
drfs.push(external.promise());
$('itemSelector').each( function() {
//initialize the context for each cycle
var t = this; // optional
var internal = $.Deferred();
// after the previous deferred operation has been resolved
drfs.pop().then( function() {
// do stuff of the cycle, optionally using t as this
var result; //boolean set by the stuff
if ( result ) {
internal.resolve();
} else {
internal.reject();
}
}
drfs.push(internal.promise());
});
external.resolve("done");
$.when(drfs).then( function() {
// after all each are resolved
});
The solution solves the following problem: to synchronize the asynchronous operations started in the .each() iteration, using Deferred object.
Using unzip
unzip -c whatever.war META-INF/MANIFEST.MF
It will print the output in terminal.
And for extracting all the files,
unzip whatever.war
Using jar
jar xvf test.war
Note! The jar
command will extract war contents to current directory. Not to a subdirectory (like Tomcat does).
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Copy Pasting @Lichtamberg's comments to gotoalberto's answer
Works also for Java 1.8:
# in ~/.zshrc and ~/.bashrc
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
This fixed my issue on java 8.
I dont do it like this. I find it easier to overload the constructor of the asychtask class ..
public class calc_stanica extends AsyncTask>
String String mWhateveryouwantToPass;
public calc_stanica( String whateveryouwantToPass)
{
this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ...
Pandas is pretty good at dealing with data. Here is one example how to use it:
import pandas as pd
# Read the CSV into a pandas data frame (df)
# With a df you can do many things
# most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')
# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]
# or export it as a list of dicts
dicts = df.to_dict().values()
One big advantage is that pandas deals automatically with header rows.
If you haven't heard of Seaborn, I recommend having a look at it.
See also: How do I read and write CSV files with Python?
import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
dicts = df.to_dict('records')
The content of df is:
country population population_time EUR
0 Germany 82521653.0 2016-12-01 True
1 France 66991000.0 2017-01-01 True
2 Indonesia 255461700.0 2017-01-01 False
3 Ireland 4761865.0 NaT True
4 Spain 46549045.0 2017-06-01 True
5 Vatican NaN NaT True
The content of dicts is
[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
{'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
{'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
{'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
{'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
{'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]
import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]
The content of lists
is:
[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
['Ireland', 4761865.0, NaT, True],
['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
['Vatican', nan, NaT, True]]
simple and makes deep copy breaking all links
$new=unserialize(serialize($old));
Here is a query used by Oracle SQL Developer in its Tablespaces view
select a.tablespace_name as "Tablespace Name",
round(a.bytes_alloc / 1024 / 1024) "Allocated (MB)",
round(nvl(b.bytes_free, 0) / 1024 / 1024) "Free (MB)",
round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024) "Used (MB)",
round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Free",
100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Used",
round(maxbytes/1024 / 1024) "Max. Bytes (MB)"
from ( select f.tablespace_name,
sum(f.bytes) bytes_alloc,
sum(decode(f.autoextensible, 'YES',f.maxbytes,'NO', f.bytes)) maxbytes
from dba_data_files f
group by tablespace_name) a,
( select f.tablespace_name,
sum(f.bytes) bytes_free
from dba_free_space f
group by tablespace_name) b
where a.tablespace_name = b.tablespace_name (+)
union all
select
h.tablespace_name as tablespace_name,
round(sum(h.bytes_free + h.bytes_used) / 1048576) megs_alloc,
round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576) megs_free,
round(sum(nvl(p.bytes_used, 0))/ 1048576) megs_used,
round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) Pct_Free,
100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) pct_used,
round(sum(f.maxbytes) / 1048576) max
from sys.v_$TEMP_SPACE_HEADER h, sys.v_$Temp_extent_pool p, dba_temp_files f
where p.file_id(+) = h.file_id
and p.tablespace_name(+) = h.tablespace_name
and f.file_id = h.file_id
and f.tablespace_name = h.tablespace_name
group by h.tablespace_name
ORDER BY 2;
PHP will work only on the .php
file extension.
If you are on Apache you can also set, in your httpd.conf
file, the extensions for PHP. You'll have to find the line:
AddType application/x-httpd-php .php .html
^^^^^
and add how many extensions, that should be read with the PHP interpreter, as you want.
No hack or js needed. Just apply the following rule to your root element:
min-height: 100%;
height: auto;
It will automatically choose the bigger one from the two as its height, which means if the content is longer than the browser, it will be the height of the content, otherwise, the height of the browser. This is standard css.
I prefer to put the variable on the inside to give an extra hint that the code is validating my variable is between a range values
if (500 < size && size < 600) { doStuff(); }
This is probably more verbose than you want, but you're asking for a slightly complex operation so actual code might be involved (the horror).
My recommendation, with zipObject
that's pretty logical:
_.zipObject(_.map(params, 'name'), _.map(params, 'input'));
Another option, more hacky, using fromPairs
:
_.fromPairs(_.map(params, function(val) { return [val['name'], val['input']));
The anonymous function shows the hackiness -- I don't believe JS guarantees order of elements in object iteration, so callling .values()
won't do.
I used this php function to generate the options, and insert it into my HTML
<?php
# code to output a set of options for a numeric drop down list
# parameters: (start, end, step, format, default)
function numericoptions($start, $end, $step, $formatstring, $default)
{
$retstring = "";
for($i = $start; $i <= $end; $i = $i + $step)
{
$retstring = $retstring . '<OPTION ';
$retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
if($default == $i)
{
$retstring = $retstring . ' selected="selected"';
}
$retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
}
return $retstring;
}
?>
And then in my webpage code I use it as below;
<select id="endmin" name="endmin">
<?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>
If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
This is my Df contain 4 is repeated twice so here will remove repeated values.
scala> df.show
+-----+
|value|
+-----+
| 1|
| 4|
| 3|
| 5|
| 4|
| 18|
+-----+
scala> val newdf=df.dropDuplicates
scala> newdf.show
+-----+
|value|
+-----+
| 1|
| 3|
| 5|
| 4|
| 18|
+-----+
Performance
typeof
is faster than instanceof
in situations where both are applicable.
Depending on your engine, the performance difference in favor of typeof
could be around 20%. (Your mileage may vary)
Here is a benchmark testing for Array
:
var subject = new Array();
var iterations = 10000000;
var goBenchmark = function(callback, iterations) {
var start = Date.now();
for (i=0; i < iterations; i++) { var foo = callback(); }
var end = Date.now();
var seconds = parseFloat((end-start)/1000).toFixed(2);
console.log(callback.name+" took: "+ seconds +" seconds.");
return seconds;
}
// Testing instanceof
var iot = goBenchmark(function instanceofTest(){
(subject instanceof Array);
}, iterations);
// Testing typeof
var tot = goBenchmark(function typeofTest(){
(typeof subject == "object");
}, iterations);
var r = new Array(iot,tot).sort();
console.log("Performance ratio is: "+ parseFloat(r[1]/r[0]).toFixed(3));
Result
instanceofTest took: 9.98 seconds.
typeofTest took: 8.33 seconds.
Performance ratio is: 1.198
The other answers here presuppose that you have a regex engine which supports non-greedy matching, which is an extension introduced in Perl 5 and widely copied to other modern languages; but it is by no means ubiquitous.
Many older or more conservative languages and editors only support traditional regular expressions, which have no mechanism for controlling greediness of the repetition operator *
- it always matches the longest possible string.
The trick then is to limit what it's allowed to match in the first place. Instead of .*
you seem to be looking for
[^>]*
which still matches as many of something as possible; but the something is not just .
"any character", but instead "any character which isn't >
".
Depending on your application, you may or may not want to enable an option to permit "any character" to include newlines.
Even if your regular expression engine supports non-greedy matching, it's better to spell out what you actually mean. If this is what you mean, you should probably say this, instead of rely on non-greedy matching to (hopefully, probably) Do What I Mean.
For example, a regular expression with a trailing context after the wildcard like .*?><br/>
will jump over any nested >
until it finds the trailing context (here, ><br/>
) even if that requires straddling multiple >
instances and newlines if you let it, where [^>]*><br/>
(or even [^\n>]*><br/>
if you have to explicitly disallow newline) obviously can't and won't do that.
Of course, this is still not what you want if you need to cope with <img title="quoted string with > in it" src="other attributes"> and perhaps <img title="nested tags">
, but at that point, you should finally give up on using regular expressions for this like we all told you in the first place.
insert into OPT (email, campaign_id)
select 'mom@coxnet' as email, 100 as campaign_id from dual MINUS
select email, campaign_id from OPT;
If there is already a record with [email protected]
/100
in OPT, the MINUS
will subtract this record from the select 'mom@coxnet' as email, 100 as campaign_id from dual
record and nothing will be inserted. On the other hand, if there is no such record, the MINUS
does not subract anything and the values mom@coxnet
/100
will be inserted.
As p.marino has already pointed out, merge
is probably the better (and more correct) solution for your problem as it is specifically designed to solve your task.
The reason it is only a suggestion is that you could quite easily write a print function that ignored the options value. The built-in printing and formatting functions do use the options
value as a default.
As to the second question, since R uses finite precision arithmetic, your answers aren't accurate beyond 15 or 16 decimal places, so in general, more aren't required. The gmp and rcdd packages deal with multiple precision arithmetic (via an interace to the gmp library), but this is mostly related to big integers rather than more decimal places for your doubles.
Mathematica or Maple will allow you to give as many decimal places as your heart desires.
EDIT:
It might be useful to think about the difference between decimal places and significant figures. If you are doing statistical tests that rely on differences beyond the 15th significant figure, then your analysis is almost certainly junk.
On the other hand, if you are just dealing with very small numbers, that is less of a problem, since R can handle number as small as .Machine$double.xmin
(usually 2e-308).
Compare these two analyses.
x1 <- rnorm(50, 1, 1e-15)
y1 <- rnorm(50, 1 + 1e-15, 1e-15)
t.test(x1, y1) #Should throw an error
x2 <- rnorm(50, 0, 1e-15)
y2 <- rnorm(50, 1e-15, 1e-15)
t.test(x2, y2) #ok
In the first case, differences between numbers only occur after many significant figures, so the data are "nearly constant". In the second case, Although the size of the differences between numbers are the same, compared to the magnitude of the numbers themselves they are large.
As mentioned by e3bo, you can use multiple-precision floating point numbers using the Rmpfr
package.
mpfr("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825")
These are slower and more memory intensive to use than regular (double precision) numeric
vectors, but can be useful if you have a poorly conditioned problem or unstable algorithm.
type chrome://restart
in the address bar and chrome, with all its apps that are running in background, will restart and the Auth password cache will be cleaned.
You have 2 options :
Create a third method that wrap both methods. Advantage here is that you put less logic in your template.
Otherwise if you want to add 2 calls in ng-click you can add ';' after edit($index)
like this
ng-click="edit($index); open()"
See here : http://jsfiddle.net/laguiz/ehTy6/
For everyone saying to get the bytes, copy it to MemoryStream
, etc. - if the content isn't expected to be larger than computer's memory should be reasonably be expected to allow, why not just use StreamReader
's built in ReadLine()
or ReadToEnd()
? I saw these weren't even mentioned, and they do everything for you.
I had a use-case where I just wanted to store the path of a SQLite file from a FileDialogResult
that the user picks during the synching/initialization process. My program then later needs to use this path when it is run for normal application processes. Maybe not the ideal way to capture/re-use the information, but it's not much different than writing to/reading from an .ini file - I just didn't want to set one up for one value. So I just read it from a flat, one-line text file. Here's what I did:
string filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!filePath.EndsWith(@"\")) temppath += @"\"; // ensures we have a slash on the end
filePath = filePath.Replace(@"\\", @"\"); // Visual Studio escapes slashes by putting double-slashes in their results - this ensures we don't have double-slashes
filePath += "SQLite.txt";
string path = String.Empty;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
path = sr.ReadLine(); // can also use sr.ReadToEnd();
sr.Close();
fs.Close();
fs.Flush();
return path;
If you REALLY need a byte[]
instead of a string
for some reason, using my example, you can always do:
byte[] toBytes;
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
toBytes = Encoding.ASCII.GetBytes(path);
sr.Close();
fs.Close();
fs.Flush();
return toBytes;
(Returning toBytes
instead of path
.)
If you don't want ASCII
you can easily replace that with UTF8
, Unicode
, etc.
In monodroid
, you can do like this for rounded rectangle, and then keeping this as a parent class, editbox
and other layout features can be added.
class CustomeView : TextView
{
public CustomeView (Context context, IAttributeSet ) : base (context, attrs)
{
}
public CustomeView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
}
protected override void OnDraw(Android.Graphics.Canvas canvas)
{
base.OnDraw(canvas);
Paint p = new Paint();
p.Color = Color.White;
canvas.DrawColor(Color.DarkOrange);
Rect rect = new Rect(0,0,3,3);
RectF rectF = new RectF(rect);
canvas.DrawRoundRect( rectF, 1,1, p);
}
}
}
try this:
OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'
If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>
. A similarly simple solution, then, would be to use tee --append
(or, on MacOS, tee -a
):
LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE" || echo "$LINE" | sudo tee --append "$FILE"
If you need an os independent method, works across Windows and Linux. Use python
$ python -c 'import multiprocessing as m; print m.cpu_count()'
16
Another option that I think is more readable when the code (e.g., a variable) is indented and the output string should be a one-liner (no newlines):
def some_method():
long_string = """
A presumptuous long string
which looks a bit nicer
in a text editor when
written over multiple lines
""".strip('\n').replace('\n', ' ')
return long_string
Apply following style to carousel listbox.
<div class="carousel-inner" role="listbox" style=" width:100%; height: 500px !important;">_x000D_
_x000D_
..._x000D_
_x000D_
</div
_x000D_
ensure_ascii=False really only defers the issue to the decoding stage:
>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "????"}
>>> json.loads(json1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 328, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte
Ultimately you can't store raw bytes in a JSON document, so you'll want to use some means of unambiguously encoding a sequence of arbitrary bytes as an ASCII string - such as base64.
>>> import json
>>> from base64 import b64encode, b64decode
>>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',}
>>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps'])
>>> json.dumps(my_dict)
'{"LeafTemps": "/////w=="}'
>>> json.loads(json.dumps(my_dict))
{u'LeafTemps': u'/////w=='}
>>> new_dict = json.loads(json.dumps(my_dict))
>>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps'])
>>> print new_dict
{u'LeafTemps': '\xff\xff\xff\xff'}
If you want to remove the support for any architecture, for example, ARMv7-s in your case, use menu Project -> Build Settings -> remove the architecture from "valid architectures".
You can use this as a temporary solution until the library has been updated. You have to remove the architecture from your main project, not from the library.
Alternatively, you can set the flag for your debug configuration's "Build Active Architecture Only" to Yes. Leave the release configuration's "Build Active Architecture Only" to No, just so you'll get a reminder before releasing that you ought to upgrade any third-party libraries you're using.
In C#, arrays cannot be resized dynamically.
One approach is to use
System.Collections.ArrayList
instead
of a native array
.
Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array.
The generic function resizeArray
(below) can be used to do that.
public static System.Array ResizeArray (System.Array oldArray, int newSize)
{
int oldSize = oldArray.Length;
System.Type elementType = oldArray.GetType().GetElementType();
System.Array newArray = System.Array.CreateInstance(elementType,newSize);
int preserveLength = System.Math.Min(oldSize,newSize);
if (preserveLength > 0)
System.Array.Copy (oldArray,newArray,preserveLength);
return newArray;
}
public static void Main ()
{
int[] a = {1,2,3};
a = (int[])ResizeArray(a,5);
a[3] = 4;
a[4] = 5;
for (int i=0; i<a.Length; i++)
System.Console.WriteLine (a[i]);
}
Android now supports adding a Space view between views. It's available from 4.0 ICS onwards.
This is how I handle iPhone (and similar) devices [not iPad]:
In my CSS file:
@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
/* CSS overrides for mobile here */
}
In the head of my HTML document:
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
You can also Navigate to HTML id from inside controller
$location.hash('id_in_html');
Have you tried it without the ANSI join ?
CREATE MATERIALIZED VIEW MV_Test
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT V.*, P.* FROM TPM_PROJECTVERSION V,TPM_PROJECT P
WHERE P.PROJECTID = V.PROJECTID
Use a DataTrigger
:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
mongod --port portnumber --dbpath /path_to_your_folder
By default portnumber is 27017 and path is /var/lib/mongodb
You can set your own port number and path where you want to keep all your database.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<script>
$(function() {
$(document).on('change', ':file', function() {var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function() {
$(':file').on('fileselect', function(event, numFiles, label) {var input = $(this).parents('.custom-file').find('.custom-file-label'),
log = numFiles > 1 ? numFiles + ' files selected' : label;if( input.length ) {input.text(log);} else {if( log ) alert(log);}});
});
});
</script>
</body>
</html>
You can build your HttpContent
using the combination of JObject
to avoid and JProperty
and then call ToString()
on it when building the StringContent
:
/*{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}*/
JObject payLoad = new JObject(
new JProperty("agent",
new JObject(
new JProperty("name", "Agent Name"),
new JProperty("version", 1)
),
new JProperty("username", "Username"),
new JProperty("password", "User Password"),
new JProperty("token", "xxxxxx")
)
);
using (HttpClient client = new HttpClient())
{
var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return JObject.Parse(responseBody);
}
}
request.getParameter("accountID")
is what you're looking for. This is part of the Java Servlet API. See http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html for more information.
Swift 4 and above
I have created an extension
extension UIViewController {
public func addActionSheetForiPad(actionSheet: UIAlertController) {
if let popoverPresentationController = actionSheet.popoverPresentationController {
popoverPresentationController.sourceView = self.view
popoverPresentationController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverPresentationController.permittedArrowDirections = []
}
}
}
How to use:
let actionSheetVC = UIAlertController(title: "Title", message: nil, preferredStyle: .actionSheet)
addActionSheetForIpad(actionSheet: actionSheetVC)
present(actionSheetVC, animated: true, completion: nil)
history -c will clear all histories.
I like to illustrate simple things by simple examples :)
Here is a very simple Service
example:
angular.module('toDo',[])
.service('dataService', function() {
// private variable
var _dataObj = {};
// public API
this.dataObj = _dataObj;
})
.controller('One', function($scope, dataService) {
$scope.data = dataService.dataObj;
})
.controller('Two', function($scope, dataService) {
$scope.data = dataService.dataObj;
});
And here the jsbin
And here is a very simple Factory
example:
angular.module('toDo',[])
.factory('dataService', function() {
// private variable
var _dataObj = {};
// public API
return {
dataObj: _dataObj
};
})
.controller('One', function($scope, dataService) {
$scope.data = dataService.dataObj;
})
.controller('Two', function($scope, dataService) {
$scope.data = dataService.dataObj;
});
And here the jsbin
If that is too simple, here is a more sophisticated example
Also see the answer here for related best practices comments
Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/
var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);
function markerOnClick(e)
{
alert("hi. you clicked the marker at " + e.latlng);
}
On Windows, you can use the following command to find out the defaults on the system where your applications runs.
java -XX:+PrintFlagsFinal -version | findstr HeapSize
Look for the options MaxHeapSize
(for -Xmx
) and InitialHeapSize
for -Xms
.
On a Unix/Linux system, you can do
java -XX:+PrintFlagsFinal -version | grep HeapSize
I believe the resulting output is in bytes.
Try this
final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
I actually use ASP C# to send my emails now, with something that looks like :
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.Count > 0)
{
string formEmail = "";
string fromEmail = "[email protected]";
string defaultEmail = "[email protected]";
string sendTo1 = "";
int x = 0;
for (int i = 0; i < Request.Form.Keys.Count; i++)
{
formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
formEmail += ": " + Request.Form[i] + "<br/>";
if (Request.Form.Keys[i] == "Email")
{
if (Request.Form[i].ToString() != string.Empty)
{
fromEmail = Request.Form[i].ToString();
}
formEmail += "<br/>";
}
}
System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
SmtpClient smtpClient = new SmtpClient();
try
{
myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
myMsg.IsBodyHtml = true;
myMsg.Body = formEmail;
myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
myMsg.Subject = "Sent using Gmail Smtp";
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "pward");
smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);
}
catch (Exception ee)
{
debug.Text += ee.Message;
}
}
}
This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.
Actually, your topic is belongs on https://serverfault.com/ but you can still try to check these .htaccess directives:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1
If you do not want to depend on external libs, this works both for Python 2.7+ and Python 3 (http://ideone.com/uB4Kdc):
# your code goes here
s = ["test"];
#s = "test";
isString = False;
if(isinstance(s, str)):
isString = True;
try:
if(isinstance(s, basestring)):
isString = True;
except NameError:
pass;
if(isString):
print("String");
else:
print("Not String");
i use colname(train) = paste("A", colname(train)) and it turns out to the same problem as yours.
I finally figure out that randomForest is more stingy than rpart, it can't recognize the colname with space, comma or other specific punctuation.
paste function will prepend "A" and " " as seperator with each colname. so we need to avert the space and use this sentence instead:
colname(train) = paste("A", colname(train), sep = "")
this will prepend string without space.
One Line option
This option gets a easy one-line to write the actual date.
Please, note that this is using
Calendar.class
andSimpleDateFormat
, and then it's not logical to use it under Java8.
yourstringdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
Only using class names is not sufficient in your case.
By.cssSelector(".ban")
has 15 matching nodesBy.cssSelector(".hot")
has 11 matching nodesBy.cssSelector(".ban.hot")
has 5 matching nodesTherefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.
Option 1: Using list items' index (CssSelector or XPath)
Limitations
Example:
driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));
Option 2: Using Selenium's FindElements
, then index them. (CssSelector or XPath)
Limitations
Example:
// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];
Option 3: Using text (XPath only)
Limitations
Example:
driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));
Option 4: Index the grouped selector (XPath only)
Limitations
Example:
driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));
Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)
Limitations
Example:
driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));
The most straight forward answer to this question is: You can't.
Youtube doesn't output their video's in the right format, thus they can't be embedded in a
<video/>
element.
There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.
Not possible in Java.
Here's the Scala way:
val m = List(5, 4, 2, 89)
for((el, i) <- m.zipWithIndex)
println(el +" "+ i)
One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py
file:
app = Flask(__name__, static_folder="your path to static")
Otherwise flask will not be able to detect static folder.
Many times when crawling we run into problems where content that is rendered on the page is generated with Javascript and therefore scrapy is unable to crawl for it (eg. ajax requests, jQuery craziness).
However, if you use Scrapy along with the web testing framework Selenium then we are able to crawl anything displayed in a normal web browser.
Some things to note:
You must have the Python version of Selenium RC installed for this to work, and you must have set up Selenium properly. Also this is just a template crawler. You could get much crazier and more advanced with things but I just wanted to show the basic idea. As the code stands now you will be doing two requests for any given url. One request is made by Scrapy and the other is made by Selenium. I am sure there are ways around this so that you could possibly just make Selenium do the one and only request but I did not bother to implement that and by doing two requests you get to crawl the page with Scrapy too.
This is quite powerful because now you have the entire rendered DOM available for you to crawl and you can still use all the nice crawling features in Scrapy. This will make for slower crawling of course but depending on how much you need the rendered DOM it might be worth the wait.
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from selenium import selenium
class SeleniumSpider(CrawlSpider):
name = "SeleniumSpider"
start_urls = ["http://www.domain.com"]
rules = (
Rule(SgmlLinkExtractor(allow=('\.html', )), callback='parse_page',follow=True),
)
def __init__(self):
CrawlSpider.__init__(self)
self.verificationErrors = []
self.selenium = selenium("localhost", 4444, "*chrome", "http://www.domain.com")
self.selenium.start()
def __del__(self):
self.selenium.stop()
print self.verificationErrors
CrawlSpider.__del__(self)
def parse_page(self, response):
item = Item()
hxs = HtmlXPathSelector(response)
#Do some XPath selection with Scrapy
hxs.select('//div').extract()
sel = self.selenium
sel.open(response.url)
#Wait for javscript to load in Selenium
time.sleep(2.5)
#Do some crawling of javascript created content with Selenium
sel.get_text("//div")
yield item
# Snippet imported from snippets.scrapy.org (which no longer works)
# author: wynbennett
# date : Jun 21, 2011
Reference: http://snipplr.com/view/66998/
I had a hard time trying to figure this out on Xamarin. From the suggestions above I came up with this solution.
private string getRealPathFromURI(Android.Net.Uri contentUri)
{
string filename = "";
string thepath = "";
Android.Net.Uri filePathUri;
ICursor cursor = this.ContentResolver.Query(contentUri, null, null, null, null);
if (cursor.MoveToFirst())
{
int column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
filePathUri = Android.Net.Uri.Parse(cursor.GetString(column_index));
filename = filePathUri.LastPathSegment;
thepath = filePathUri.Path;
}
return thepath;
}
In my exprience I added two Jquery libraries in my file.The versions were jquery 1.11.1 and 2.1.Suddenly I took out 2.1 Jquery from my code. Then ran it and was working for me well. After trying out the first answer. please check out your file like I said above.
x.times do |i|
something(i+1)
end
awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls >> to-plot-p.xls
print
will insert a newline by default. You dont want that to happen, hence use printf
instead.
And the ed
answer:
printf "%s\n" '1,$s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' w q | ed index.html
To reiterate what codaddict answered, the shell handles the redirection first, wiping out the "input.html" file, and then the shell invokes the "sed" command passing it a now empty file.
According to mysql docs: "to rename TEMPORARY
tables, RENAME TABLE
does not work. Use ALTER TABLE
instead."
So this is the most portable method:
ALTER TABLE `old_name` RENAME `new_name`;
In order to accomplish what you are describing please try this.forceUpdate().
If you just need to detect a palindrome, you can do it with a regex, as explained here. Probably not the most efficient approach, though...
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
You can use numpy's slicing, simply start:stop:step
.
>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])
This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2] # O(1), constant time
>>> b[:] = 0 # modifying the view changes original array
>>> a # original array is modified
array([0, 2, 0, 4, 0])
so if either of the above things are a problem, you can make a copy explicitly:
>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy() # explicit copy, O(n)
>>> b[:] = 0 # modifying the copy
>>> a # original is intact
array([1, 2, 3, 4, 5])
This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
It's too late to answer this question, but it could help for new readers,
It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody
and @RequestParam
doesn't matter.
body= "name=abc"
, and name = "abc"
body ="name=abc"
, name = "xyz,abc"
Html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="x" content="xx" />
vs Php:
<?php header('Content-type: text/html; charset=ISO-8859-1'); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta name="x" content="xx" />
To get this to work I had to combine many of the above answers, to anyone who this might help here is my much simpler process.
If you have Windows 10 just start typing "edit environmental..." and it'll pop up right away. Click path and Edit… then paste the ;C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd
at the end of the path already there, don't forget the ; to separate your new github path from the current path.
You do not need the guid but if you want to know how to find it open bash, type git --man-path
Regex is a very bad choice for this kind of task. Try to find a web service or an address database or a product which can clean address data instead.
Related:
What's wrong with this 1 simple line?
new LocalDateTime(new Date().getTime()).toLocalDate();
Write this in each "new activity" after you initialized your new intent->
Intent i = new Intent(this, yourClass.class);
startActivity(i);
finish();
One option would be to create a symbolic link between a subfolder in your storage directory and public directory.
For example
ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars
This is also the method used by Envoyer, a deployment manager built by Taylor Otwell, the developer of Laravel.
From this forum:
parseInt()
returns primitive integer type (int), wherebyvalueOf
returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
Oddly, the only decent JSON processor mentioned so far has been GSON.
Here are more good choices:
EDIT (Aug/2013):
One more to consider:
Suppose you have a which is an array. to get the dimensions of an array you should use shape.
import numpy as np
a = np.array([[3,20,99],[-13,4.5,26],[0,-1,20],[5,78,-19]])
a.shape
The output of this will be (4,3)
I had the same doubts, but could not make any changes on the table, I decided doing the following having seen my ID did not exceed the maximum number setted in the variable @count:
SET @count = 40000000;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;
SET @count = 0;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;
ALTER TABLE `users` AUTO_INCREMENT = 1;
The solution takes, but it's safe and it was necessary because my table owned foreign keys with data in another table.
I discovered that the dist/ folder in the project was owned by root. That is why sudo ng serve
does see the changes when ng serve
does not.
I removed the dist/ folder sudo rm -R dist/
and rebuild it as current user by starting the dev server ng serve
and all worked again.
You say in a comment you want to get "15.09.2016".
For this, use Date
and DateFormatter
:
let date = Date()
let formatter = DateFormatter()
Give the format you want to the formatter:
formatter.dateFormat = "dd.MM.yyyy"
Get the result string:
let result = formatter.string(from: date)
Set your label:
label.text = result
Result:
15.09.2016
ALTER TABLE
`table_name`
MODIFY COLUMN
`column_name2` enum(
'existing_value1',
'existing_value2',
'new_value1',
'new_value2'
)
NOT NULL AFTER `column_name1`;
In Spring Boot 2.2.x
you need to configure it like this:
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.build()
}
Kotlin:
@Bean
fun objectMapper(builder: Jackson2ObjectMapperBuilder) = builder.build()
I already found it:
SELECT grantee, privilege_type
FROM information_schema.role_table_grants
WHERE table_name='mytable'