While not directly related to the question's environment, just for the curiosity, I did the same test on .NET Core 2.1, x64, release mode.
Here is the interesting result, confirming similar phonomena (other way around) happening over the dark side of the force. Code:
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
Console.WriteLine("2 * (i * i)");
for (int a = 0; a < 10; a++)
{
int n = 0;
watch.Restart();
for (int i = 0; i < 1000000000; i++)
{
n += 2 * (i * i);
}
watch.Stop();
Console.WriteLine($"result:{n}, {watch.ElapsedMilliseconds} ms");
}
Console.WriteLine();
Console.WriteLine("2 * i * i");
for (int a = 0; a < 10; a++)
{
int n = 0;
watch.Restart();
for (int i = 0; i < 1000000000; i++)
{
n += 2 * i * i;
}
watch.Stop();
Console.WriteLine($"result:{n}, {watch.ElapsedMilliseconds}ms");
}
}
Result:
2 * (i * i)
2 * i * i
CPython has reference counting and garbage collection, PyPy has garbage collection only.
So objects tend to be deleted earlier and __del__
is called in a more predictable way in CPython. Some software relies on this behavior, thus they are not ready for migrating to PyPy.
Some other software works with both, but uses less memory with CPython, because unused objects are freed earlier. (I don't have any measurements to indicate how significant this is and what other implementation details affect the memory use.)
I know this is an old thread, but runtime optimization is another important part of JIT compilation that doesn't seemed to be discussed here. Basically, the JIT compiler can monitor the program as it runs to determine ways to improve execution. Then, it can make those changes on the fly - during runtime. Google JIT optimization (javaworld has a pretty good article about it.)
Code will be as below:
public class RemoveString {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String s=scanner.next();
String st="";
for(int i=s.length()-1;i>=0;i--){
st=st+s.charAt(i);
}
System.out.println(st);
}
}
If just to filter out the drag case, do it like this:
var moved = false;
$(selector)
.mousedown(function() {moved = false;})
.mousemove(function() {moved = true;})
.mouseup(function(event) {
if (!moved) {
// clicked without moving mouse
}
});
A late answer, but and approach using data.table
library(data.table)
DT <- data.table(dat)
DT[, .SD[which.max(Score),], by = Group]
Or, if it is possible to have more than one equally highest score
DT[, .SD[which(Score == max(Score)),], by = Group]
Noting that (from ?data.table
.SD
is a data.table containing the Subset of x's Data for each group, excluding the group column(s)
One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.
I am just going to show as a static example which you can accommodate in your real world.
On each of your <tr>
's add a data attribute for id
(i.e. data-id
) with the corresponding id value and specify a data-target
, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal
to make this a trigger for modal.
<tr data-toggle="modal" data-id="1" data-target="#orderModal">
<td>1</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="2" data-target="#orderModal">
<td>2</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="3" data-target="#orderModal">
<td>3</td>
<td>24234234</td>
<td>A</td>
</tr>
And now in the javascript just set up the modal just once and event listen to its events so you can do your work.
$(function(){
$('#orderModal').modal({
keyboard: true,
backdrop: "static",
show:false,
}).on('show', function(){ //subscribe to show method
var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
//make your ajax call populate items or what even you need
$(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow + '</b>'))
});
});
Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.
Alternative ways here:
More correct create DTO for API queries, for example entityDTO:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<EntityDto> getAll() { return entityService.getAllEntities(); }
But if you need return different Map parameters you can use next two examples
2. For return one parameter like map:
@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getOneParameterMap() { return ResponseEntity.status(HttpStatus.CREATED).body( Collections.singletonMap("key", "value")); }
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> getSomeParameters() { return ResponseEntity.status(HttpStatus.OK).body(Map.of( "key-1", "value-1", "key-2", "value-2", "key-3", "value-3")); }
SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).
A SQL 2012 example on this data
/* Prepare */
select * into #tmp
from
(
select 2 as rowint, 23 as Value
union select 3, 45
union select 17, 10
union select 9, 0
) x
/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value
from #tmp
LEAD(value) will return the value of the next row in respect to the given order in "over" clause.
try with this:
var RegExp =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;
You can add a specific url to each point, e.g.:
var points = [
['name1', 59.9362384705039, 30.19232525792222, 12, 'www.google.com'],
['name2', 59.941412822085645, 30.263564729357767, 11, 'www.amazon.com'],
['name3', 59.939177197629455, 30.273554411974955, 10, 'www.stackoverflow.com']
];
Add the url to the marker values in the for-loop:
var marker = new google.maps.Marker({
...
zIndex: place[3],
url: place[4]
});
Then you can add just before to the end of your for-loop:
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
Also see this example.
If you get the error "Unrecognized attribute 'enableSsl'" when following the advice to add that parameter to your web.config. I found that I was able to workaround the error by adding it to my code file instead in this format:
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
try
{
smtp.Send(mm);
}
catch (Exception ex)
{
MsgBox("Message not emailed: " + ex.ToString());
}
This is the system.net section of my web.config:
<system.net>
<mailSettings>
<smtp from="<from_email>">
<network host="smtp.gmail.com"
port="587"
userName="<your_email>"
password="<your_app_password>" />
</smtp>
</mailSettings>
</system.net>
On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:
yumdb search from_repo repoid
(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:
http://james.fedorapeople.org/yum/commands/find-repos-of-install.py
As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?
I'm late to the party but... I've had a similar situation come up and I discovered padding-right (and bottom, top, left too, of course). From the way I understand its definition, it puts a padding area inside the inner div
so there's no need to add a negative margin on the parent as you did with a margin.
padding-right: 10px;
This did the trick for me!
I use the QPython app. It's free and includes a code editor, an interactive interpreter and a package manager, allowing you to create and execute Python programs directly on your device.
Javac Reporter.java
java Reporter
Similarily, you can set it in windows environment variables. for example, in Win7
Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila
I believe that the code should be:
$connect = new mysqli("host", "root", "", "dbname");
because root does not have a password. the (using password: YES)
is saying "you're using a password with this user"
This is useful concept for recursion without static properties , reference etc:
function getRecursiveItems($id){
$allItems = array();
function getItems($parent_id){
return DB::findAll()->where('`parent_id` = $parent_id');
}
foreach(getItems($id) as $item){
$allItems = array_merge($allItems, getItems($item->id) );
}
return $allItems;
}
add this to your my.cnf
innodb_buffer_pool_size=1G
restart your mysql to make it effect
You're right that the SD Card directory is /sdcard
but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory()
to get the directory:
File sdDir = Environment.getExternalStorageDirectory();
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can use this code for toggle your element var ele = jQuery("yourelementid"); ele.slideToggle('slow'); this will work for you :)
A simple example:
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
int number1, number2, sum;
Scanner input = new Scanner(System.in);
System.out.println("Enter First multiple");
number1 = input.nextInt();
System.out.println("Enter second multiple");
number2 = input.nextInt();
sum = number1 * number2;
System.out.printf("The product of both number is %d", sum);
}
}
I don't realize why MimeTypeMap.getFileExtensionFromUrl()
has problems with space
s and some other characters, that returns ""
, but I just wrote this method to change the file name to an admit-able one. It's just playing with String
s. However, It kind of works. Through the method, the space
s existing in the file name is turned into a desirable character (which, here, is "x") via replaceAll(" ", "x")
and other unsuitable characters are turned into a suitable one via URLEncoder
. so the usage (according to the codes presented in the question and the selected answer) should be something like getMimeType(reviseUrl(url))
.
private String reviseUrl(String url) {
String revisedUrl = "";
int fileNameBeginning = url.lastIndexOf("/");
int fileNameEnding = url.lastIndexOf(".");
String cutFileNameFromUrl = url.substring(fileNameBeginning + 1, fileNameEnding).replaceAll(" ", "x");
revisedUrl = url.
substring(0, fileNameBeginning + 1) +
java.net.URLEncoder.encode(cutFileNameFromUrl) +
url.substring(fileNameEnding, url.length());
return revisedUrl;
}
I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.
select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
select o.orderID, o.price * o.qty as subtotal
from product p inner join orderitem o on p.ProductID= o.productID
where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
Some of the code I see in here fails with years like 2016, in which week 53 jumps to week 2.
Here is a revised and working version:
Date.prototype.getWeek = function() {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on monday, so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
if(new Date(target.getFullYear(), 0, 1).getDay() < 5) {
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
return 1 + Math.ceil(dayDiff / 7);
}
else { // jan 4th is on the next week (so next week is week 1)
return Math.ceil(dayDiff / 7);
}
};
there are some syntax errors to your program heres a working code;
#include<stdio.h>
int main()
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0){
printf("this is multiple number");
}
else if (b%a==0){
printf("this is multiple number");
}
else{
printf("this is not multiple number");
return 0;
}
}
$ls -l `which sh`
/bin/sh -> dash
$sudo dpkg-reconfigure dash #Select "no" when you're asked
[...]
$ls -l `which sh`
/bin/sh -> bash
Then it will be OK
Just in case commands in previous answers doesn't work,
Try this:
dat.dropna(subset=['x'], inplace = True)
How you loop through an array, depends on the presence of new line characters. With new line characters separating the array elements, the array can be referred to as "$array"
, otherwise it should be referred to as "${array[@]}"
. The following script will make it clear:
#!/bin/bash
mkdir temp
mkdir temp/aaa
mkdir temp/bbb
mkdir temp/ccc
array=$(ls temp)
array1=(aaa bbb ccc)
array2=$(echo -e "aaa\nbbb\nccc")
echo '$array'
echo "$array"
echo
for dirname in "$array"; do
echo "$dirname"
done
echo
for dirname in "${array[@]}"; do
echo "$dirname"
done
echo
echo '$array1'
echo "$array1"
echo
for dirname in "$array1"; do
echo "$dirname"
done
echo
for dirname in "${array1[@]}"; do
echo "$dirname"
done
echo
echo '$array2'
echo "$array2"
echo
for dirname in "$array2"; do
echo "$dirname"
done
echo
for dirname in "${array2[@]}"; do
echo "$dirname"
done
rmdir temp/aaa
rmdir temp/bbb
rmdir temp/ccc
rmdir temp
Is m_cRedundencyManager
able to use member functions? Most callbacks are set up to use regular functions or static member functions. Take a look at this page at C++ FAQ Lite for more information.
Update: The function declaration you provided shows that m_cRedundencyManager
is expecting a function of the form: void yourCallbackFunction(int, void *)
. Member functions are therefore unacceptable as callbacks in this case. A static member function may work, but if that is unacceptable in your case, the following code would also work. Note that it uses an evil cast from void *
.
// in your CLoggersInfra constructor:
m_cRedundencyManager->Init(myRedundencyManagerCallBackHandler, this);
// in your CLoggersInfra header:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr);
// in your CLoggersInfra source file:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr)
{
((CLoggersInfra *)CLoggersInfraPtr)->RedundencyManagerCallBack(i);
}
Also for openCV in python you can do:
img = cv2.imread('myImage.jpg')
height, width, channels = img.shape
Had a similar need. $compile
does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)
http://jsbin.com/ebuhuv/7/edit - my exploration test.
One thing to note (per my example), one of my requirements was that the template would change based on a type
attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.
To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.
ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");
You can do it without having to create a real Hibernate mapping. Try this:
SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team
No, you can use only some escape sequences - \n for example (maybe only this one).
Some answers don't work with large numbers.
Convert integer to the hex representation, then convert it to bytes:
def int_to_bytes(number):
hrepr = hex(number).replace('0x', '')
if len(hrepr) % 2 == 1:
hrepr = '0' + hrepr
return bytes.fromhex(hrepr)
Result:
>>> int_to_bytes(2**256 - 1)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
Love VonC's answer. Here's an easy version of it for beginners.
There is a git remote called origin
which I am sure you are all aware of. Basically, you can add as many remotes to a git repo as you want. So, what we can do is introduce a new remote which is the original repo not the fork. I like to call it original
Let's add original repo's to our fork as a remote.
git remote add original https://git-repo/original/original.git
Now let's fetch the original repo to make sure we have the latest coded
git fetch original
As, VonC suggested, make sure we are on the master.
git checkout master
Now to bring our fork up to speed with the latest code on original repo, all we have to do is hard reset our master branch in accordance with the original remote.
git reset --hard original/master
And you are done :)
$sudo docker-compose up
I did follow the steps as it is in the above answer to add $USER to group docker. i didn't want to add a new group docker because in my docker installation a group named docker automatically created.
but using docker-compose up didn't work either. It gave the same previous error. So in my case(Ubuntu 18.10) sudo docker-compose up fixed the issue.
ps: @Tiw thanks for the advice.
None of these answers with the use of HEAD@{1}
worked out for me, so here's my solution:
git reflog
d0c9f22 HEAD@{0}: commit (amend): [Feature] - ABC Commit Description
c296452 HEAD@{1}: commit: [Feature] - ABC Commit Description
git reset --soft c296452
Your staging environment will now contain all of the changes that you accidentally merged with the c296452 commit.
If you want to find all records that are not NULL, and either empty or have any number of spaces, this will work:
LIKE '%\ '
Make sure that there's a space after the backslash. More info here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
Recently I was also having this issue, then I contacted Google Support and they gave me this link to provide required info, I posted and within 24 hours my problem was fixed.
Link: https://support.google.com/payments/contact/alt_account_verification
I think that replacing:
List<String> list = Arrays.asList(split);
with
List<String> list = new ArrayList<String>(Arrays.asList(split));
resolves the problem.
@kindall's solution does not work with my Python version 3.5. @styles correctly states in his comment that the reason is the additional optional keywords argument. Hence my slightly refined version for Python 3 looks like this:
if VERBOSE:
def verboseprint(*args, **kwargs):
print(*args, **kwargs)
else:
verboseprint = lambda *a, **k: None # do-nothing function
Adding to kennytm's answer. When you do a shallow copy parent.copy() a new dictionary is created with same keys,but the values are not copied they are referenced.If you add a new value to parent_copy it won't effect parent because parent_copy is a new dictionary not reference.
parent = {1: [1,2,3]}
parent_copy = parent.copy()
parent_reference = parent
print id(parent),id(parent_copy),id(parent_reference)
#140690938288400 140690938290536 140690938288400
print id(parent[1]),id(parent_copy[1]),id(parent_reference[1])
#140690938137128 140690938137128 140690938137128
parent_copy[1].append(4)
parent_copy[2] = ['new']
print parent, parent_copy, parent_reference
#{1: [1, 2, 3, 4]} {1: [1, 2, 3, 4], 2: ['new']} {1: [1, 2, 3, 4]}
The hash(id) value of parent[1], parent_copy[1] are identical which implies [1,2,3] of parent[1] and parent_copy[1] stored at id 140690938288400.
But hash of parent and parent_copy are different which implies They are different dictionaries and parent_copy is a new dictionary having values reference to values of parent
This problem is happend because of php.ini defined limit was exided but have lot's of solution for this but simple one is to find your local servers folder and on that find the php folder and in that folder have php.ini file which have all declaration of these type setups. You just need to find one and change that value. But in this situation have one big problem once you change in your localhost file but what about server when you want to put your site on server it again produce same problem and you again follow the same for server. But you also know about .htaccess file this is one of the best and single place to do a lot's of things without changing core files. Like you change www routing, removing .php or other extentions from url or add one. Same like that you also difine default values of php.ini here like this - First you need to open the .htaccess file from your root directory or if you don't have this file so create one on root directory of your site and paste this code on it -
php_value upload_max_filesize 1000M
php_value post_max_size 99500M
php_value memory_limit 500M
php_value max_execution_time 300
after changes if you want to check the changes just run the php code
<?php phpinfo(); ?>
it will show you the php cofigrations all details. So you find your changes.
Note: for defining unlimited just add -1 like php_value memory_limit -1 It's not good and most of the time slow down your server. But if you like to be limit less then this one option is also fit for you. If after refresh your page changes will not reflect you must restart your local server once for changes.
Good Luck. Hope it will help. Want to download the .htaccess file click this.
I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.
To run the code in setNum
you have to call it. If you don't call it, the default value is 0
.
It isn't possible as far as I can tell, since a link needs HTML, and mailto links don't create an HTML email.
This is probably for security as you could add javascript or iframes to this link and the email client might open up the end user for vulnerabilities.
Thats where asp.net puts dynamically compiled assemblies.
This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger. http://youtu.be/9gAjIQc4bPU
This should do:
samp2 <- samp[,-1]
rownames(samp2) <- samp[,1]
So in short, no there is no alternative to reassigning.
Edit: Correcting myself, one can also do it in place: assign rowname attributes, then remove column:
R> df<-data.frame(a=letters[1:10], b=1:10, c=LETTERS[1:10])
R> rownames(df) <- df[,1]
R> df[,1] <- NULL
R> df
b c
a 1 A
b 2 B
c 3 C
d 4 D
e 5 E
f 6 F
g 7 G
h 8 H
i 9 I
j 10 J
R>
You should use UsedRange
instead like so:
Sub test()
Dim sh As Worksheet
Dim rn As Range
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim k As Long
Set rn = sh.UsedRange
k = rn.Rows.Count + rn.Row - 1
End Sub
The + rn.Row - 1
part is because the UsedRange only starts at the first row and column used, so if you have something in row 3 to 10, but rows 1 and 2 is empty, rn.Rows.Count
would be 8
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null)
{
int nmb = 0;
foreach (var item in ViewBag.Articles)
{
if (nmb % 3 == 0)
{
@:<div class="row">
}
<a href="@Url.Action("Article", "Programming", new { id = item.id })">
<div class="tasks">
<div class="col-md-4">
<div class="task important">
<h4>@item.Title</h4>
<div class="tmeta">
<i class="icon-calendar"></i>
@item.DateAdded - Pregleda:@item.Click
<i class="icon-pushpin"></i> Authorrr
</div>
</div>
</div>
</div>
</a>
if (nmb % 3 == 0)
{
@:</div>
}
}
}
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
Agree with @Pom12, @abayer. To complete the answer you need to add script block
Try something like this:
pipeline {
agent any
environment {
ENV_NAME = "${env.BRANCH_NAME}"
}
// ----------------
stages {
stage('Build Container') {
steps {
echo 'Building Container..'
script {
if (ENVIRONMENT_NAME == 'development') {
ENV_NAME = 'Development'
} else if (ENVIRONMENT_NAME == 'release') {
ENV_NAME = 'Production'
}
}
echo 'Building Branch: ' + env.BRANCH_NAME
echo 'Build Number: ' + env.BUILD_NUMBER
echo 'Building Environment: ' + ENV_NAME
echo "Running your service with environemnt ${ENV_NAME} now"
}
}
}
}
I had the same problem. Here is how I solved it. The solution loads the lib directory and all the subdirectories (not only the direct). Of course you can use this for all directories.
# application.rb
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
You can also override onContentChanged()
which is among others fired when setContentView()
has been called.
float: left
… Below are the most common ways to achieve two elements side-by-side…
Some basic css styles for parent
and child
elements in these examples:
.parent {
background: mediumpurple;
padding: 1rem;
}
.child {
border: 1px solid indigo;
padding: 1rem;
}
Using the float
solution my have unintended affect on other elements. (Hint: You may need to use a clearfix.)
html
<div class='parent'>
<div class='child float-left-child'>A</div>
<div class='child float-left-child'>B</div>
</div>
css
.float-left-child {
float: left;
}
html
<div class='parent'>
<div class='child inline-block-child'>A</div>
<div class='child inline-block-child'>B</div>
</div>
css
.inline-block-child {
display: inline-block;
}
Note: the space between these two child elements can be removed, by removing the space between the div tags:
html
<div class='parent'>
<div class='child inline-block-child'>A</div><div class='child inline-block-child'>B</div>
</div>
css
.inline-block-child {
display: inline-block;
}
html
<div class='parent flex-parent'>
<div class='child flex-child'>A</div>
<div class='child flex-child'>B</div>
</div>
css
.flex-parent {
display: flex;
}
.flex-child {
flex: 1;
}
html
<div class='parent inline-flex-parent'>
<div class='child'>A</div>
<div class='child'>B</div>
</div>
css
.inline-flex-parent {
display: inline-flex;
}
html
<div class='parent grid-parent'>
<div class='child'>A</div>
<div class='child'>B</div>
</div>
css
.grid-parent {
display: grid;
grid-template-columns: 1fr 1fr
}
If you want to search on both FROM and TO airports, you'll want to join on the Airports table twice - then you can use both from and to tables in your results set:
SELECT
Flights.*,fromAirports.*,toAirports.*
FROM
Flights
INNER JOIN
Airports fromAirports on Flights.fairport = fromAirports.code
INNER JOIN
Airports toAirports on Flights.tairport = toAirports.code
WHERE
...
for i in range(100):
if i == 50:
continue
dosomething
I think this is all you really need to do:
var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};
var listMerged = listA.Union(listB);
from Object import Object
or
From Class_Name import Class_name
If Object is a .py
file.
Gotta love list comprehensions.
[dict([a, int(x)] for a, x in b.items()) for b in list]
(remark: for Python 2 only code you may use "iteritems" instead of "items")
Rails 6 added an upsert
and upsert_all
methods that deliver this functionality.
Model.upsert(column_name: value)
[upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations.
Not if you are looking for an "upsert" (where the database executes an update or an insert statement in the same operation) type of statement. Out of the box, Rails and ActiveRecord have no such feature. You can use the upsert gem, however.
Otherwise, you can use: find_or_initialize_by
or find_or_create_by
, which offer similar functionality, albeit at the cost of an additional database hit, which, in most cases, is hardly an issue at all. So unless you have serious performance concerns, I would not use the gem.
For example, if no user is found with the name "Roger", a new user instance is instantiated with its name
set to "Roger".
user = User.where(name: "Roger").first_or_initialize
user.email = "[email protected]"
user.save
Alternatively, you can use find_or_initialize_by
.
user = User.find_or_initialize_by(name: "Roger")
In Rails 3.
user = User.find_or_initialize_by_name("Roger")
user.email = "[email protected]"
user.save
You can use a block, but the block only runs if the record is new.
User.where(name: "Roger").first_or_initialize do |user|
# this won't run if a user with name "Roger" is found
user.save
end
User.find_or_initialize_by(name: "Roger") do |user|
# this also won't run if a user with name "Roger" is found
user.save
end
If you want to use a block regardless of the record's persistence, use tap
on the result:
User.where(name: "Roger").first_or_initialize.tap do |user|
user.email = "[email protected]"
user.save
end
For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.
import urllib.request
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()
Output:
>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]
And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:
import random
upper_words = [word for word in words if word[0].isupper()]
name_words = [word for word in upper_words if not word.isupper()]
rand_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
And some random names:
>>> for n in range(10):
' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])
'Semiramis Sicilian'
'Julius Genevieve'
'Rwanda Cohn'
'Quito Sutherland'
'Eocene Wheller'
'Olav Jove'
'Weldon Pappas'
'Vienna Leyden'
'Io Dave'
'Schwartz Stromberg'
You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM
. Then simply type where it says TYPE
: what you want to say in QUOTES.
Example.. "OTHER"
ContextLoaderListener
has its own context which is shared by all servlets and filters. By default it will search /WEB-INF/applicationContext.xml
You can customize this by using
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/somewhere-else/root-context.xml</param-value>
</context-param>
on web.xml
, or remove this listener if you don't need one.
Try this:
SELECT 'I like ' || type_column_name || ' cake with ' ||
icing_column_name || ' and a ' fruit_column_name || '.'
AS Cake_Column FROM your_table_name;
It should concatenate all that data as a single column entry named "Cake_Column".
You can achieve this by two methods
Using XML Add this attribute to toolbar XML app:menu = "menu_name"
Using java By overriding onCreateOptionMenu(Menu menu)
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.demo_menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
for more details or implementating click on the menu go through this article https://bedevelopers.tech/android-toolbar-implementation-using-android-studio/
I think it's a pretty strong assumption to assume that the object is a class
. What if it's not a class
? There's also the assumption that the object was not defined in the interpreter. What if it was defined in the interpreter? Also, what if the attributes were added dynamically? When some python objects have attributes added to their __dict__
after creation, pickle
doesn't respect the addition of those attributes (i.e. it 'forgets' they were added -- because pickle
serializes by reference to the object definition).
In all these cases, pickle
and cPickle
can fail you horribly.
If you are looking to save an object
(arbitrarily created), where you have attributes (either added in the object definition, or afterward)… your best bet is to use dill
, which can serialize almost anything in python.
We start with a class…
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
... pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
...
>>>
Now shut down, and restart...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
... company1 = pickle.load(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>>
Oops… pickle
can't handle it. Let's try dill
. We'll throw in another object type (a lambda
) for good measure.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> with open('company_dill.pkl', 'wb') as f:
... dill.dump(company1, f)
... dill.dump(company2, f)
...
>>>
And now read the file.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
... company1 = dill.load(f)
... company2 = dill.load(f)
...
>>> company1
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>
It works. The reason pickle
fails, and dill
doesn't, is that dill
treats __main__
like a module (for the most part), and also can pickle class definitions instead of pickling by reference (like pickle
does). The reason dill
can pickle a lambda
is that it gives it a name… then pickling magic can happen.
Actually, there's an easier way to save all these objects, especially if you have a lot of objects you've created. Just dump the whole python session, and come back to it later.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> dill.dump_session('dill.pkl')
>>>
Now shut down your computer, go enjoy an espresso or whatever, and come back later...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>
The only major drawback is that dill
is not part of the python standard library. So if you can't install a python package on your server, then you can't use it.
However, if you are able to install python packages on your system, you can get the latest dill
with git+https://github.com/uqfoundation/dill.git@master#egg=dill
. And you can get the latest released version with pip install dill
.
To avoid the compilation error I used
let name1:string = person.name || '';
And then validate the empty string.
My case it solved i was using
@Html.DropDownList(model => model.TypeId ...)
using
@Html.DropDownListFor(model => model.TypeId ...)
will solve it
This is the correct code
function sum()
{
var txtFirstNumberValue = document.getElementById('total_fees').value;
var txtSecondNumberValue = document.getElementById('advance_payement').value;
var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);
if(txtFirstNumberValue=="" ||txtSecondNumberValue=="")
{
document.getElementById('balance_payement').value = 0;
}
if (!isNaN(result))
{
document.getElementById('balance_payement').value = result;
}
}
You can ssh
directly from the Terminal on Mac, but you need to use a .PEM
key rather than the putty
.PPK
key. You can use PuttyGen on Windows to convert from .PEM
to .PPK
, I'm not sure about the other way around though.
You can also convert the key using putty
for Mac via port
or brew
:
sudo port install putty
or
brew install putty
This will also install puttygen
. To get puttygen
to output a .PEM
file:
puttygen privatekey.ppk -O private-openssh -o privatekey.pem
Once you have the key, open a terminal window and:
ssh -i privatekey.pem [email protected]
The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.
chmod go-rw privatekey.pem
This could also be an issue of building the code using a 64 bit
configuration. You can try to select x86
as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager
From there you can change the Platform
of the project using the 32-bit .dll to x86
Use div.section > div
.
Better yet, use an <h1>
tag for the heading and div.section h1
in your CSS, so as to support older browsers (that don't know about the >
) and keep your markup semantic.
Here's my expression dark theme for WPF controls.
Harry Martyrossian mentions in a comment on his own answer that the
Get-ItemPropertyValue cmdlet was introduced in Powershell v5, which solves the problem:
PS> Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' 'ProgramFilesDir'
C:\Program Files
Alternatives for PowerShell v4-:
Here's an attempt to retain the efficiency while eliminating the need for repetition of the value name, which, however, is still a little cumbersome:
& { (Get-ItemProperty `
-LiteralPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion `
-Name $args `
).$args } 'ProgramFilesDir'
By using a script block, the value name can be passed in once as a parameter, and the parameter variable ($args
) can then simply be used twice inside the block.
Alternatively, a simple helper function can ease the pain:
function Get-RegValue([String] $KeyPath, [String] $ValueName) {
(Get-ItemProperty -LiteralPath $KeyPath -Name $ValueName).$ValueName
}
Note: All solutions above bypass the problem described in Ian Kemp's's answer - the need to use explicit quoting for certain value names when used as property names; e.g., .'15.0'
- because the value names are passed as parameters and property access happens via a variable; e.g., .$ValueName
As for the other answers:
I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.
double time_seconds = time_milliseconds / 1000.0; // add the decimal
System.out.println(time_milliseconds); // Now this should give you the right value.
evidently, as stated in the parser response, a column name is needed for both cases. In either versions the columns of "d" are not named.
in case 1: your column 2 of d is sum(totalitems)
which is not named. duration
will retain the name "duration"
in case 2: both month(clothdeliverydate)
and SUM(CONVERT(INT, deliveredqty))
have to be named
Example from the guide:
\newcommand{\example}[2][YYY]{Mandatory arg: #2;
Optional arg: #1.}
This defines \example to be a command with two arguments,
referred to as #1 and #2 in the {<definition>}--nothing new so far.
But by adding a second optional argument to this \newcommand
(the [YYY]) the first argument (#1) of the newly defined
command \example is made optional with its default value being YYY.
Thus the usage of \example is either:
\example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
\example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.
Use the DateTime.SpecifyKind
static method.
Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.
Example:
DateTime dateTime = DateTime.Now;
DateTime other = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
Console.WriteLine(dateTime + " " + dateTime.Kind); // 6/1/2011 4:14:54 PM Local
Console.WriteLine(other + " " + other.Kind); // 6/1/2011 4:14:54 PM Utc
M refers to the first non-ambiguous character in "decimal". If you don't add it the number will be treated as a double.
D is double.
How about useing Array.ConstrainedCopy:
int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
int[] ArrayTwo = new int[5];
Array.ConstrainedCopy(ArrayOne, 3, ArrayTwo, 0, 7-3);
You could use Array.CopyTo:
int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
int[] ArrayTwo = new int[5];
ArrayOne.CopyTo(ArrayTwo,3); //starts copy at index=3 until it reaches end of
//either array
If you set a static height for your header, you can use that in a calculation for the size of your wrapper.
http://jsfiddle.net/ske5Lqyv/5/
Using your example code, you can add this CSS:
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
#container {
height: 100%;
}
.header {
height: 64px;
background-color: lightblue;
}
.wrapper {
height: calc(100% - 64px);
overflow-y: auto;
}
Or, you can use flexbox for a more dynamic approach http://jsfiddle.net/19zbs7je/3/
<div id="container">
<div class="section">
<div class="header">Heading</div>
<div class="wrapper">
<p>Large Text</p>
</div>
</div>
</div>
html, body {
margin: 0px;
padding: 0px;
height: 100%;
}
#container {
display: flex;
flex-direction: column;
height: 100%;
}
.section {
flex-grow: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.header {
height: 64px;
background-color: lightblue;
flex-shrink: 0;
}
.wrapper {
flex-grow: 1;
overflow: auto;
min-height: 100%;
}
And if you'd like to get even fancier, take a look at my response to this question https://stackoverflow.com/a/52416148/1513083
works great!
using both ways seem to be unnecessary now:
execBtn.onclick = function() { runCommand() };
apparently works in every current browser.
tested in current Firefox, IE, Safari, Opera, Chrome on Windows; Firefox and Epiphany on Ubuntu; not tested on Mac or mobile systems.
If you use same color for whole program , you can define printf()
function.
#include<stdio.h>
#define ah_red "\e[31m"
#define printf(X) printf(ah_red "%s",X);
#int main()
{
printf("Bangladesh");
printf("\n");
return 0;
}
You can encode the <
and >
to their HTML equivelant.
html = html.replace(/</g, "<").replace(/>/g, ">");
var mode = [];
$("input[name='mode[]']:checked").each(function(i) {
mode.push($(this).val());
})
if(mode.length == 0)
{
alert('Please select mode!')
};
If you use Kotlin language you just add this code:
Create global variables of GoogleMap
and Marker
types.
I use variable marker to make variable marker value can change directly
private lateinit var map: GoogleMap
private lateinit var marker: Marker
And I use this function/method to add the marker on my map:
private fun placeMarkerOnMap(location: LatLng) {
val markerOptions = MarkerOptions().position(location)
val titleStr = getAddress(location)
markerOptions.title(titleStr)
marker = map.addMarker(markerOptions)
}
After I create the function I place this code on the onMapReady()
to remove the marker and create a new one:
map.setOnMapClickListener { location ->
map.clear()
marker.remove()
placeMarkerOnMap(location)
}
It's bonus if you want to display the address location when you click the marker add this code to hide and show the marker address but you need a method to get the address location. I got the code from this post: How to get complete address from latitude and longitude?
map.setOnMarkerClickListener {marker ->
if (marker.isInfoWindowShown){
marker.hideInfoWindow()
}else{
marker.showInfoWindow()
}
true
}
Try this:
foreach($array as $k => $obj) {
$obj->{'newKey'} = "value";
}
Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview
Below are the descriptions of different keystores from the post:
JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.
JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.
PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.
PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.
Try to complete cmake process with following libs:
sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev
What everyone seems to miss is that the semi-colons in JavaScript are not statement terminators but statement separators. It's a subtle difference, but it is important to the way the parser is programmed. Treat them like what they are and you will find leaving them out will feel much more natural.
I've programmed in other languages where the semi-colon is a statement separator and also optional as the parser does 'semi-colon insertion' on newlines where it does not break the grammar. So I was not unfamiliar with it when I found it in JavaScript.
I don't like noise in a language (which is one reason I'm bad at Perl) and semi-colons are noise in JavaScript. So I omit them.
First alpha of eclipse word wrap released!
Got this answer from this post: How can I get word wrap to work in Eclipse PDT for PHP files?
you can use help on command prompt on cd command by writing this command cd /? as shown in this figure
Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON
method to recursively build the result
Below, html2json
is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
tagName: _x000D_
e.tagName,_x000D_
textContent:_x000D_
e.textContent,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.children, Elem)_x000D_
})_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
In the previous example, the textContent
gets a little butchered. To remedy this, we introduce another data constructor, TextElem
. We'll have to map over the childNodes
(instead of children
) and choose to return the correct data type based on e.nodeType
– this gets us a littler closer to what we might need
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
toJSON: () => ({_x000D_
type:_x000D_
'TextElem',_x000D_
textContent:_x000D_
e.textContent_x000D_
})_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
toJSON : () => ({_x000D_
type:_x000D_
'Elem',_x000D_
tagName: _x000D_
e.tagName,_x000D_
attributes:_x000D_
Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
children:_x000D_
Array.from(e.childNodes, fromNode)_x000D_
})_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
switch (e.nodeType) {_x000D_
case 3: return TextElem(e)_x000D_
default: return Elem(e)_x000D_
}_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
JSON.stringify(Elem(e), null, ' ')_x000D_
_x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
<h1 class="mainHeading">Some heading</h1>_x000D_
<ul id="menu">_x000D_
<li><a href="/a">a</a></li>_x000D_
<li><a href="/b">b</a></li>_x000D_
<li><a href="/c">c</a></li>_x000D_
</ul>_x000D_
<p>some text</p>_x000D_
</main>
_x000D_
Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity
In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^
Related: Recursive methods using JavaScript: building your own version of JSON.stringify
I would like to use this field in order to return all the records that have been updated in the last 5 minutes.
This means you need to update the date to "now" every time you save the object. Maybe you'll find this useful: Moongoose create-modified plugin
Another option would be to set a flag variable as a Boolean
and then change that value based on your criteria.
Dim count as Integer
Dim flag as Boolean
flag = True
While flag
count = count + 1
If count = 10 Then
'Set the flag to false '
flag = false
End If
Wend
Use traceback.extract_stack()
if you want convenient access to module and function names and line numbers.
Use ''.join(traceback.format_stack())
if you just want a string that looks like the traceback.print_stack()
output.
Notice that even with ''.join()
you will get a multi-line string, since the elements of format_stack()
contain \n
. See output below.
Remember to import traceback
.
Here's the output from traceback.extract_stack()
. Formatting added for readability.
>>> traceback.extract_stack()
[
('<string>', 1, '<module>', None),
('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
('<pyshell#1>', 1, '<module>', None)
]
Here's the output from ''.join(traceback.format_stack())
. Formatting added for readability.
>>> ''.join(traceback.format_stack())
' File "<string>", line 1, in <module>\n
File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
ret = method(*args, **kwargs)\n
File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
exec(code, self.locals)\n File "<pyshell#2>", line 1, in <module>\n'
I created a WSGI middleware that stores the raw body from the environ['wsgi.input']
stream. I saved the value in the WSGI environ so I could access it from request.environ['body_copy']
within my app.
This isn't necessary in Werkzeug or Flask, as request.get_data()
will get the raw data regardless of content type, but with better handling of HTTP and WSGI behavior.
This reads the entire body into memory, which will be an issue if for example a large file is posted. This won't read anything if the Content-Length
header is missing, so it won't handle streaming requests.
from io import BytesIO
class WSGICopyBody(object):
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
length = int(environ.get('CONTENT_LENGTH') or 0)
body = environ['wsgi.input'].read(length)
environ['body_copy'] = body
# replace the stream since it was exhausted by read()
environ['wsgi.input'] = BytesIO(body)
return self.application(environ, start_response)
app.wsgi_app = WSGICopyBody(app.wsgi_app)
request.environ['body_copy']
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]);
}
I ended up using this quick piece of code that did exactly what I needed:
final JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
try {
// Open an input stream
Scanner reader = new Scanner(fc.getSelectedFile());
}
There are windows installers for MySQLdb avaialable for both 32 and 64 bit, supporting Python from 2.6 to 3.4. Check here.
My two cents with example length of 30 :
var truncatedInput = string.IsNullOrEmpty(input) ?
string.Empty :
input.Substring(0, Math.Min(input.Length, 30));
you can use also..
$('#apply-form input').blur(function()
{
if( $(this).val() == '' ) {
$(this).parents('p').addClass('warning');
}
});
if you have doubt about spaces,then try..
$('#apply-form input').blur(function()
{
if( $(this).val().trim() == '' ) {
$(this).parents('p').addClass('warning');
}
});
SELECT MIN(COLUMN_NAME)
FROM (
SELECT DISTINCT TOP 3 COLUMN_NAME
FROM TABLE_NAME
ORDER BY
COLUMN_NAME DESC
) AS 'COLUMN_NAME'
I use the following directive that makes me and most users very happy! It uses moment for parsing and formatting. It looks a little bit like the one by SunnyShah, mentioned earlier.
angular.module('app.directives')
.directive('appDatetime', function ($window) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
var moment = $window.moment;
ngModel.$formatters.push(formatter);
ngModel.$parsers.push(parser);
element.on('change', function (e) {
var element = e.target;
element.value = formatter(ngModel.$modelValue);
});
function parser(value) {
var m = moment(value);
var valid = m.isValid();
ngModel.$setValidity('datetime', valid);
if (valid) return m.valueOf();
else return value;
}
function formatter(value) {
var m = moment(value);
var valid = m.isValid();
if (valid) return m.format("LLLL");
else return value;
}
} //link
};
}); //appDatetime
In my form i use it like this:
<label>begin: <input type="text" ng-model="doc.begin" app-datetime required /></label>
<label>end: <input type="text" ng-model="doc.end" app-datetime required /></label>
This will bind a timestamp (milliseconds since 1970) to doc.begin
and doc.end
.
CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.
first we read data in csv format and then convert to data frame and create a temp view
Reading data in csv format
val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")
printing the schema
data.printSchema
data.createOrReplaceTempView("Data")
Now we can run sql queries on top the table view we just created
%sql select Week as Date,Campaign Type,Engagements,Country from Data order by Date asc
grep
For non-greedy match in grep
you could use a negated character class. In other words, try to avoid wildcards.
For example, to fetch all links to jpeg files from the page content, you'd use:
grep -o '"[^" ]\+.jpg"'
To deal with multiple line, pipe the input through xargs
first. For performance, use ripgrep
.
You'll need to tell your vnc client to export the correct $DISPLAY once you have logged in. How you do that will probably depend on your vnc client.
I had a similar problem with IndentationError in PyCharm.
I could not find any tabs in my code, but once I deleted code AFTER the line with the IndentationError, all was well.
I suspect that you had a tab in the following line:
sex = sex if not sex == 2 else random.randint(0,1)
tools.jar comes with JDK, but what happens in your case it looks for it within /Java/jre6. Change JAVA_HOME env var to one of your JDK home.
You can certainly do something like
SQL> ed
Wrote file afiedt.buf
1 begin
2 for d in (select * from dept)
3 loop
4 for e in (select * from emp where deptno=d.deptno)
5 loop
6 dbms_output.put_line( 'Employee ' || e.ename ||
7 ' in department ' || d.dname );
8 end loop;
9 end loop;
10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
Or something equivalent using explicit cursors.
SQL> ed
Wrote file afiedt.buf
1 declare
2 cursor dept_cur
3 is select *
4 from dept;
5 d dept_cur%rowtype;
6 cursor emp_cur( p_deptno IN dept.deptno%type )
7 is select *
8 from emp
9 where deptno = p_deptno;
10 e emp_cur%rowtype;
11 begin
12 open dept_cur;
13 loop
14 fetch dept_cur into d;
15 exit when dept_cur%notfound;
16 open emp_cur( d.deptno );
17 loop
18 fetch emp_cur into e;
19 exit when emp_cur%notfound;
20 dbms_output.put_line( 'Employee ' || e.ename ||
21 ' in department ' || d.dname );
22 end loop;
23 close emp_cur;
24 end loop;
25 close dept_cur;
26* end;
27 /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES
PL/SQL procedure successfully completed.
However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of
FOR x IN (SELECT *
FROM all_users,
org
WHERE length(all_users.username) = 3
AND all_users.username = org.username )
LOOP
<<do something>>
END LOOP;
Here is a basic, successful use of javascript hover on ios that I made:
Note: I used jQuery, which is hopefully ok for you.
JavaScript:
$(document).ready(function(){
// Sorry about bad spacing. Also...this is jquery if you didn't notice allready.
$(".mm").hover(function(){
//On Hover - Works on ios
$("p").hide();
}, function(){
//Hover Off - Hover off doesn't seem to work on iOS
$("p").show();
})
});
CSS:
.mm { color:#000; padding:15px; }
HTML:
<div class="mm">hello world</div>
<p>this will disappear on hover of hello world</p>
I found this http://weblogs.asp.net/mikaelsoderstrom/archive/2010/07/30/add-namespaces-with-razor.aspx which explains how to add a custom namespace to all your razor pages.
Basically you can make this
using Microsoft.WebPages.Compilation;
public class PreApplicationStart
{
public static void InitializeApplication()
{
CodeGeneratorSettings.AddGlobalImport("Custom.Namespace");
}
}
and put the following code in your AssemblyInfo.cs
[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "InitializeApplication")]
the method InitializeApplication will be executed before Application_Start in global.asax
var times = [1,2,3];
for(var i = 0; i < times.length; i++) {
for(var j = 0; j < times[i];j++) {
// do something
}
}
Using jQuery .each()
$([1,2,3]).each(function(i, val) {
for(var j = 0; j < val;j++) {
// do something
}
});
OR
var x = [1,2,3];
$(x).each(function(i, val) {
for(var j = 0; j < val;j++) {
// do something
}
});
You can do like below with pure JS:
var times = [1,2,3];
times.forEach(function(i) {
// do something
});
For info, if you are binding to a class, you can do this in your type via DisplayNameAttribute
:
[DisplayName("Access key")]
public string AccessKey { get {...} set {...} }
Now the header-text on auto-generated columns will be "Access key".
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country
in another function as return value, (string)
, taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
DefaultTextStyle
is unrelated to the problem. Removing it simply uses the default style, which is far bigger than the one you used so it hides the problem.
textAlign
aligns the text in the space occupied by Text
when that occupied space is bigger than the actual content.
The thing is, inside a Column
, your Text
takes the bare minimum space. It is then the Column
that aligns its children using crossAxisAlignment
which defaults to center
.
An easy way to catch such behavior is by wrapping your texts like this :
Container(
color: Colors.red,
child: Text(...)
)
Which using the code you provided, render the following :
The problem suddenly becomes obvious: Text
don't take the whole Column
width.
You now have a few solutions.
You can wrap your Text
into an Align
to mimic textAlign
behavior
Column(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Container(
color: Colors.red,
child: Text(
"Should be left",
),
),
),
],
)
Which will render the following :
or you can force your Text
to fill the Column
width.
Either by specifying crossAxisAlignment: CrossAxisAlignment.stretch
on Column
, or by using SizedBox
with an infinite width
.
Column(
children: <Widget>[
SizedBox(
width: double.infinity,
child: Container(
color: Colors.red,
child: Text(
"Should be left",
textAlign: TextAlign.left,
),
),
),
],
),
which renders the following:
In that example, it is TextAlign
that placed the text to the left.
Possible solutions:
Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.
If you use AWS you can use the load balancer to redirect the request to specific port based on the host.
For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html
EDIT: In case that blog dies, here are the links from the blog.
All the bellow files are more them 400MB.
Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO FileVisual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO FileVisual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO FileVisual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File
Visual J# 2005 Express Edition
448,702 KB
.IMG File|.ISO File
I like things to happen automatically and for bins to fall on "nice" values. The following seems to work quite well.
import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
def compute_histogram_bins(data, desired_bin_size):
min_val = np.min(data)
max_val = np.max(data)
min_boundary = -1.0 * (min_val % desired_bin_size - min_val)
max_boundary = max_val - max_val % desired_bin_size + desired_bin_size
n_bins = int((max_boundary - min_boundary) / desired_bin_size) + 1
bins = np.linspace(min_boundary, max_boundary, n_bins)
return bins
if __name__ == '__main__':
data = np.random.random_sample(100) * 123.34 - 67.23
bins = compute_histogram_bins(data, 10.0)
print(bins)
plt.hist(data, bins=bins)
plt.xlabel('Value')
plt.ylabel('Counts')
plt.title('Compute Bins Example')
plt.grid(True)
plt.show()
The result has bins on nice intervals of bin size.
[-70. -60. -50. -40. -30. -20. -10. 0. 10. 20. 30. 40. 50. 60.]
Sample Usage:
import paramiko
paramiko.util.log_to_file("paramiko.log")
# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))
# Auth
username,password = "bar","foo"
transport.connect(None,username,password)
# Go!
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)
# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)
# Close
if sftp: sftp.close()
if transport: transport.close()
System.exit(0);
Is probably what you are looking for. It will close the entire application and take you to the home Screen.
Number of parameters is the amount of numbers that can be changed in the model. Mathematically this means number of dimensions of your optimization problem. For you as a programmer, each of this parameters is a floating point number, which typically takes 4 bytes of memory, allowing you to predict the size of this model once saved.
This formula for this number is different for each neural network layer type, but for Dense layer it is simple: each neuron has one bias parameter and one weight per input:
N = n_neurons * ( n_inputs + 1)
.
[Update]
I've just realized why you weren't receiving results back... you have a missing line in your Deserialize
method. You were forgetting to assign the results to your obj
:
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
Also, just for reference, here is the Serialize
method :
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
Edit
If you want to use Json.NET here are the equivalent Serialize/Deserialize methods to the code above..
Deserialize:
JsonConvert.DeserializeObject<T>(string json);
Serialize:
JsonConvert.SerializeObject(object o);
This are already part of Json.NET so you can just call them on the JsonConvert class.
Link: Serializing and Deserializing JSON with Json.NET
Now, the reason you're getting a StackOverflow is because of your Properties
.
Take for example this one :
[DataMember]
public string unescapedUrl
{
get { return unescapedUrl; } // <= this line is causing a Stack Overflow
set { this.unescapedUrl = value; }
}
Notice that in the getter
, you are returning the actual property (ie the property's getter is calling itself over and over again), and thus you are creating an infinite recursion.
Properties (in 2.0) should be defined like such :
string _unescapedUrl; // <= private field
[DataMember]
public string unescapedUrl
{
get { return _unescapedUrl; }
set { _unescapedUrl = value; }
}
You have a private field and then you return the value of that field in the getter, and set the value of that field in the setter.
Btw, if you're using the 3.5 Framework, you can just do this and avoid the backing fields, and let the compiler take care of that :
public string unescapedUrl { get; set;}
This Code will Divide the control into two equal sides.
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linearLayout">
<TextView
android:text = "Left Side"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight = "1"
android:id = "@+id/txtLeft"/>
<TextView android:text = "Right Side"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight = "1"
android:id = "@+id/txtRight"/>
</LinearLayout>
I guess it doesn't mean anything to you now. But just for reference for people stopping by
Performance Test - SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable
Memory allocation:
Time used for inserting:
Time for searching an item:
this is pretty basic stuff, all you need to do is to create a base view model and make sure ALL! and i mean ALL! of your views that will ever use that layout will receive views that use that base model!
public class SomeViewModel : ViewModelBase
{
public bool ImNotEmpty = true;
}
public class EmptyViewModel : ViewModelBase
{
}
public abstract class ViewModelBase
{
}
in the _Layout.cshtml:
@model Models.ViewModelBase
<!DOCTYPE html>
<html>
and so on...
in the the Index (for example) method in the home controller:
public ActionResult Index()
{
var model = new SomeViewModel()
{
};
return View(model);
}
the Index.cshtml:
@model Models.SomeViewModel
@{
ViewBag.Title = "Title";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
i disagree that passing a model to the _layout is an error, some user info can be passed and the data can be populate in the controllers inheritance chain so only one implementation is needed.
obviously for more advanced purpose you should consider creating custom static contaxt using injection and include that model namespace in the _Layout.cshtml.
but for basic users this will do the trick
I call this script trun. I suggest putting it in a directory in your executable path. Make sure it is executable like this:
chmod +x ~/bin/trun
Then you can run commands in a new window by just adding trun before them, like this:
trun tail -f /var/log/system.log
Here's the script. It does some fancy things like pass your arguments, change the title bar, clear the screen to remove shell startup clutter, remove its file when its done. By using a unique file for each new window it can be used to create many windows at the same time.
#!/bin/bash
# make this file executable with chmod +x trun
# create a unique file in /tmp
trun_cmd=`mktemp`
# make it cd back to where we are now
echo "cd `pwd`" >$trun_cmd
# make the title bar contain the command being run
echo 'echo -n -e "\033]0;'$*'\007"' >>$trun_cmd
# clear window
echo clear >>$trun_cmd
# the shell command to execute
echo $* >>$trun_cmd
# make the command remove itself
echo rm $trun_cmd >>$trun_cmd
# make the file executable
chmod +x $trun_cmd
# open it in Terminal to run it in a new Terminal window
open -b com.apple.terminal $trun_cmd
Expanding on @JetLaggy:
After trying again and again to modify .bash_profile with the MAMP directory, I changed the file permissions for the MAMP php directory and was able to get 'which php' to show the proper directory. Trouble was that other functions didn't work, such as 'php -v'.
So I updated MAMP. http://documentation.mamp.info/en/mamp/installation/updating-mamp
This did the trick for my particular setup. I had to adjust my PATH to reflect the updated version of PHP, but once I did, everything worked!
Try this :
awk '$3="";1' file.txt > new_file && mv new_file file.txt
or
awk '{$3="";print}' file.txt > new_file && mv new_file file.txt
ArrayList<String> myArrayList = new ArrayList<String>();
...
String[] myArray = myArrayList.toArray(new String[0]);
Whether it's a "good idea" would really be dependent on your use case.
The number of rows effected is returned from execute:
rows_affected=cursor.execute("SELECT ... ")
of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:
cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount
From the inline documentation of python MySQLdb:
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns long integer rows affected, if any
"""
You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();
.
The SPE IDE has built-in UML creator. Just open the files in SPE and click on the UML tab.
I don't know how comprhensive it is for your needs, but it doesn't require any additional downloads or configurations to use.
Save the page which contains
<?php
phpinfo();
?>
with the .php extension. Something like info.php
, not info.html
...
If you use Robert Harder's Base64 utility, then you can do:
InputStream is = new Base64.InputStream(cph);
Or with sun's JRE, you can do:
InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.
There are other Stack Overflow questions about Base64 decoding, such as this one.
var num = new Number(14.12);
console.log(num.toPrecision(2));//outputs 14
console.log(num.toPrecision(3));//outputs 14.1
console.log(num.toPrecision(4));//outputs 14.12
console.log(num.toPrecision(5));//outputs 14.120
Try this:
str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);
Output:
ice
There may be a valid reason why you want to do this, but generating this kind of XML is generally best avoided. Why? Because it means that the XML elements of your map are dependent on the runtime contents of your map. And since XML is usually used as an external interface or interface layer this is not desirable. Let me explain.
The Xml Schema (xsd) defines the interface contract of your XML documents. In addition to being able to generate code from the XSD, JAXB can also generate the XML schema for you from the code. This allows you to restrict the data exchanged over the interface to the pre-agreed structures defined in the XSD.
In the default case for a Map<String, String>
, the generated XSD will restrict the map element to contain multiple entry elements each of which must contain one xs:string
key and one xs:string
value. That's a pretty clear interface contract.
What you describe is that you want the xml map to contain elements whose name will be determined by the content of the map at runtime. Then the generated XSD can only specify that the map must contain a list of elements whose type is unknown at compile time. This is something that you should generally avoid when defining an interface contract.
To achieve a strict contract in this case, you should use an enumerated type as the key of the map instead of a String. E.g.
public enum KeyType {
KEY, KEY2;
}
@XmlJavaTypeAdapter(MapAdapter.class)
Map<KeyType , String> mapProperty;
That way the keys which you want to become elements in XML are known at compile time so JAXB should be able to generate a schema that would restrict the elements of map to elements using one of the predefined keys KEY or KEY2.
On the other hand, if you wish to simplify the default generated structure
<map>
<entry>
<key>KEY</key>
<value>VALUE</value>
</entry>
<entry>
<key>KEY2</key>
<value>VALUE2</value>
</entry>
</map>
To something simpler like this
<map>
<item key="KEY" value="VALUE"/>
<item key="KEY2" value="VALUE2"/>
</map>
You can use a MapAdapter that converts the Map to an array of MapElements as follows:
class MapElements {
@XmlAttribute
public String key;
@XmlAttribute
public String value;
private MapElements() {
} //Required by JAXB
public MapElements(String key, String value) {
this.key = key;
this.value = value;
}
}
public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
public MapAdapter() {
}
public MapElements[] marshal(Map<String, String> arg0) throws Exception {
MapElements[] mapElements = new MapElements[arg0.size()];
int i = 0;
for (Map.Entry<String, String> entry : arg0.entrySet())
mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());
return mapElements;
}
public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {
Map<String, String> r = new TreeMap<String, String>();
for (MapElements mapelement : arg0)
r.put(mapelement.key, mapelement.value);
return r;
}
}
The best solution I found this to work for me guys after trying all the other solutions.... Basically i set the sScrollX to 200% then set the individual column widths to the required % that I wanted. The more columns that you have and the more space that you require then you need to raise the sScrollX %... The null means that I want those columns to retain the datatables auto width they have set in their code.
$('#datatables').dataTable
({
"sScrollX": "200%", //This is what made my columns increase in size.
"bScrollCollapse": true,
"sScrollY": "320px",
"bAutoWidth": false,
"aoColumns": [
{ "sWidth": "10%" }, // 1st column width
{ "sWidth": "null" }, // 2nd column width
{ "sWidth": "null" }, // 3rd column width
{ "sWidth": "null" }, // 4th column width
{ "sWidth": "40%" }, // 5th column width
{ "sWidth": "null" }, // 6th column width
{ "sWidth": "null" }, // 7th column width
{ "sWidth": "10%" }, // 8th column width
{ "sWidth": "10%" }, // 9th column width
{ "sWidth": "40%" }, // 10th column width
{ "sWidth": "null" } // 11th column width
],
"bPaginate": true,
"sDom": '<"H"TCfr>t<"F"ip>',
"oTableTools":
{
"aButtons": [ "copy", "csv", "print", "xls", "pdf" ],
"sSwfPath": "copy_cvs_xls_pdf.swf"
},
"sPaginationType":"full_numbers",
"aaSorting":[[0, "desc"]],
"bJQueryUI":true
});
On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.
If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.
You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.
Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.
Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
and Java 8 you could do
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);
Update: For pre 26 use Joda time
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);
In app/build.gradle file, add like this-
dependencies {
compile 'joda-time:joda-time:2.9.4'
}
Use Collections.swap
and Arrays.asList
:
Collections.swap(Arrays.asList(arr), i, j);
As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.
We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.
Have a ViewModel for the User
public class UserViewModel
{
public int UserID { set;get;}
public string FirstName { set;get;}
//add remaining properties as per your requirement
}
and in your controller have a method to get a list of Users
public class UserController : Controller
{
[HttpGet]
public ActionResult List()
{
List<UserViewModel> objList=UserService.GetUsers(); // this method should returns list of Users
return View("users",objList)
}
}
Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)
and in your users.cshtml ( which is under Views/User folder),
@model List<UserViewModel>
<table>
@foreach(UserViewModel objUser in Model)
{
<tr>
<td>@objUser.UserId.ToString()</td>
<td>@objUser.FirstName</td>
</tr>
}
</table>
All Set now you can access the url like yourdomain/User/List
and it will give you a list of users in an HTML table.
This is an answer to this question (Export Heroku App to a new GitHub repo) which has been marked as duplicate of this one and redirected here.
I wanted to mirror my repo from Heroku to Github personal so that it shows all commits etc also which I made in Heroku. https://docs.github.com/en/free-pro-team@latest/github/importing-your-projects-to-github/importing-a-git-repository-using-the-command-line in Github documentation was useful.
As mentioned in another answer, this plugin
makes Ctrl-+ and Ctrl-- zoom in and out. On MacOS that would be ?+ and ?-.
But at least on MacOS Lion and Eclipse Helios, ?- worked but not ?+ – no key combination (and I tried a bunch, including ?= and variants with Ctrl and Shift) would increase font size. However, by changing the key bindings, I was able to get it to work.
Preferences => General => Keys
Commands "Zoom Out" and "Decrease Font" were already set to ?- (and that seemed to work), so I set "Zoom In" and "Increase Font" to ?= (one of them was that and the other was ?+), and that worked.
What about using filter and getting the first index from the resulting array?
var result = someArray.filter(isNotNullNorUndefined)[0];
In Java 8 you can do it like this:
import java.util.*;
import java.util.stream.*;
List<JsonNode> datasets = StreamSupport
.stream(datasets.get("datasets").spliterator(), false)
.collect(Collectors.toList())
I've got this error when I accidentally defined a property as a specific object type, instead of the interface type I have defined in UnityContainer.
For example:
Defining UnityContainer:
var container = new UnityContainer();
container.RegisterInstance(typeof(IDashboardRepository), DashboardRepository);
config.DependencyResolver = new UnityResolver(container);
SiteController (the wrong way - notice repo type):
private readonly DashboardRepository _repo;
public SiteController(DashboardRepository repo)
{
_repo = repo;
}
SiteController (the right way):
private readonly IDashboardRepository _repo;
public SiteController(IDashboardRepository repo)
{
_repo = repo;
}
.register a:link{
color:#FFFFFF;
}
There is an operator missing, likely a *
:
-3.7 need_something_here (prof[x])
The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7
(a float) as a function, which is not allowed.
The parenthesis are also not needed in this case, the following may be sufficient/correct:
-3.7 * prof[x]
As Legolas points out, there are other things which may need to be addressed:
2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
^-- op missing
extra parenthesis --^
valid but questionable float*tuple --^
expression yields 0.0 always --^
TestClass.instance_methods
or without all the inherited methods
TestClass.instance_methods - Object.methods
(Was 'TestClass.methods - Object.methods')
Another pure css based solution that is based on two clipped rounded elements that i rotate to get to the right angle:
http://jsfiddle.net/maayan/byT76/
That's the basic css that enables it:
.clip1 {
position:absolute;
top:0;left:0;
width:200px;
height:200px;
clip:rect(0px,200px,200px,100px);
}
.slice1 {
position:absolute;
width:200px;
height:200px;
clip:rect(0px,100px,200px,0px);
-moz-border-radius:100px;
-webkit-border-radius:100px;
border-radius:100px;
background-color:#f7e5e1;
border-color:#f7e5e1;
-moz-transform:rotate(0);
-webkit-transform:rotate(0);
-o-transform:rotate(0);
transform:rotate(0);
}
.clip2
{
position:absolute;
top:0;left:0;
width:200px;
height:200px;
clip:rect(0,100px,200px,0px);
}
.slice2
{
position:absolute;
width:200px;
height:200px;
clip:rect(0px,200px,200px,100px);
-moz-border-radius:100px;
-webkit-border-radius:100px;
border-radius:100px;
background-color:#f7e5e1;
border-color:#f7e5e1;
-moz-transform:rotate(0);
-webkit-transform:rotate(0);
-o-transform:rotate(0);
transform:rotate(0);
}
and the js rotates it as required.
quite easy to understand..
Hope it helps, Maayan
I'm doing it with no additional tool. I have just added the following files to my Win32 app project.
One header file which defines some constants than we can reuse on our resource file and even on the program code. We only need to maintain one file. Thanks to the Qt team that showed me how to do it on a Qt project, it now also works on my Win32 app.
----[version.h]----
#ifndef VERSION_H
#define VERSION_H
#define VER_FILEVERSION 0,3,0,0
#define VER_FILEVERSION_STR "0.3.0.0\0"
#define VER_PRODUCTVERSION 0,3,0,0
#define VER_PRODUCTVERSION_STR "0.3.0.0\0"
#define VER_COMPANYNAME_STR "IPanera"
#define VER_FILEDESCRIPTION_STR "Localiza archivos duplicados"
#define VER_INTERNALNAME_STR "MyProject"
#define VER_LEGALCOPYRIGHT_STR "Copyright 2016 [email protected]"
#define VER_LEGALTRADEMARKS1_STR "All Rights Reserved"
#define VER_LEGALTRADEMARKS2_STR VER_LEGALTRADEMARKS1_STR
#define VER_ORIGINALFILENAME_STR "MyProject.exe"
#define VER_PRODUCTNAME_STR "My project"
#define VER_COMPANYDOMAIN_STR "www.myurl.com"
#endif // VERSION_H
----[MyProjectVersion.rc]----
#include <windows.h>
#include "version.h"
VS_VERSION_INFO VERSIONINFO
FILEVERSION VER_FILEVERSION
PRODUCTVERSION VER_PRODUCTVERSION
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904E4"
BEGIN
VALUE "CompanyName", VER_COMPANYNAME_STR
VALUE "FileDescription", VER_FILEDESCRIPTION_STR
VALUE "FileVersion", VER_FILEVERSION_STR
VALUE "InternalName", VER_INTERNALNAME_STR
VALUE "LegalCopyright", VER_LEGALCOPYRIGHT_STR
VALUE "LegalTrademarks1", VER_LEGALTRADEMARKS1_STR
VALUE "LegalTrademarks2", VER_LEGALTRADEMARKS2_STR
VALUE "OriginalFilename", VER_ORIGINALFILENAME_STR
VALUE "ProductName", VER_PRODUCTNAME_STR
VALUE "ProductVersion", VER_PRODUCTVERSION_STR
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
If you use log without base it uses e
.
From the comment
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
Therefor you have to use:
import math
print( math.log(1.5, 10))
edit/update: Xcode 8.3.2 • Swift 3.1
If you know HTML and CSS you can use it to easily control the font style, color and size of your attributed string as follow:
extension String {
var html2AttStr: NSAttributedString? {
return try? NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
}
}
"<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>".html2AttStr
I think I found what you are looking for since I was also looking for it.
You have to follow Pawel's steps and then go to the key that is "Cookie". This will open a submenu with all the cookies and it specifies their name, value, domain, etc...
Respectively the values are: Key, Value, Expiration Date, Domain, Path.
This shows all the keys for this domain.
So again to get there:
have you installed a user db2inst2, i think, i remember, that db2inst1 is very administrative
I suggest you create your own list of operator words that you take out of the stopword list. Sets can be conveniently subtracted, so:
operators = set(('and', 'or', 'not'))
stop = set(stopwords...) - operators
Then you can simply test if a word is in
or not in
the set without relying on whether your operators are part of the stopword list. You can then later switch to another stopword list or add an operator.
if word.lower() not in stop:
# use word
Assuming you're running on a Windows machine...
F12
keyScripts
, or Sources
, tab in the developer toolsThen during execution debugging you can do a handful of stepping motions...
F8
Continue: Will continue until the next breakpointF10
Step over: Steps over next function call (won't enter the
library)F11
Step into: Steps into the next function call (will
enter the library)Shift + F11
Step out: Steps out of the current
functionUpdate
After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.
There's no direct idiomatic way to repeat strings in C++ equivalent to the * operator in Python or the x operator in Perl. If you're repeating a single character, the two-argument constructor (as suggested by previous answers) works well:
std::string(5, '.')
This is a contrived example of how you might use an ostringstream to repeat a string n times:
#include <sstream>
std::string repeat(int n) {
std::ostringstream os;
for(int i = 0; i < n; i++)
os << "repeat";
return os.str();
}
Depending on the implementation, this may be slightly more efficient than simply concatenating the string n times.
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
solve this issue for angular
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
Push and Pop make sense in terms of the metaphor of a stack of plates or trays in a cafeteria or buffet, specifically the ones in type of holder that has a spring underneath so the top plate is (more or less... in theory) in the same place no matter how many plates are under it.
If you remove a tray, the weight on the spring is a little less and the stack "pops" up a little, if you put the plate back, it "push"es the stack down. So if you think about the list as a stack and the last element as being on top, then you shouldn't have much confusion.
Try this Using moment.js (Its quite easy to compute date operations in javascript)
firstDate.diff(secondDate, 'days', false);// true|false for fraction value
Result will give you number of days in integer.
Without eval:
Your original string was not an actual string.
jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"
The easiest way to to wrap it all with a single quote.
jsonObj = '"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"'
Then you can combine two steps to parse it to JSON:
$.parseJSON(jsonObj.slice(1,-1))
In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...
@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)
This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...
model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;
May not be the best way, but it does work.
Just for the completeness, we can also avoid declaring private_class_method in a separate line. I personally don't like this usage but good to know that it exists.
private_class_method def self.method_name
....
end
Try this:
foreach (Item item in myItemsList)
{
if (SkipCondition) continue;
// More stuff here
}
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
There are a number of font formats that one can set MIME types for, on both Apache and IIS servers. I've traditionally had luck with the following:
svg as "image/svg+xml" (W3C: August 2011)
ttf as "application/x-font-ttf" (IANA: March 2013)
or "application/x-font-truetype"
otf as "application/x-font-opentype" (IANA: March 2013)
woff as "application/font-woff" (IANA: January 2013)
woff2 as "application/font-woff2" (W3C W./E.Draft: May 2014/March 2016)
eot as "application/vnd.ms-fontobject" (IANA: December 2005)
sfnt as "application/font-sfnt" (IANA: March 2013)
According to the Internet Engineering Task Force who maintain the initial document regarding Multipurpose Internet Mail Extensions (MIME types) here: http://tools.ietf.org/html/rfc2045#section-5 ... it says in specifics:
"It is expected that additions to the larger set of supported types can generally be accomplished by the creation of new subtypes of these initial types. In the future, more top-level types may be defined only by a standards-track extension to this standard. If another top-level type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid a potential conflict with a future official name."
As it were, and over time, additional MIME types get added as standards are created and accepted, therefor we see examples of vendor specific MIME types such as vnd.ms-fontobject and the like.
UPDATE August 16, 2013: WOFF was formally registered at IANA on January 3, 2013 and Webkit has been updated on March 5, 2013 and browsers that are sourcing this update in their latest versions will start issuing warnings about the server MIME types with the old x-font-woff declaration. Since the warnings are only annoying I would recommend switching to the approved MIME type right away. In an ideal world, the warnings will resolve themselves in time.
UPDATE February 26, 2015: WOFF2 is now in the W3C Editor's Draft with the proposed mime-type. It should likely be submitted to IANA in the next year (possibly by end of 2016) following more recent progress timelines. As well SFNT, the scalable/spline container font format used in the backbone table reference of Google Web Fonts with their sfntly java library and is already registered as a mime type with IANA and could be added to this list as well dependent on individual need.
UPDATE October 4, 2017: We can follow the progression of the WOFF2 format here with a majority of modern browsers supporting the format successfully. As well, we can follow the IETF's "font" Top-Level Media Type request for comments (RFC) tracker and document regarding the latest set of proposed font types for approval.
For those wishing to embed the typeface in the proper order in your CSS please visit this article. But again, I've had luck with the following order:
@font-face {
font-family: 'my-web-font';
src: url('webfont.eot');
src: url('webfont.eot?#iefix') format('embedded-opentype'),
url('webfont.woff2') format('woff2'),
url('webfont.woff') format('woff'),
url('webfont.ttf') format('truetype'),
url('webfont.svg#webfont') format('svg');
font-weight: normal;
font-style: normal;
}
For Subversion auto-properties, these can be listed as:
# Font formats
svg = svn:mime-type=image/svg+xml
ttf = svn:mime-type=application/x-font-ttf
otf = svn:mime-type=application/x-font-opentype
woff = svn:mime-type=application/font-woff
woff2 = svn:mime-type=application/font-woff2
eot = svn:mime-type=application/vnd.ms-fontobject
sfnt = svn:mime-type=application/font-sfnt
From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("enable();", null);
} else {
webView.loadUrl("javascript:enable();");
}
Try changing border
to outline
:
outline: 1px solid black;
I think there is another reason for wanting to set java.library.path
. Subversion comes with many libraries and Eclipse won't see these unless java.library.path
can be appended. For example I'm on OS-X, so the libraries are under \opt\subversion\lib
. There are a lot of them and I'd like to keep them where they are (not copy them into a standard lib directory).
Project settings won't fix this.
If you want to use "sudo", example:
sudo git clone [email protected]......... -o heroku
you should also generate ssh key for your root user.
sudo su
cd /root/.ssh
ssh-keygen -t rsa
....
heroku keys:add id_rsa.pub
and it'll work.
if you don't use root user, generate ssh key in your user directory instead.
cd /home/user/.ssh
Sorry if my sentences messed up...
May be some time this also will be helpful
import collections
#Write you select statement here and other things to fetch the data.
if rows:
JArray = []
for row in rows:
JArray2 = collections.OrderedDict()
JArray2["id"]= str(row['id'])
JArray2["Name"]= row['catagoryname']
JArray.append(JArray2)
return json.dumps(JArray)
Example Output:
[
{
"id": 14
"Name": "someName1"
},
{
"id": 15
"Name": "someName2"
}
]
And you can add a max
attribute that will specify the highest possible number that you may insert
<input type="number" max="999" />
if you add both a max
and a min
value you can specify the range of allowed values:
<input type="number" min="1" max="999" />
The above will still not stop a user from manually entering a value outside of the specified range. Instead he will be displayed a popup telling him to enter a value within this range upon submitting the form as shown in this screenshot:
I don't know it's right or not, but it worked for me
def varname(variable):
names = []
for name in list(globals().keys()):
string = f'id({name})'
if id(variable) == eval(string):
names.append(name)
return names[0]
Try with paramter
.....................
.....................
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
{
command.Paramter.Add("@IDNumber",IDNumber)
command.ExecuteNonQuery();
}
.....................
.....................
No need to close connection in using statement
select A, B, 'c' as C
from MyTable
In the previous answer also in the section <selector>...</selector>
you may need:
<item android:state_pressed="true" android:drawable="@drawable/checkbox_pressed" ></item>
Since, String is immutable in Java, so the left and right String have to be copied into the new String for every pair of concatenation. So, better go for the placeholder.
Another way in which this could be achieved is
df['color'] = df.Set.map( lambda x: 'red' if x == 'Z' else 'green')
Example groupBy and sum of a column using Lodash 4.17.4
var data = [{
"name": "jim",
"color": "blue",
"amount": 22
}, {
"name": "Sam",
"color": "blue",
"amount": 33
}, {
"name": "eddie",
"color": "green",
"amount": 77
}];
var result = _(data)
.groupBy(x => x.color)
.map((value, key) =>
({color: key,
totalamount: _.sumBy(value,'amount'),
users: value})).value();
console.log(result);
It's simple. Suppose you want to move from A to C
if there's only one disk, just move it.
If there's more than one disk, do
Keep in mind that, when moving the n-1 disks, the nth won't be a problem at all (once it is bigger than all the others)
Note that moving the n-1 disks recurs on the same problem again, until n-1 = 1, in which case you'll be on the first if (where you should just move it).
I had a similar use case during testing hibernate event listeners which are only called on commit.
The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW
. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.
Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.
I like this approach
my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)
Note the appended d and s to the brackets respectively.
output will be:
I scored 3 goals and took 5 penalties
Well another way :)
md5=`md5sum ${my_iso_file} | awk '{ print $1 }'`
I have recently done something similar to this using the "Haversine Formula" on WGS-84 data, which is a derivative of the "Law of Haversines" with very satisfying results.
Yes, WGS-84 assumes the Earth is an ellipsoid, but I believe you only get about a 0.5% average error using an approach like the "Haversine Formula", which may be an acceptable amount of error in your case. You will always have some amount of error unless you're talking about a distance of a few feet and even then there is theoretically curvature of the Earth... If you require a more rigidly WGS-84 compatible approach checkout the "Vincenty Formula."
I understand where starblue is coming from, but good software engineering is often about trade-offs, so it all depends on the accuracy you require for what you are doing. For example, the result calculated from "Manhattan Distance Formula" versus the result from the "Distance Formula" can be better for certain situations as it is computationally less expensive. Think "which point is closest?" scenarios where you don't need a precise distance measurement.
Regarding, the "Haversine Formula" it is easy to implement and is nice because it is using "Spherical Trigonometry" instead of a "Law of Cosines" based approach which is based on two-dimensional trigonometry, therefore you get a nice balance of accuracy over complexity.
A gentleman by the name of Chris Veness has a great website that explains some of the concepts you are interested in and demonstrates various programmatic implementations; this should answer your x/y conversion question as well.
Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than
customer_id INT( 4 ) NOT NULL ,
make it
customer_id INT( 10 ) NOT NULL ,
and make sure your int column in the customers table is int(10) also.
Dherik : I'm not sure about what you say, when you don't use fetch the result will be of type : List<Object[ ]>
which means a list of Object tables and not a list of Employee.
Object[0] refers an Employee entity
Object[1] refers a Departement entity
When you use fetch, there is just one select and the result is the list of Employee List<Employee>
containing the list of departements. It overrides the lazy declaration of the entity.
This is from my xamarin.forms code, the class derives from NavigationRenderer
NavigationBar.Items.FirstOrDefault().BackBarButtonItem = new UIBarButtonItem( "", UIBarButtonItemStyle.Plain, null);
If nothing helps, look for some uni-code characters like
\u2028
this may break your string on more than one line and throw this error
I customized more @Suragch code. My output looks
I wrote a method to stop code redundancy.
public TextView createATextView(int layout_widh, int layout_height, int align,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}
It can be called like
createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
subTotal.toString(), 20, 10, 20);
Now you can add this to a RelativeLayout dynamically. LinearLayout is also same, just add a orientation.
RelativeLayout primary_layout = new RelativeLayout(this);
LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
primary_layout.setLayoutParams(layoutParam);
// FOR LINEAR LAYOUT SET ORIENTATION
// primary_layout.setOrientation(LinearLayout.HORIZONTAL);
// FOR BACKGROUND COLOR
primary_layout.setBackgroundColor(0xff99ccff);
primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i],
20, 10, 20));
primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
subTotal.toString(), 20, 10, 20));
if you want to scroll just only some div, can use the div id instead of 'html, body'
$('html, body').animate(...
use
$('#mydivid').animate(...
Lets Experiment with below code Playground.I Hope will clear idea what is optional and reason of using it.
var sampleString: String? ///Optional, Possible to be nil
sampleString = nil ////perfactly valid as its optional
sampleString = "some value" //Will hold the value
if let value = sampleString{ /// the sampleString is placed into value with auto force upwraped.
print(value+value) ////Sample String merged into Two
}
sampleString = nil // value is nil and the
if let value = sampleString{
print(value + value) ///Will Not execute and safe for nil checking
}
// print(sampleString! + sampleString!) //this line Will crash as + operator can not add nil
Simply type the following command on the command line inside the virtual environment:
deactivate
You can do by the following ways
this.your_form.getRawValue()['formcontrolname]
this.your_form.value['formcontrolname]
Based on Mohammed Radwan's answer I came up with the following jQuery solution. Basically what it does is keep track of what iFrame people are hovering. Then if the window blurs that most likely means the user clicked the iframe banner.
the iframe should be put in a div with an id, to make sure you know which iframe the user clicked on:
<div class='banner' bannerid='yyy'>
<iframe src='http://somedomain.com/whatever.html'></iframe>
<div>
so:
$(document).ready( function() {
var overiFrame = -1;
$('iframe').hover( function() {
overiFrame = $(this).closest('.banner').attr('bannerid');
}, function() {
overiFrame = -1
});
... this keeps overiFrame at -1 when no iFrames are hovered, or the 'bannerid' set in the wrapping div when an iframe is hovered. All you have to do is check if 'overiFrame' is set when the window blurs, like so: ...
$(window).blur( function() {
if( overiFrame != -1 )
$.post('log.php', {id:overiFrame}); /* example, do your stats here */
});
});
Very elegant solution with a minor downside: if a user presses ALT-F4 when hovering the mouse over an iFrame it will log it as a click. This only happened in FireFox though, IE, Chrome and Safari didn't register it.
Thanks again Mohammed, very useful solution!
The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):
Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.
For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.
These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '
), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "
), or (iv) unquoted — with the following restrictions:
... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.