Here's the correct way to do it with modern (2014) JQuery:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.appendTo('head');
})
or if you really want to replace a div you could do:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.replaceAll('#someelement');
});
Try this method to convert a 'string that could potentially contain html code' to 'text format':
$msg = "<div></div>";
$safe_msg = htmlspecialchars($msg, ENT_QUOTES);
echo $safe_msg;
Hope this helps!
Don't apply these properties to the whole body. Move them to a class and apply that class to the elements you want to disable select:
.disable-select {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
It has nothing to do with jQuery, it's just a handy js method built into modern browsers.
Think of it as a handy alternative to debugging via window.alert()
Highlighting with your mouse only highlights characters on the terminal. VI doesn't really get this information, so you have to highlight differently.
Press 'v' to enter a select mode, and use arrow keys to move that around. To delete, press x. To select lines at a time, press shift+v. To select blocks, try ctrl+v. That's good for, say, inserting lots of comment lines in front of your code :).
I'm OK with VI, but it took me a while to improve. My work mates recommended me this cheat sheet. I keep a printout on the wall for those odd moments when I forget something.
Happy hacking!
short answer, specific to OAuth2,
Support for OFFSET and LIMIT was recently added to DB2 for i 7.1 and 7.2. You need the following DB PTF group levels to get this support:
See here for more information: OFFSET and LIMIT documentation, DB2 for i Enhancement Wiki
I've spent a great deal of time to figure out why the log4j.properties file is not seen.
Then I noticed it was visible for the project only when it was in both MyProject/target/classes/ and MyProject/src/main/resources folders.
Hope it'll be useful to somebody.
PS: The project was maven-based.
If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;
The above decriptions will result different Date values, if you run with EST or UTC timezones.
To set the timezone; aka to UTC, you can simply rewrite;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));
Yay recursion!
def trunc(s,l):
if l > 0:
return s[:l] + trunc(s, l - len(s))
return ''
Won't scale forever, but it's fine for smaller strings. And it's pretty.
I admit I just read the Little Schemer and I like recursion right now.
We can have this in 2 ways,
Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within
ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons
Or
Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code
if (Request.Form["btnSubmit1"] != null)
{
//
}
if (Request.Form["btnSubmit2"] != null)
{
//
}
Double.parseDouble(p.replace(',','.'))
...is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.
Basically replace(char,char) is about 10 times quicker and since you'll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out... Certainly doesn't on my system.
I would like to offer a minor improvement on the last loop answer given in the previous post (that post is correct and should still be accepted). The implicit assumption made when labeling the last example is that plt.label(LIST)
puts label number X in LIST
with the line corresponding to the Xth time plot
was called. I have run into problems with this approach before. The recommended way to build legends and customize their labels per matplotlibs documentation ( http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item) is to have a warm feeling that the labels go along with the exact plots you think they do:
...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
plotHandles.append(x)
labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)
http://jsfiddle.net/adiioo7/vmfbA/
Use
document.body.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
instead of
document.body.innerHTML = '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
Edit:-
Ideally you should use body.appendChild
method instead of changing the innerHTML
var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);
Getting a stack trace from a running Python application
There are several tricks here. These include
When you are in a custom View, you can use getDimensionPixelSize(R.dimen.dimen_value)
, in my case, I added the margin in LayoutParams created on init
method.
In Kotlin
init {
LayoutInflater.from(context).inflate(R.layout.my_layout, this, true)
layoutParams = LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
val margin = resources.getDimensionPixelSize(R.dimen.dimen_value)
setMargins(0, margin, 0, margin)
}
in Java:
public class CustomView extends LinearLayout {
//..other constructors
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
int margin = getResources().getDimensionPixelSize(R.dimen.spacing_dime);
params.setMargins(0, margin, 0, margin);
setLayoutParams(params);
}
}
Put a breakpoint in your code at a somewhere close to a reference to the $scope variable (so that the $scope is in the current 'plain old JavaScript' scope). Then your can inspect the $scope value in the console.
Simply use this math function
System.out.println(Math.min(a,b,c));
You will get the answer in single line.
the problem mainly is because the width have to be == to the height, and in the case of bs, the height is set to auto so here is a fix for that in js instead
function img_circle() {
$('.img-circle').each(function() {
$w = $(this).width();
$(this).height($w);
});
}
$(document).ready(function() {
img_circle();
});
$(window).resize(function() {
img_circle();
});
Excel 2007+ is limited to somewhat over 1 million rows ( 2^20 to be precise), so it will never load your 2M line file. I think that the technique you refer to as splitting is the built-in thing Excel has, but afaik that only works for width problems, not for length problems.
The really easiest way I see right away is to use some file splitting tool - there's tons of 'em and use that to load the resulting partial csv files into multiple worksheets.
ps: "excel csv files" don't exist, there are only files produced by Excel that use one of the formats commonly referred to as csv files...
If you're simply looking for a way to display it, you could use describe():
grp = df.groupby['colName']
grp.describe()
This gives you a neat table.
Looks like you want git diff and/or git log. Also check out gitk
gitk path/to/file
git diff path/to/file
git log path/to/file
Run it not through Visual Studio - then the icon should look just fine.
I believe it is because when you debug, Visual Studio runs <yourapp>.vshost.exe
and not your application. The .vshost.exe file doesn't use your icon.
Ultimately, what you have done is correct.
There, the icon should look fine. If you run it by clicking that .exe the icon should be correct in the application as well.
Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.
inside templateHTML.html:
<form action="#" method="get">
<input type="text" value="8" name="mytextbox" size="1"/>
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
inside view.py:
import mypythoncode
def request_page(request):
if(request.GET.get('mybtn')):
mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')
Use:
select * from mytest
EXEC sp_rename 'mytest.eid', 'id', 'COLUMN'
alter table mytest add id int not null identity(1,1)
update mytset set eid=id
ALTER TABLE mytest DROP COLUMN eid
ALTER TABLE [dbo].[yourtablename] ADD DEFAULT (getdate()) FOR [yourfieldname]
It's working 100%.
Another option is to make the Bootstrap dropdown behave like a select using jQuery...
$(".dropdown-menu li a").click(function(){
var selText = $(this).text();
$(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
});
Use setResizable on your JFrame
yourFrame.setResizable(false);
But extending JFrame is generally a bad idea.
Definitely late to the party; anyway, for those interested, picking up on Lan's mention of HTML5 canvas, you can use gRaphaël Charting which has a MIT License (instead of HighCharts dual license). It's not Bootstrap-specific either, so it's more of a general suggestion.
I have to admit that HighCharts demos seem very pretty, and I have to warn that gRaphaël is quite hard to understand before becoming proficient with it. Anyway you can easily add nice features to your gRaphaël charts (say, tooltips or zooming effects), so it may be worth the effort.
I agree with the last answer.But there is another way to solve this problem.You can download the package named future,such as pip install future.And in your .py file input this "from past.builtins import xrange".This method is for the situation that there are many xranges in your file.
If you want to submit a POST request
Content-Type
” and “value” = “application/x-www-form-urlencoded
”name=mynamehere&title=TA
” in the “request body” text area fieldAs has been said, datetime has no format/string representational format.
You can change the string output with some formatting.
To convert your string to a datetime:
declare @date nvarchar(25)
set @date = '2011-09-28 18:01:00'
-- To datetime datatype
SELECT CONVERT(datetime, @date)
Gives:
-----------------------
2011-09-28 18:01:00.000
(1 row(s) affected)
To convert that to the string you want:
-- To VARCHAR of your desired format
SELECT CONVERT(VARCHAR(10), CONVERT(datetime, @date), 105) +' '+ CONVERT(VARCHAR(8), CONVERT(datetime, @date), 108)
Gives:
-------------------
28-09-2011 18:01:00
(1 row(s) affected)
More recent versions have a different syntax:
var table = $('#example').DataTable();
// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
table.search(this.value).draw();
});
Note that this example uses the variable table
assigned when datatables is first initialised. If you don't have this variable available, simply use:
var table = $('#example').dataTable().api();
// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
table.search(this.value).draw();
});
Since: DataTables 1.10
I have a blog and I had a lot of trouble finding out how to resize my embedded gist. Post manager only allows you to write text, place images and embed HTML code. Blog layout is responsive itself. It's built with Wix. However, embedded HTML is not. I read a lot about how it's impossible to resize components inside body of generated iFrames. So, here is my suggestion:
If you only have one component inside your iFrame, i.e. your gist, you can resize only the gist. Forget about the iFrame.
I had problems with viewport, specific layouts to different user agents and this is what solved my problem:
<script language="javascript" type="text/javascript" src="https://gist.github.com/roliveiravictor/447f994a82238247f83919e75e391c6f.js"></script>
<script language="javascript" type="text/javascript">
function windowSize() {
let gist = document.querySelector('#gist92442763');
let isMobile = {
Android: function() {
return /Android/i.test(navigator.userAgent)
},
BlackBerry: function() {
return /BlackBerry/i.test(navigator.userAgent)
},
iOS: function() {
return /iPhone|iPod/i.test(navigator.userAgent)
},
Opera: function() {
return /Opera Mini/i.test(navigator.userAgent)
},
Windows: function() {
return /IEMobile/i.test(navigator.userAgent) || /WPDesktop/i.test(navigator.userAgent)
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
if(isMobile.any()) {
gist.style.width = "36%";
gist.style.WebkitOverflowScrolling = "touch"
gist.style.position = "absolute"
} else {
gist.style.width = "auto !important";
}
}
windowSize();
window.addEventListener('onresize', function() {
windowSize();
});
</script>
<style type="text/css">
.gist-data {
max-height: 300px;
}
.gist-meta {
display: none;
}
</style>
The logic is to set gist (or your component) css based on user agent. Make sure to identify your component first, before applying to query selector. Feel free to take a look how responsiveness is working.
First, I changed the script to do some more benchmarking (and also do 1000 runs instead of just 1):
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Make a big, honkin test array
// You may need to adjust this depth to avoid memory limit errors
$testArray = fillArray(0, 5);
$totalJsonTime = 0;
$totalSerializeTime = 0;
$totalJsonWins = 0;
for ($i = 0; $i < 1000; $i++) {
// Time json encoding
$start = microtime(true);
$json = json_encode($testArray);
$jsonTime = microtime(true) - $start;
$totalJsonTime += $jsonTime;
// Time serialization
$start = microtime(true);
$serial = serialize($testArray);
$serializeTime = microtime(true) - $start;
$totalSerializeTime += $serializeTime;
if ($jsonTime < $serializeTime) {
$totalJsonWins++;
}
}
$totalSerializeWins = 1000 - $totalJsonWins;
// Compare them
if ($totalJsonTime < $totalSerializeTime) {
printf("json_encode() (wins: $totalJsonWins) was roughly %01.2f%% faster than serialize()\n", ($totalSerializeTime / $totalJsonTime - 1) * 100);
} else {
printf("serialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than json_encode()\n", ($totalJsonTime / $totalSerializeTime - 1) * 100);
}
$totalJsonTime = 0;
$totalJson2Time = 0;
$totalSerializeTime = 0;
$totalJsonWins = 0;
for ($i = 0; $i < 1000; $i++) {
// Time json decoding
$start = microtime(true);
$orig = json_decode($json, true);
$jsonTime = microtime(true) - $start;
$totalJsonTime += $jsonTime;
$start = microtime(true);
$origObj = json_decode($json);
$jsonTime2 = microtime(true) - $start;
$totalJson2Time += $jsonTime2;
// Time serialization
$start = microtime(true);
$unserial = unserialize($serial);
$serializeTime = microtime(true) - $start;
$totalSerializeTime += $serializeTime;
if ($jsonTime < $serializeTime) {
$totalJsonWins++;
}
}
$totalSerializeWins = 1000 - $totalJsonWins;
// Compare them
if ($totalJsonTime < $totalSerializeTime) {
printf("json_decode() was roughly %01.2f%% faster than unserialize()\n", ($totalSerializeTime / $totalJsonTime - 1) * 100);
} else {
printf("unserialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than json_decode()\n", ($totalJsonTime / $totalSerializeTime - 1) * 100);
}
// Compare them
if ($totalJson2Time < $totalSerializeTime) {
printf("json_decode() was roughly %01.2f%% faster than unserialize()\n", ($totalSerializeTime / $totalJson2Time - 1) * 100);
} else {
printf("unserialize() (wins: $totalSerializeWins) was roughly %01.2f%% faster than array json_decode()\n", ($totalJson2Time / $totalSerializeTime - 1) * 100);
}
function fillArray( $depth, $max ) {
static $seed;
if (is_null($seed)) {
$seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10);
}
if ($depth < $max) {
$node = array();
foreach ($seed as $key) {
$node[$key] = fillArray($depth + 1, $max);
}
return $node;
}
return 'empty';
}
I used this build of PHP 7:
PHP 7.0.14 (cli) (built: Jan 18 2017 19:13:23) ( NTS ) Copyright (c) 1997-2016 The PHP Group Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies with Zend OPcache v7.0.14, Copyright (c) 1999-2016, by Zend Technologies
And my results were:
serialize() (wins: 999) was roughly 10.98% faster than json_encode() unserialize() (wins: 987) was roughly 33.26% faster than json_decode() unserialize() (wins: 987) was roughly 48.35% faster than array json_decode()
So clearly, serialize/unserialize is the fastest method, while json_encode/decode is the most portable.
If you consider a scenario where you read/write serialized data 10x or more often than you need to send to or receive from a non-PHP system, you are STILL better off to use serialize/unserialize and have it json_encode or json_decode prior to serialization in terms of time.
pretty old topic but this is maybe a help for someone searching for the problem where the above tips does not solved it.
I use
git credential-manager remove -force
We want to add it because we are making a class library that uses it.
For me it is here...
C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies
After login I had the same problem so I used
@Override
protected void onRestart() {
this.recreate();
super.onRestart();
}
Think of it this way, the "Public API Key" is similar to a user name that your database is using as a login to a verification server. The "Private API Key" would then be similar to the password. By the site/databse using this method, the security is maintained on the third party/verification server in order to authentic request of posting or editing your site/database.
The API string is just the URL of the login for your site/database to contact the verification server.
I just resolved this problem with a little hack:
static int s_CellHeight = 30;
static int s_CellHeightEditing = 60;
- (void)onTimer {
cellHeight++;
[tableView reloadData];
if (cellHeight < s_CellHeightEditing)
heightAnimationTimer = [[NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(onTimer) userInfo:nil repeats:NO] retain];
}
- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (isInEdit) {
return cellHeight;
}
cellHeight = s_CellHeight;
return s_CellHeight;
}
When I need to expand the cell height I set isInEdit = YES
and call the method [self onTimer]
and it animates the cell growth until it reach the s_CellHeightEditing value :-)
Works GReat.
Category Question Apple Banana Cherry<input type="text" name="cat_q" id="cat_q">
$(document).ready(function(){
$("#btn_cat div a").click(function(){
alert($(this).text());
});
});
1) First you need to generate EDMX
model using your database. To do that you should add new item to your project:
ADO.NET Entity Data Model
from the Templates list. So now you have Model1.edmx
file in your project.
2) To generate classes using your model:
EDMX
model designer.EF 4.x DbContext Generator for C#
.Notice that two items are added to your project:
Model1.tt
(This template generates very simple POCO classes for each entity in your model) Model1.Context.tt
(This template generates a derived DbContext to use for querying and persisting data)3) Read/Write Data example:
var dbContext = new YourModelClass(); //class derived from DbContext
var contacts = from c in dbContext.Contacts select c; //read data
contacts.FirstOrDefault().FirstName = "Alex"; //edit data
dbContext.SaveChanges(); //save data to DB
Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.
C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.
reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.
static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.
dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.
There are a couple of others but these are the main ones you will come across.
To make mode, controllers with resources, You can type CMD as follows :
php artisan make:model Todo -mcr
or you can check by typing
php artisan help make:model
where you can get all the ideas
Sliding from the right:
$('#example').animate({width:'toggle'},350);
Sliding to the left:
$('#example').toggle({ direction: "left" }, 1000);
If you are using variables with the same name as your column, it could be that you forgot the '@' variable marker. In an INSERT statement it will be detected as a column.
If you don't want to add any code to the form (as mentioned in the comments to @shadfc's Answer), it is certainly possible, here are two options.
First, you just reference the fields individually in the HTML, rather than the entire form at once:
<form action="" method="post">
<ul class="contactList">
<li id="subject" class="contact">{{ form.subject }}</li>
<li id="email" class="contact">{{ form.email }}</li>
<li id="message" class="contact">{{ form.message }}</li>
</ul>
<input type="submit" value="Submit">
</form>
(Note that I also changed it to a unsorted list.)
Second, note in the docs on outputting forms as HTML, Django:
The Field id, is generated by prepending 'id_' to the Field name. The id attributes and tags are included in the output by default.
All of your form fields already have a unique id. So you would reference id_subject in your CSS file to style the subject field. I should note, this is how the form behaves when you take the default HTML, which requires just printing the form, not the individual fields:
<ul class="contactList">
{{ form }} # Will auto-generate HTML with id_subject, id_email, email_message
{{ form.as_ul }} # might also work, haven't tested
</ul>
See the previous link for other options when outputting forms (you can do tables, etc).
Note - I realize this isn't the same as adding a class to each element (if you added a field to the Form, you'd need to update the CSS also) - but it's easy enough to reference all of the fields by id in your CSS like this:
#id_subject, #id_email, #email_message
{color: red;}
My favorite way is called do the sleep to 50. here i
variable need to be used inside echo statements.
for i in $(seq 1 50); do
echo -ne "$i%\033[0K\r"
sleep 50
done
echo "ended"
Install an interval:
<script type="text/javascript">
setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>
When I was trying to accomplish something very similar, I ended up doing something along these lines:
wp-content/themes/resources/functions.php
add_action('init', 'my_php_function');
function my_php_function() {
if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
// add desired php code here
}
}
I haven't managed to get WMDC working on Windows 10 (it hanged on splash screen upon start), so I've finally uninstalled it. But now I have a Portable Devices / Compact device in the Device Manager and I can browse my Windows Compact 7 device within Windows Explorer. All my apps using RAPI also work. Maybe this is the result of installing/uninstalling WMDC, or probably this functionality was already presented on Windows 10 and I've just overlooked it initially.
here is a quick implement, i used it to get a 'Matrix'(sruct) from a string. you can have a bigger array and change its values on the run also:
typedef struct { int** lines; int isDefined; }mat;
mat matA, matB, matC, matD, matE, matF;
/* an auxilary struct to be used in a dictionary */
typedef struct { char* str; mat *matrix; }stringToMat;
/* creating a 'dictionary' for a mat name to its mat. lower case only! */
stringToMat matCases [] =
{
{ "mat_a", &matA },
{ "mat_b", &matB },
{ "mat_c", &matC },
{ "mat_d", &matD },
{ "mat_e", &matE },
{ "mat_f", &matF },
};
mat* getMat(char * str)
{
stringToMat* pCase;
mat * selected = NULL;
if (str != NULL)
{
/* runing on the dictionary to get the mat selected */
for(pCase = matCases; pCase != matCases + sizeof(matCases) / sizeof(matCases[0]); pCase++ )
{
if(!strcmp( pCase->str, str))
selected = (pCase->matrix);
}
if (selected == NULL)
printf("%s is not a valid matrix name\n", str);
}
else
printf("expected matrix name, got NULL\n");
return selected;
}
no it will not call destructor for class A, you should call it explicitly (like PoweRoy told), delete line 'delete ptr;' in example to compare ...
#include <iostream>
class A
{
public:
A(){};
~A();
};
A::~A()
{
std::cout << "Destructor of A" << std::endl;
}
class B
{
public:
B(){ptr = new A();};
~B();
private:
A* ptr;
};
B::~B()
{
delete ptr;
std::cout << "Destructor of B" << std::endl;
}
int main()
{
B* b = new B();
delete b;
return 0;
}
.C
and .cc
seem to be standard for the (few) Unix-oriented C++ programs I've seen. I've always used .cpp
myself, since I only really work on Windows and that's been the standard there since like forever.
I recommend .cpp
personally, because... it stands for "C Plus Plus". It is of course vitally important that file extensions are acronyms, but should this rationale prove insufficiently compelling other important things are non-use of the shift key (which rules out .C
and .c++
) and avoidance of regular expression metacharacters where possible (which rules out .c++
-- unfortunately you can't really avoid the .
of course.).
This doesn't rule out .cc
, so even though it doesn't really stand for anything (or does it?) it is probably a good choice for Linux-oriented code.
This is work for me: Drwable->New->Drawable Resource File->create xml file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#e0e0e0" />
<stroke android:width="2dp" android:color="#a4b0ba" />
</shape>
As mentioned above BOOL
could be an unsigned char
type depending on your architecture, while bool
is of type int
. A simple experiment will show the difference why BOOL and bool can behave differently:
bool ansicBool = 64;
if(ansicBool != true) printf("This will not print\n");
printf("Any given vlaue other than 0 to ansicBool is evaluated to %i\n", ansicBool);
BOOL objcBOOL = 64;
if(objcBOOL != YES) printf("This might print depnding on your architecture\n");
printf("BOOL will keep whatever value you assign it: %i\n", objcBOOL);
if(!objcBOOL) printf("This will not print\n");
printf("! operator will zero objcBOOL %i\n", !objcBOOL);
if(!!objcBOOL) printf("!! will evaluate objcBOOL value to %i\n", !!objcBOOL);
To your surprise if(objcBOOL != YES)
will evaluates to 1 by the compiler, since YES
is actually the character code 1, and in the eyes of compiler, character code 64 is of course not equal to character code 1 thus the if statement will evaluate to YES/true/1
and the following line will run.
However since a none zero bool
type always evaluates to the integer value of 1, the above issue will not effect your code. Below are some good tips if you want to use the Objective-C BOOL
type vs the ANSI C bool
type:
YES
or NO
value and nothing else.BOOL
types by using double not !!
operator to avoid unexpected results.YES
use if(!myBool) instead of if(myBool != YES)
it is much cleaner to use the not !
operator and gives the expected result.As already mentioned, there are a few ways to achieve this with possibly the safest method being call_user_func()
or if you must you can also go down the route of $function_name()
. It is possible to pass arguments using both of these methods as so
$function_name = 'foobar';
$function_name(arg1, arg2);
call_user_func_array($function_name, array(arg1, arg2));
If the function you are calling belongs to an object you can still use either of these
$object->$function_name(arg1, arg2);
call_user_func_array(array($object, $function_name), array(arg1, arg2));
However if you are going to use the $function_name()
method it may be a good idea to test for the existence of the function if the name is in any way dynamic
if(method_exists($object, $function_name))
{
$object->$function_name(arg1, arg2);
}
This is possible with simple JavaScript.
window.frames
syntax to fire a JavaScript function in iframe2. Just make sure to use the id
/name
of iframe2 and not the src
.//function in iframe1
function refreshIframe2()
{
if (<cfoutput>#didValidation#</cfoutput> == 1)
{
parent.window.frames.iframe2.refreshPage();
}
}
//function in iframe2
function refreshPage()
{
document.location.reload();
}
As pointed out by @Jason, for most shared hosting environments, having a copy of php.ini file in your public_html directory works to override the system default settings. A great way to do this is by copying the hosting company's copy. Put this in a file, say copyini.php
<?php
system("cp /path/to/php/conf/file/php.ini /home/yourusername/public_html/php.ini");
?>
Get /path/to/php/conf/file/php.ini from the output of phpinfo(); in a file. Then in your ini file, make your amendments Delete all files created during this process (Apart from php.ini of course :-) )
Visual Studio Code market place has a very nice extension named Go To Method for navigating only methods in a code file.
Hit Ctrl+Shift+P and type the install extensions
and press enter
Now type Add to method
in search box of extensions market place and press enter.
Click install to install the extension.
Last step is to bind a keyboard shortcut to the command workbench.action.gotoMethod
to make it a real productivity thing for a developer.
In Oracle 12c, you can now specify the CURRVAL and NEXTVAL sequence pseudocolumns as default values for a column. Alternatively, you can use Identity columns; see:
E.g.,
CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
id NUMBER DEFAULT t1_seq.NEXTVAL,
description VARCHAR2(30)
);
Create a table for a demo:
CREATE TABLE your_table(
thekey integer NOT NULL, ticker character varying(10) NOT NULL,
date_val date, open_val numeric(10,4) NOT NULL
);
pg_dump can output the table-create psql:
pg_dump -U your_user your_database -t your_table --schema-only
Which prints:
-- pre-requisite database and table configuration omitted
CREATE TABLE your_table (
thekey integer NOT NULL,
ticker character varying(10) NOT NULL,
date_val date,
open_val numeric(10,4) NOT NULL
);
-- post-requisite database and table configuration omitted
Explanation:
pg_dump helps us get information about the database itself. -U
stands for username. My pgadmin user has no password set, so I don't have to put in a password. The -t
option means specify for one table. --schema-only
means print only data about the table, and not the data in the table. Here is the exact command I use:
CREATE TABLE your_table( thekey integer NOT NULL,
ticker character varying(10) NOT NULL,
date_val date,
open_val numeric(10,4) NOT NULL
);
SELECT table_name, column_name, data_type
FROM information_schema.columns
WHERE table_name = 'your_table';
Which prints:
+----------------------------------------------+
¦ table_name ¦ column_name ¦ data_type ¦
+------------+-------------+-------------------¦
¦ your_table ¦ thekey ¦ integer ¦
¦ your_table ¦ ticker ¦ character varying ¦
¦ your_table ¦ date_val ¦ date ¦
¦ your_table ¦ open_val ¦ numeric ¦
+----------------------------------------------+
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
I think what are attempting is semantically same as a radio button when 1 is when one of the options is selected and 0 is the other option.
I suggest using the radio button provided by Android by default.
Here is how to use it- http://www.mkyong.com/android/android-radio-buttons-example/
and the android documentation is here-
http://developer.android.com/guide/topics/ui/controls/radiobutton.html
Thanks.
In case of complex ProgressBar
like this,
use ClipDrawable
.
NOTE : I've not used
ProgressBar
here in this example. I've achieved this using ClipDrawable by clipping image withAnimation
.
A Drawable
that clips another Drawable
based on this Drawable
's current level value. You can control how much the child Drawable
gets clipped in width and height based on the level, as well as a gravity to control where it is placed in its overall container. Most often used to implement things like progress bars
, by increasing the drawable's level with setLevel()
.
NOTE : The drawable is clipped completely and not visible when the level is 0 and fully revealed when the level is 10,000.
I've used this two images to make this CustomProgressBar
.
scall.png
ballon_progress.png
MainActivity.java
public class MainActivity extends ActionBarActivity {
private EditText etPercent;
private ClipDrawable mImageDrawable;
// a field in your class
private int mLevel = 0;
private int fromLevel = 0;
private int toLevel = 0;
public static final int MAX_LEVEL = 10000;
public static final int LEVEL_DIFF = 100;
public static final int DELAY = 30;
private Handler mUpHandler = new Handler();
private Runnable animateUpImage = new Runnable() {
@Override
public void run() {
doTheUpAnimation(fromLevel, toLevel);
}
};
private Handler mDownHandler = new Handler();
private Runnable animateDownImage = new Runnable() {
@Override
public void run() {
doTheDownAnimation(fromLevel, toLevel);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etPercent = (EditText) findViewById(R.id.etPercent);
ImageView img = (ImageView) findViewById(R.id.imageView1);
mImageDrawable = (ClipDrawable) img.getDrawable();
mImageDrawable.setLevel(0);
}
private void doTheUpAnimation(int fromLevel, int toLevel) {
mLevel += LEVEL_DIFF;
mImageDrawable.setLevel(mLevel);
if (mLevel <= toLevel) {
mUpHandler.postDelayed(animateUpImage, DELAY);
} else {
mUpHandler.removeCallbacks(animateUpImage);
MainActivity.this.fromLevel = toLevel;
}
}
private void doTheDownAnimation(int fromLevel, int toLevel) {
mLevel -= LEVEL_DIFF;
mImageDrawable.setLevel(mLevel);
if (mLevel >= toLevel) {
mDownHandler.postDelayed(animateDownImage, DELAY);
} else {
mDownHandler.removeCallbacks(animateDownImage);
MainActivity.this.fromLevel = toLevel;
}
}
public void onClickOk(View v) {
int temp_level = ((Integer.parseInt(etPercent.getText().toString())) * MAX_LEVEL) / 100;
if (toLevel == temp_level || temp_level > MAX_LEVEL) {
return;
}
toLevel = (temp_level <= MAX_LEVEL) ? temp_level : toLevel;
if (toLevel > fromLevel) {
// cancel previous process first
mDownHandler.removeCallbacks(animateDownImage);
MainActivity.this.fromLevel = toLevel;
mUpHandler.post(animateUpImage);
} else {
// cancel previous process first
mUpHandler.removeCallbacks(animateUpImage);
MainActivity.this.fromLevel = toLevel;
mDownHandler.post(animateDownImage);
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/etPercent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="number"
android:maxLength="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:onClick="onClickOk" />
</LinearLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<ImageView
android:id="@+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/scall" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/clip_source" />
</FrameLayout>
clip_source.xml
<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
android:clipOrientation="vertical"
android:drawable="@drawable/ballon_progress"
android:gravity="bottom" />
In case of complex HorizontalProgressBar
just change cliporientation
in clip_source.xml like this,
android:clipOrientation="horizontal"
You can download complete demo from here.
Programmatically in Java - At least API v14+
exampleEditText.setHintTextColor(getResources().getColor(R.color.your_color));
Have you seen CAT.NET?
From the blurb -
CAT.NET is a binary code analysis tool that helps identify common variants of certain prevailing vulnerabilities that can give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL Injection and XPath Injection.
I used an early beta and it did seem to turn up a few things worth looking at.
int is a primitive type and not an object. That means that there are no methods associated with it. Integer is an object with methods (such as parseInt).
With newer java there is functionality for auto boxing (and unboxing). That means that the compiler will insert Integer.valueOf(int) or integer.intValue() where needed. That means that it is actually possible to write
Integer n = 9;
which is interpreted as
Integer n = Integer.valueOf(9);
I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like
$redis->set('persons', $persons)
Later I decided to change to "hSet" method, and I tried it this way
foreach($persons as $person){
$redis->hSet('persons', $person->id, $person);
}
Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with
del persons
It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.
My solution is in function getRoman:
public String getRoman(int number) {
String riman[] = {"M","XM","CM","D","XD","CD","C","XC","L","XL","X","IX","V","IV","I"};
int arab[] = {1000, 990, 900, 500, 490, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
StringBuilder result = new StringBuilder();
int i = 0;
while (number > 0 || arab.length == (i - 1)) {
while ((number - arab[i]) >= 0) {
number -= arab[i];
result.append(riman[i]);
}
i++;
}
return result.toString();
}
I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size
Try
=IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))
Now incorporate your left
argument
=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))
Also note your usage of left, your argument doesn't specify the number of characters, but a set.
7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet
, but I rather link to official sources.
A "table" in Excel is indeed known as a ListObject.
The "proper" way to reference a table is by getting its ListObject from its Worksheet i.e. SheetObject.ListObjects(ListObjectName)
.
If you want to reference a table without using the sheet, you can use a hack Application.Range(ListObjectName).ListObject
.
NOTE: This hack relies on the fact that Excel always creates a named range for the table's DataBodyRange with the same name as the table. However this range name can be changed...though it's not something you'd want to do since the name will reset if you edit the table name! Also you could get a named range with no associated ListObject.
Given Excel's not-very-helpful 1004 error message when you get the name wrong, you may want to create a wrapper...
Public Function GetListObject(ByVal ListObjectName As String, Optional ParentWorksheet As Worksheet = Nothing) As Excel.ListObject
On Error Resume Next
If (Not ParentWorksheet Is Nothing) Then
Set GetListObject = ParentWorksheet.ListObjects(ListObjectName)
Else
Set GetListObject = Application.Range(ListObjectName).ListObject
End If
On Error GoTo 0 'Or your error handler
If (Not GetListObject Is Nothing) Then
'Success
ElseIf (Not ParentWorksheet Is Nothing) Then
Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found on sheet '" & ParentWorksheet.Name & "'!")
Else
Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found!")
End If
End Function
Also some good ListObject info here.
if you need to change specific option from the select menu you can do it like this
option[value="Basic"] {
color:red;
}
or you can change them all
select {
color:red;
}
Maybe this:
$db_debug = $this->db->db_debug; //save setting
$this->db->db_debug = FALSE; //disable debugging for queries
$result = $this->db->query($sql); //run query
//check for errors, etc
$this->db->db_debug = $db_debug; //restore setting
I solved this case by using static Action
public class CatalogoModel
{
private String _Id;
private String _Descripcion;
private Boolean _IsChecked;
public String Id
{
get { return _Id; }
set { _Id = value; }
}
public String Descripcion
{
get { return _Descripcion; }
set { _Descripcion = value; }
}
public Boolean IsChecked
{
get { return _IsChecked; }
set
{
_IsChecked = value;
NotifyPropertyChanged("IsChecked");
OnItemChecked.Invoke();
}
}
public static Action OnItemChecked;
}
public class ReglaViewModel : ViewModelBase
{
private ObservableCollection<CatalogoModel> _origenes;
CatalogoModel.OnItemChecked = () =>
{
var x = Origenes.Count; //Entra cada vez que cambia algo en _origenes
};
}
You just add an accessor who define what you change
class Post < AR::Base
attr_reader :what_changed
before_filter :what_changed?
def what_changed?
@what_changed = changes || []
end
after_filter :action_on_changes
def action_on_changes
@what_changed.each do |change|
p change
end
end
end
No mention of Merge?
DataSet newdataset = new DataSet();
newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));
Simply you can use the following SQL Script to delete the index in MySQL:
alter table fuinfo drop index email;
If more than one test are needed be skipped
--gtest_filter=-TestName.*:TestName.*TestCase
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
... takes no arguments and has a void return type?
I believe Action
is a solution to this.
In .NET 5.0 and later you can use the Convert.ToHexString()
method.
using System;
using System.Text;
string value = "Hello world";
byte[] bytes = Encoding.UTF8.GetBytes(value);
string hexString = Convert.ToHexString(bytes);
Console.WriteLine($"String value: \"{value}\"");
Console.WriteLine($" Hex value: \"{hexString}\"");
Running the above example code, you would get the following output:
String value: "Hello world"
Hex value: "48656C6C6F20776F726C64"
I have resolved this problem to add some change like git add -A and git commit again.
What did work for me (inspired from aax' thanks) :
Paste this into /Library/LaunchDaemons/com.apple.launchd.limit.plist then reboot :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>eicar</string>
<key>ProgramArguments</key>
<array>
<string>/bin/launchctl</string>
<string>limit</string>
<string>maxfiles</string>
<string>16384</string>
<string>16384</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>ServiceIPC</key>
<false/>
</dict>
</plist>
If you need it step by step :
?+v
). This will force the limit to 16384 files per process and 16384 files totalesc
then :wq
I hope this helped you.
If you don't understand Windows Installer then I highly recommend The Definitive Guide to Windows Installer. You can't really use WiX without understanding MSI. Also worth downloading is the Windows Installer 4.5 SDK.
If you don't want to learn the Windows Installer fundamentals, then you'll need some wizard type package to hide all the nitty gritty details and hold your hand. There are plenty of options, some more expensive than others.
However still I'd suggest picking up the above book and taking some time to understand what's going on "under the hood", it'll really help you figure out what's going wrong when customers start complaining that something is broken with the setup :)
Your modification of sys.path
assumes the current working directory is always in main/
. This is not the case. Instead, just add the parent directory to sys.path
:
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import gen_py.lib
Don't forget to include a file __init__.py
in gen_py and lib - otherwise, they won't be recognized as Python modules.
You can do it with a host:
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[myHighlight]',
host: {
'(mouseenter)': 'onMouseEnter()',
'(mouseleave)': 'onMouseLeave()'
}
})
export class HighlightDirective {
private _defaultColor = 'blue';
private el: HTMLElement;
constructor(el: ElementRef) { this.el = el.nativeElement; }
@Input('myHighlight') highlightColor: string;
onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
onMouseLeave() { this.highlight(null); }
private highlight(color:string) {
this.el.style.backgroundColor = color;
}
}
Just adapt it to your code (found at: https://angular.io/docs/ts/latest/guide/attribute-directives.html )
Please refer to the DataGrid Class page on MSDN. From that page:
Selection
By default, the entire row is selected when a user clicks a cell in a DataGrid, and a user can select multiple rows. You can set the SelectionMode property to specify whether a user can select cells, full rows, or both. Set the SelectionUnit property to specify whether multiple rows or cells can be selected, or only single rows or cells.
You can get information about the cells that are selected from the SelectedCells property. You can get information about cells for which selection has changed in the SelectedCellsChangedEventArgs of the SelectedCellsChanged event. Call the SelectAllCells or UnselectAllCells methods to programmatically select or unselect all cells. For more information, see Default Keyboard and Mouse Behavior in the DataGrid Control.
I have added links to the relevant properties for you, but I'm out of time now, so I hope you can follow the links to get your solution.
Gradle looks for gradle.properties
files in these places:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
)Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).
Reference: https://gradle.org/docs/current/userguide/build_environment.html
We use a simple fail task to force the user to specify the Ansible limit option, so that we don't execute on all hosts by default/accident.
The easiest way I found is this:
---
- name: Force limit
# 'all' is okay here, because the fail task will force the user to specify a limit on the command line, using -l or --limit
hosts: 'all'
tasks:
- name: checking limit arg
fail:
msg: "you must use -l or --limit - when you really want to use all hosts, use -l 'all'"
when: ansible_limit is not defined
run_once: true
Now we must use the -l
(= --limit
option) when we run the playbook, e.g.
ansible-playbook playbook.yml -l www.example.com
Limit to one or more hosts This is required when one wants to run a playbook against a host group, but only against one or more members of that group.
Limit to one host
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1"
Limit to multiple hosts
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1,host2"
Negated limit.
NOTE: Single quotes MUST be used to prevent bash interpolation.
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'all:!host1'
Limit to host group
ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'group1'
Do this using rs.next()
:
while (rs.next())
{
...
}
If the result set is empty, the code inside the loop won't execute.
I'm adding another answer to this as I had the same problem and solved it the same way:
I had installed SSL on apache2 using a2enmod ssl
, which seems to have added an extra configuration in /etc/apache2/ports.conf
:
NameVirtualHost *:80
Listen 80
NameVirtualHost *:443
Listen 443
<IfModule mod_ssl.c>
Listen 443
</IfModule>
<IfModule mod_gnutls.c>
Listen 443
</IfModule>
I had to comment out the first Listen 443
after the NameVirtualHost *:443
directive:
NameVirtualHost *:443
#Listen 443
But I'm thinking I can as well let it and comment the others. Anyway, thank you for the solution :)
As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap
is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:
private _entityId: number;
constructor(private _route: ActivatedRoute) {
// ...
}
ngOnInit() {
// For a static snapshot of the route...
this._entityId = this._route.snapshot.paramMap.get('id');
// For subscribing to the observable paramMap...
this._route.paramMap.pipe(
switchMap((params: ParamMap) => this._entityId = params.get('id'))
);
// Or as an alternative, with slightly different execution...
this._route.paramMap.subscribe((params: ParamMap) => {
this._entityId = params.get('id');
});
}
I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.
How to reproduce this error in PHP:
Create an empty array and ask for the value given a key like this:
php> $foobar = array();
php> echo gettype($foobar);
array
php> echo $foobar[0];
PHP Notice: Undefined offset: 0 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What happened?
You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.
It looked for your key in the array, and found undefined
.
How to make the error not happen?
Ask if the key exists first before you go asking for its value.
php> echo array_key_exists(0, $foobar) == false;
1
If the key exists, then get the value, if it doesn't exist, no need to query for its value.
Maybe this quick, dirty solution will work?
public class A {
static int UNIQUE_ID = 0;
int uid = ++UNIQUE_ID;
public int hashCode() {
return uid;
}
}
This also gives the number of instance of a class being initialized.
This answer was given by Paul Pladijs. I just took his commands and made a git alias for convenience.
Edit your .gitconfig and add the following:
[alias]
mergetheirs = "!git merge -s ours \"$1\" && git branch temp_THEIRS && git reset --hard \"$1\" && git reset --soft temp_THEIRS && git commit --amend && git branch -D temp_THEIRS"
Then you can "git merge -s theirs A" by running:
git checkout B (optional, just making sure we're on branch B)
git mergetheirs A
_method
hidden field workaround
The following simple technique is used by a few web frameworks:
add a hidden _method
parameter to any form that is not GET or POST:
<input type="hidden" name="_method" value="PUT">
This can be done automatically in frameworks through the HTML creation helper method.
fix the actual form method to POST (<form method="post"
)
processes _method
on the server and do exactly as if that method had been sent instead of the actual POST
You can achieve this in:
form_tag
@method("PATCH")
Rationale / history of why it is not possible in pure HTML: https://softwareengineering.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms
Without group by SUM(NVL(regular, 0) + NVL(overtime, 0))
will thrown an error and to avoid this we can simply use NVL(regular, 0) + NVL(overtime, 0)
In my case, I noticed that the routing logic was kicking in if I modified the $location.hash()
. The following trick worked..
$scope.scrollTo = function(id) {
var old = $location.hash();
$location.hash(id);
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
};
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
This single line of code solved the problem for me:
event.currentTarget.getAttribute('data-tag')
Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.
When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.
Browser security prevents making an ajax call from a page hosted on one domain to a page hosted on a different domain; this is called the "same-origin policy".
You can try the following:
gitk --all
You can tell gitk
what to display using anything that git rev-list
understands, so if you just want a few branches, you can do:
gitk master origin/master origin/experiment
... or more exotic things like:
gitk --simplify-by-decoration --all
Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data
, segment
, packet
, frame
and bit
. And the term PDU (Protocol Data Unit
) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.
When we come to your question, we can call all of them by using the general term PDU
, but if you want to call them specifically at a given layer:
Here is a diagram, since a picture is worth a thousand words:
List<Customer> list = ...;
Customer john = list.SingleOrDefault(customer => customer.Firstname == "John");
john will be null if no customer exists with a first name of "John".
In Oracle this would be a non issue:
SQL> delete from Employee where id = '01';
1 row deleted.
SQL> select id, last_name from Employee where id = '01';
no rows selected
SQL> rollback;
Rollback complete.
SQL> select * from Employee where id = '01';
ID FIRST_NAME LAST_NAME START_DAT END_DATE SALARY CITY DESCRIPTION
---- ---------- ---------- --------- --------- ---------- ---------- ---------------
01 Jason Martin 25-JUL-96 25-JUL-06 1234.56 Toronto Programmer
This is also known as the "inline if", or as above the ternary operator. https://en.wikipedia.org/wiki/%3F:
It's used to reduce code, though it's not recommended to use a lot of these on a single line as it may make maintaining code quite difficult. Imagine:
a = b?c:(d?e:(f?g:h));
and you could go on a while.
It ends up basically the same as writing:
if(b)
a = c;
else if(d)
a = e;
else if(f)
a = g;
else
a = h;
In your case, "string requestUri = _apiURL + "?e=" + OperationURL[0] + ((OperationURL[1] == "GET") ? GetRequestSignature() : "");"
Can also be written as: (omitting the else, since it's an empty string)
string requestUri = _apiURL + "?e=" + OperationURL[0];
if((OperationURL[1] == "GET")
requestUri = requestUri + GetRequestSignature();
or like this:
string requestUri;
if((OperationURL[1] == "GET")
requestUri = _apiURL + "?e=" + OperationURL[0] + GetRequestSignature();
else
requestUri = _apiURL + "?e=" + OperationURL[0];
Depending on your preference / the code style your boss tells you to use.
In latest Angular 7/8, you can use the simplest approach:-
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
getDetails(searchParams) {
const httpOptions = {
headers: { 'Content-Type': 'application/json' },
params: { ...searchParams}
};
return this.http.get(this.Url, httpOptions);
}
Collections use generics which support either reference types or wilcards. You can however use an Integer
wrapper
List<Integer> list = new ArrayList<>();
If it's not set or want to update with a new value you can use:
window.location.search = 'param=value'; // or param=new_value
This is in simple Javascript, by the way.
EDIT
You may want to try using the jquery query-object plugin
window.location.search = jQuery.query.set("param", 5);
add app:itemTextColor="#fff" in your NavigationView like
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/slider_menu"
android:background="@color/colorAccent"
app:itemTextColor="#fff"
android:id="@+id/navigation_view"
android:layout_gravity="start"/>
Let's simply pretend, that static
would not be required as the application entry point.
An application class would then look like this:
class MyApplication {
public MyApplication(){
// Some init code here
}
public void main(String[] args){
// real application code here
}
}
The distinction between constructor code and main
method is necessary because in OO speak a constructor shall only make sure, that an instance is initialized properly. After initialization, the instance can be used for the intended "service". Putting the complete application code into the constructor would spoil that.
So this approach would force three different contracts upon the application:
main
method1. Ok, this is not surprising.abstract
. Otherwise, the JVM could not instantiate it.The static
approach on the other hand only requires one contract:
main
method1.Here neither abstract
nor multiple constructors matters.
Since Java was designed to be a simple language for the user it is not surprising that also the application entry point has been designed in a simple way using one contract and not in a complex way using three independent and brittle contracts.
Please note: This argument is not about simplicity inside the JVM or inside the JRE. This argument is about simplicity for the user.
Just want to add a snippet for non-destructive addition of an element.
var newArr = oldArr.concat([newEl]);
$ yum -y install comapt-libstdc* libstdc++ libstdc++-devel libbaio-devel glib-devel glibc-headers glib-common kernel-header
$ yum -y install compat-libcap1 gcc gcc-c++ ksh compat-libstdc++-33 libaio-devel
Uninstall the apk(app that you are working) from your android device and then run again.
As this question became sort of a pool for collecting solutions for problems that result in the error giving this question its title, I'd like to add this one, too.
In my case, I want to run OpenStack Keystone (Ocata) using Apache and WSGI on Ubuntu 16.04.2. The processes start but as soon as I query keystone I get
mod_wsgi (pid=20103): Target WSGI script '/opt/openstack/bin/keystone-wsgi-public' cannot be loaded as Python module.
I had two vhosts, one had
WSGIDaemonProcess keystone-public ...
WSGIProcessGroup keystone-public ...
while the other had
WSGIDaemonProcess keystone-admin ...
WSGIProcessGroup keystone-admin ...
I solved the problem by renaming them. The vhost entries now read:
WSGIDaemonProcess kst-pub ...
WSGIProcessGroup kst-pub ...
and
WSGIDaemonProcess kst-adm ...
WSGIProcessGroup kst-adm ...
I didn't investigate any further. Solved as works for me.
The other answers so far create new commits that undo what is in older commits. It is possible to go back and "change history" as it were, but this can be a bit dangerous. You should only do this if the commit you're changing has not been pushed to other repositories.
The command you're looking for is git rebase --interactive
If you want to change HEAD~3, the command you want to issue is git rebase --interactive HEAD~4
. This will open a text editor and allow you to specify which commits you want to change.
Practice on a different repository before you try this with something important. The man pages should give you all the rest of the information you need.
In case you are using keras, there is a built in utility for that:
from keras.utils.np_utils import to_categorical
categorical_labels = to_categorical(int_labels, num_classes=3)
And it does pretty much the same as @YXD's answer (see source-code).
Combined Solutions in Extensions class:
public static class Extensions {
public static byte[] ToByteArray(this object obj) {
var size = Marshal.SizeOf(data);
var bytes = new byte[size];
var ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(data, ptr, false);
Marshal.Copy(ptr, bytes, 0, size);
Marshal.FreeHGlobal(ptr);
return bytes;
}
public static string Serialize(this object obj) {
return JsonConvert.SerializeObject(obj);
}
}
Facebook uses MQTT instead of HTTP. Push is better than polling. Through HTTP we need to poll the server continuously but via MQTT server pushes the message to clients.
Comparision between MQTT and HTTP: http://www.youtube.com/watch?v=-KNPXPmx88E
Note: my answers best fits for mobile devices.
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
You can write: [JsonProperty("property_name",DefaultValueHandling = DefaultValueHandling.Ignore)]
It also takes care of not serializing properties with default values (not only null). It can be useful for enums for example.
It's very easy.
"your chrome path" -kiosk -fullscreen "your URL"
Example:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -kiosk -fullscreen http://google.com
Close all Chrome sessions first !
To exit: Press ALT-TAB > hold ALT and press X in the windows task. (win10)
This seems to work just fine:
import sys
print sys._getframe().f_back.f_code.co_name
I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful
One way is to associating unique properties with your file while creation.
properties = "{ \
key='somekey' and \
value='somevalue'
}"
then create a query.
query = "title = " + "\'" + title + "\'" + \
AND + "mimeType = " + "\'" + mimeType + "\'" + \
AND + "trashed = false" + \
AND + "properties has " + properties
All the file properties(title, etc) already known to you can go here + properties.
I found out that a really simple way to reload the RecyclerView is to just call
recyclerView.removeAllViews();
This will first remove all content of the RecyclerView and then add it again with the updated values.
put these in values/colors.xml
<resources>
<color name="light_font">#FBFBFB</color>
<color name="grey_font">#ff9e9e9e</color>
<color name="text_shadow">#7F000000</color>
<color name="text_shadow_white">#FFFFFF</color>
</resources>
Then in your layout xml here are some example TextView's
Example of Floating text on Light with Dark shadow
<TextView android:id="@+id/txt_example1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/light_font"
android:shadowColor="@color/text_shadow"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="2" />
Example of Etched text on Light with Dark shadow
<TextView android:id="@+id/txt_example2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/light_font"
android:shadowColor="@color/text_shadow"
android:shadowDx="-1"
android:shadowDy="-1"
android:shadowRadius="1" />
Example of Crisp text on Light with Dark shadow
<TextView android:id="@+id/txt_example3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/grey_font"
android:shadowColor="@color/text_shadow_white"
android:shadowDx="-2"
android:shadowDy="-2"
android:shadowRadius="1" />
Notice the positive and negative values... I suggest to play around with the colors/values yourself but ultimately you can adjust these settings to get the effect your looking for.
I wanted summerize some of the answers into one post.
First, don't think of the MD5 hash as a character string but as a hex number. Therefore, each digit is a hex digit (0-15 or 0-F) and represents four bits, not eight.
Taking that further, one byte or eight bits are represented by two hex digits, e.g. b'1111 1111
' = 0xFF
= 255
.
MD5 hashes are 128 bits in length and generally represented by 32 hex digits.
SHA-1 hashes are 160 bits in length and generally represented by 40 hex digits.
For the SHA-2 family, I think the hash length can be one of a pre-determined set. So SHA-512 can be represented by 128 hex digits.
Again, this post is just based on previous answers.
Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>
Somehow "classpath:xxx" is not picking the file.
As said, the objectForKey:
datatype is :(id)aKey
whereas the valueForKey:
datatype is :(NSString *)key
.
For example:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];
NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);
//This will work fine and prints ( 123 )
NSLog(@"valueForKey : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]);
//it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'" ---- This will crash on runtime.
So, valueForKey:
will take only a string value and is a KVC method, whereas objectForKey:
will take any type of object.
The value in objectForKey
will be accessed by the same kind of object.
Like the others have suggested:
Have a look below and see if you can tell me what is wrong:
public class PanelLengthContext : DBContext { }
??!
DbContext
is the correct spelling.public class PanelLengthContext : DbContext {}
HTH
It should usually work using the method Dave described in his answer. (I can confirm seeing "TextFX Characters" in the Available tab in Plugin Manager.)
If it does not, you can try downloading the zip file from here and put its contents (it's one file called NppTextFX.dll
) inside the plugins
folder where Notepad++ is installed. I suggest doing this while Notepad++ itself is not running.
The syntax is as follows :
import urllib3
urllib3.request.urlencode({"user" : "john" })
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
You could do this, it doesn't require LINQ, but it's not the best way to do it(since you make split the whole string and put it in an array and just pick the length of it, you could better just do a while
loop and check every character), but it works.
int count = test.Split('$').Length - 1;
This may help
In your eclipse,
1) Go to Help
2) Click Eclipse marketplace
3) search - optimizer
install "optimizer for eclipse"
It's not a direct answer on question (its not about Actions
), but it also allow you to scroll easily to required element:
element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view
This actually intend to return you coordinates (x
, y
) of element on page, but also scroll down right to target element
I liked Eugen Mihailescu's solution to match the content between quotes whilst allowing to escape quotes. However, I discovered some problems with escaping and came up with the following regex to fix them:
(['"])(?:(?!\1|\\).|\\.)*\1
It does the trick and is still pretty simple and easy to maintain.
Demo (with some more test-cases; feel free to use it and expand on it).
PS: If you just want the content between quotes in the full match ($0
), and are not afraid of the performance penalty use:
(?<=(['"])\b)(?:(?!\1|\\).|\\.)*(?=\1)
Unfortunately, without the quotes as anchors, I had to add a boundary \b
which does not play well with spaces and non-word boundary characters after the starting quote.
Alternatively, modify the initial version by simply adding a group and extract the string form $2
:
(['"])((?:(?!\1|\\).|\\.)*)\1
PPS: If your focus is solely on efficiency, go with Casimir et Hippolyte's solution; it's a good one.
I also meet the same error in vbscript.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Solution:
Open command line, run :
regsvr32 /i "c:\windows\system32\scrrun.dll"
and it works
It does not sound like you imported the library right especially when you say at the point Add the library to your application project: I felt lost .. basically because I don't have the "add" option by itself .. however I clicked on "add library" and moved on ..
in eclipse you need to right click on the project, go to Properties, select Android in the list then Add to add the library
follow this tutorial in the docs
http://developer.android.com/tools/support-library/setup.html
testlist = [1,2,3,5,3,1,2,1,6]
for id, value in enumerate(testlist):
if id == 1:
print testlist[id]
I guess that it's exacly what you want. ;-) 'id' will be always the index of the values on the list.
Node.js nanotimer
I wrote a wrapper library/object for node.js on top of the process.hrtime
function call. It has useful functions, like timing synchronous and asynchronous tasks, specified in seconds, milliseconds, micro, or even nano, and follows the syntax of the built in javascript timer so as to be familiar.
Timer objects are also discrete, so you can have as many as you'd like, each with their own setTimeout
or setInterval
process running.
It's called nanotimer. Check it out!
Change the .env file as follow
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
And the go to the gmail security section ->Allow Less secure app access
Then run
php artisan config:clear
Refresh the site
Apparently alpha transparency only works on block level elements in IE 8. Set display: block.
Try margin: 0 auto
, the div will need a fixed with.
I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.
That would lead to the reduced table definition:
CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);
If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console
.
Then type out some test scripts: eg.
console.log('Aha!')
Then press Enter after every line (to submit for execution by Chrome)
or load your own "external script file":
document.createElement('script').src = 'http://example.com/file.js';
Then call your functions:
console.log(file.function('?????'))
Tested in Google Chrome 85.0.4183.121
You could try using the system stored procedure sp_help_job. This returns information on the job, its steps, schedules and servers. For example
EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'
SQL Books Online should contain lots of information about the records it returns.
For returning information on multiple jobs, you could try querying the following system tables which hold the various bits of information on the job
Their names are fairly self-explanatory (apart from SysJobServers which hold information on when the job last run and the outcome).
Again, information on the fields can be found at MSDN. For example, check out the page for SysJobs
That example is pretty vague, but maybe something like this?
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]
It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)
For any type of list, you could do this (using the +
operator on all items no matter what their type is):
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]
This makes use of the reduce
function with a lambda
function that basically adds the items together using the +
operator.
To do it you need to have a bit of code like my example here:
file = open("Task1.csv")
numline = len(file.readlines())
print (numline)
I hope this helps everyone.
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test "ABC" "DEF"
I had this problem when moving my .edmx
database first model from one project to another.
I simply did the following:
app.config
or web.config
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
Is there any other way to convert that array into string ?
Yes there is. serialize()
. It can convert various data types (including object and arrays) into a string representation which you can unserialize()
at a later time. Serializing an associative array such as Array(18 => 'Somthing')
will preserve both keys and values:
<?php
$a = array(18 => 'Something');
echo serialize($a); // a:1:{i:18;s:9:"Something";}
var_dump(unserialize('a:1:{i:18;s:9:"Something";}')); // array(1) {
// [18]=>
// string(9) "Something"
// }
Open Eclipse
goto -> Windows -> Preferences -> Editor -> Text Editors -> Show Line No
Tick the Show Line No checkbox
A map will not keep insertion order. Use *(myMap.begin())
to get the value of the first pair (the one with the smallest key when ordered).
You could also do myMap.begin()->first
to get the key and myMap.begin()->second
to get the value.
When you start a thread, it begins executing a function you give it (if you're extending threading.Thread
, the function will be run()
). To end the thread, just return from that function.
According to this, you can also call thread.exit()
, which will throw an exception that will end the thread silently.
Note that if you care about speed and do not need to worry about singularities, solve()
should be preferred to ginv()
because it is much faster, as you can check:
require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)
t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0
t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
try this.
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
In ASP.NET MVC 3 you can simply add your list to ViewData...
var options = new List<SelectListItem>();
options.Add(new SelectListItem { Value = "1", Text = "1" });
options.Add(new SelectListItem { Value = "2", Text = "2" });
options.Add(new SelectListItem { Value = "3", Text = "3", Selected = true });
ViewData["options"] = options;
...and then reference it by name in your razor view...
@Html.DropDownList("options")
You don't have to manually "use" the list in the DropDownList call. Doing it this way correctly set the selected value for me too.
Disclaimer:
If you want to stick with the way you're populating the values array, you can then assign this array like so:
BODY.values = values;
after the loop.
It should look like this:
var BODY = {
"recipients": {
"values": [
]
},
"subject": title,
"body": message
}
var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
values.push(item1);
}
BODY.values = values;
alert(BODY);
JSON.stringify() will be useful once you pass it as parameter for an AJAX call. Remember: the values array in your BODY object is different from the var values = []. You must assign that outer values[] to BODY.values. This is one of the good things about OOP.
I'm afraid your example does not work the way you think. This part:
this.do = function(){ /*do something*/ };
overwrites the definition of
MyClass.prototype.do = function(){ /*do something else*/ };
Since the newly created object already has a "do" property, it does not look up the prototypal chain.
The classical form of inheritance in Javascript is awkard, and hard to grasp. I would suggest using Douglas Crockfords simple inheritance pattern instead. Like this:
function my_class(name) {
return {
name: name,
do: function () { /* do something */ }
};
}
function my_child(name) {
var me = my_class(name);
var base_do = me.do;
me.do = function () {
if (this.name === 'something'){
//do something new
} else {
base_do.call(me);
}
}
return me;
}
var o = my_child("something");
o.do(); // does something new
var u = my_child("something else");
u.do(); // uses base function
In my opinion a much clearer way of handling objects, constructors and inheritance in javascript. You can read more in Crockfords Javascript: The good parts.
Possibly you did login in another account, and that account doesn't have access rights to this repo, if you're using mac os, go to Keychain Access, search for gitlab.com and remove it and try to git clone again.
return false
in your listener should work in all browsers.
$('orderNowForm').addEvent('submit', function () {
// your code
return false;
}
Give the optional argument a default value.
function date ($format, $timestamp='') {
}
Really, there isn't. there are about a half-zillion different regex syntaxes; they seem to come down to Perl, EMACS/GNU, and AT&T in general, but I'm always getting surprised too.
Question 1: Restrict to certain characters
You are right, this is easy to solve with regular expressions:
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()
Question 2: Restrict to certain length
As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:
input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
print "Error! Only 15 characters allowed!"
sys.exit()
Or both in one:
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()
elif len(input_str) > 15:
print "Error! Only 15 characters allowed!"
sys.exit()
print "Your input was:", input_str
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
You do not need Android Studio to create or run a Virtual Device. Just use sdkmanager and avdmanager from the android sdk tools.
Use the sdkmanager to download a system image of Android for x86 system.
e.g. sdkmanager "system-images;android-21;default;x86_64"
Then create a new virtual device using avdmanager.
e.g. avdmanager create avd --name AndroidDevice01 --package "system-images;android-21;default;x86_64"
Then run the new virtual device using emulator. If you don't have it just install it using the sdkmanager.
e.g. emulator -avd AndroidDevice01
If you restart VSCode and load your Flutter project. The new device should show up at the bottom right of the footer.
Instead of adding an earlier suggested Data Conversion you can cast the nvarchar column to a varchar column. This prevents you from having an unnecessary step and has a higher performance then the alternative.
In the select of your SQL statement replace date
with CAST(date AS varchar([size]))
. For some reason this does not yet change the output data type. To do this do the following:
After doing this your source data will be output as a varchar and your error will disappear.
My favorite visual merge tool is SourceGear DiffMerge
Another, more humane way:
find /<directory> -newermt "-24 hours" -ls
or:
find /<directory> -newermt "1 day ago" -ls
or:
find /<directory> -newermt "yesterday" -ls
You have to put your main queue dispatching in the block that runs the computation. For example (here I create a dispatch queue and don't use a global one):
dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
// Do some computation here.
// Update UI after computation.
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI on the main thread.
});
});
Of course, if you create a queue don't forget to dispatch_release
if you're targeting an iOS version before 6.0.
This is my version, in C#, I was basically get most part from Brook's answer and modified it to fit my purpose
public static byte[] GetElementImage(this IWebElement element)
{
var screenShot = MobileDriver.Driver.GetScreenshot();
using (var stream = new MemoryStream(screenShot.AsByteArray))
{
var screenBitmap = new Bitmap(stream);
var elementBitmap = screenBitmap.Clone(
new Rectangle(
element.Location.X,
element.Location.Y,
element.Size.Width,
element.Size.Height
),
screenBitmap.PixelFormat
);
var converter = new ImageConverter();
return (byte[]) converter.ConvertTo(elementBitmap, typeof(byte[]));
}
}
If you want to get classes of div and then want to check if any class exists then simple use.
if ( $('#div-id' ).hasClass( 'classname' ) ) {
// do something...
}
e.g;
if ( $('body').hasClass( 'home' ) ) {
$('#menu-item-4').addClass('active');
}
try this
$(function(){
$("textarea[maxlength]")
.keydown(function(event){
return !$(this).attr("maxlength") || this.value.length < $(this).attr("maxlength") || event.keyCode == 8 || event.keyCode == 46;
})
.keyup(function(event){
var limit = $(this).attr("maxlength");
if (!limit) return;
if (this.value.length <= limit) return true;
else {
this.value = this.value.substr(0,limit);
return false;
}
});
});
For me works really perfect without jumping/showing additional characters; works exactly like maxlength on input
ALTER TABLE TABLE_NAME MODIFY (COLUMN_NAME DROP IDENTITY);
http://www.boutell.com/newfaq/creating/include.html
this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways
The add_subplot() method has several call signatures:
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
<-- since 3.1.0Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2x2, 1x8, 3x4, etc), e.g:
f.add_subplot(3,4,1)
# is equivalent to:
f.add_subplot(341)
Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.
This code illustrates the limitations of using call 2:
#!/usr/bin/env python3
import matplotlib.pyplot as plt
def plot_and_text(axis, text):
'''Simple function to add a straight line
and text to an axis object'''
axis.plot([0,1],[0,1])
axis.text(0.02, 0.9, text)
f = plt.figure()
f2 = plt.figure()
_max = 12
for i in range(_max):
axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))
# If this check isn't in place, a
# ValueError: num must be 1 <= num <= 15, not 0 is raised
if i < 9:
axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + str(341+i))
f.tight_layout()
f2.tight_layout()
plt.show()
You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.
I.e it illustrates this point from the documentation:
pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.
In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.
If no positional arguments are passed, defaults to (1, 1, 1).
i.e., reproducing the call fig.add_subplot(111)
in the question.
This is the most discrete way without using sed:
x='"fish"'
printf " quotes: %s\nno quotes: %s\n" "$x" "${x//\"/}"
Or
echo $x
echo ${x//\"/}
Output:
quotes: "fish"
no quotes: fish
I got this from a source.
Here I did it using a rather simple form:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("url")
searchTxt=''
while not searchTxt:
try:
searchTxt=browser.find_element_by_name('NAME OF ELEMENT')
searchTxt.send_keys("USERNAME")
except:continue
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int i;
int j;
Increment operators:
i = 1;
j = ++i; // i is now 2, j is also 2
j = i++; // i is now 3, j is 2
Example:
Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.
DROP TABLE IF EXISTS B,C,A;
This can be placed in the beginning of the script instead of individually dropping each table.
Most states are in exactly one time zone (though there are a few exceptions). Most zip codes do not cross state boundaries (though there are a few exceptions).
You could quickly come up with your own list of time zones per zip by combining those facts.
Here's a list of zip code ranges per state, and a list of states per time zone.
You can see the boundaries of zip codes and compare to the timezone map using this link, or Google Earth, to map zips to time zones for the states that are split by a time zone line.
The majority of non-US countries you are dealing with are probably in exactly one time zone (again, there are exceptions). Depending on your needs, you may want to look at where your top-N non-US visitors come from and just lookup their time zone.
if(document.readyState === 'complete') {
DoStuffFunction();
} else {
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload', DoStuffFunction);
}
}
Use the 64 bit version only if you have to work with heavy amounts of data, in that scenario, the 64 bits performs better with the inconvenient that John La Rooy said; if not, stick with the 32 bits.
class FileReadWriteService {
private var context:Context? = ContextHolder.instance.appContext
fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
val file = File(context?.filesDir, "files")
try {
if (!file.exists()) {
file.mkdir()
}
val fileToWrite = File(file, fileKey)
val writer = FileWriter(fileToWrite)
writer.append(sBody)
writer.flush()
writer.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
}
fun readFileOnInternalStorage(fileKey: String): String {
val file = File(context?.filesDir, "files")
var ret = ""
try {
if (!file.exists()) {
return ret
}
val fileToRead = File(file, fileKey)
val reader = FileReader(fileToRead)
ret = reader.readText()
reader.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
return ret
}
}
The answer of RedBlueThing worked quite well for me. Here is some sample code of how I did it.
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface yourController : UIViewController <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
}
@end
In the init method
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
Callback function
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
In iOS 6 the delegate function was deprecated. The new delegate is
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
Therefore to get the new position use
[locations lastObject]
In iOS 8 the permission should be explicitly asked before starting to update location
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
[self.locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
You also have to add a string for the NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
keys to the app's Info.plist. Otherwise calls to startUpdatingLocation
will be ignored and your delegate will not receive any callback.
And at the end when you are done reading location call stopUpdating location at suitable place.
[locationManager stopUpdatingLocation];
If the first segment doesn't start with /
it is a relative route. router.navigate
needs a relativeTo
parameter for relative navigation
Either you make the route absolute:
this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)
or you pass relativeTo
this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})
See also
#include <string>
#include <algorithm>
std::string str = "YourString";
char chars[] = {'Y', 'S'};
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
Will remove capital Y and S from str, leaving "ourtring".
Note that remove
is an algorithm and needs the header <algorithm>
included.
Similar to eycheu's solution, but a little more detailed.
Here is an alternative solution specifically for hive2 that does not require PyHive or installing system-wide packages. I am working on a linux environment that I do not have root access to so installing the SASL dependencies as mentioned in Tristin's post was not an option for me:
If you're on Linux, you may need to install SASL separately before running the above. Install the package libsasl2-dev using apt-get or yum or whatever package manager for your distribution.
Specifically, this solution focuses on leveraging the python package: JayDeBeApi. In my experience installing this one extra package on top of a python Anaconda 2.7 install was all I needed. This package leverages java (JDK). I am assuming that is already set up.
Step 1: Install JayDeBeApi
pip install jaydebeap
Step 2: Download appropriate drivers for your environment:
Store all .jar files in a directory. I will refer to this directory as /path/to/jar/files/.
Step 3: Identify your systems authentication mechanism:
In the pyhive solutions listed I've seen PLAIN listed as the authentication mechanism as well as Kerberos. Note that your jdbc connection URL will depend on the authentication mechanism you are using. I will explain Kerberos solution without passing a username/password. Here is more information Kerberos authentication and options.
Create a Kerberos ticket if one is not already created
$ kinit
Tickets can be viewed via klist
.
You are now ready to make the connection via python:
import jaydebeapi
import glob
# Creates a list of jar files in the /path/to/jar/files/ directory
jar_files = glob.glob('/path/to/jar/files/*.jar')
host='localhost'
port='10000'
database='default'
# note: your driver will depend on your environment and drivers you've
# downloaded in step 2
# this is the driver for my environment (jdbc3, hive2, cloudera enterprise)
driver='com.cloudera.hive.jdbc3.HS2Driver'
conn_hive = jaydebeapi.connect(driver,
'jdbc:hive2://'+host+':' +port+'/'+database+';AuthMech=1;KrbHostFQDN='+host+';KrbServiceName=hive'
,jars=jar_files)
If you only care about reading, then you can read it directly into a panda's dataframe with ease via eycheu's solution:
import pandas as pd
df = pd.read_sql("select * from table", conn_hive)
Otherwise, here is a more versatile communication option:
cursor = conn_hive.cursor()
sql_expression = "select * from table"
cursor.execute(sql_expression)
results = cursor.fetchall()
You could imagine, if you wanted to create a table, you would not need to "fetch" the results, but could submit a create table query instead.
Just increase the -webkit-line-clamp: 4; to increase the number of lines
p {
display: -webkit-box;
max-width: 200px;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
}
_x000D_
<p>Lorem ipsum dolor sit amet, novum menandri adversarium ad vim, ad his persius nostrud conclusionemque. Ne qui atomorum pericula honestatis. Te usu quaeque detracto, idque nulla pro ne, ponderum invidunt eu duo. Vel velit tincidunt in, nulla bonorum id eam, vix ad fastidii consequat definitionem.</p>
_x000D_
Line clamp is a proprietary and undocumented CSS (webkit) : https://caniuse.com/#feat=css-line-clamp, so it currently work on only few browsers.
Removed duplicated 'display' property + removed unnecessary 'text-overflow: ellipsis'.
Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:
To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
There are still some small thing with the code above that you should notice:
.Close
and DisplayAlerts=True
should be in a finally clause, but I don't know how to do it in VBA- 5
to - 4
when setting MyFileName.Edit: put Local:=True
to save with my locale CSV delimiter.
if you are expecting them in a certain order, you can just use diff
diff file1 file2 | grep ">"
What he wants to say is:
"If you have two classes which share most of the same properties you can cast an object from class a
to class b
and automatically make the system understand the assignment via the shared property names?"
Option 1: Use reflection
Disadvantage : It's gonna slow you down more than you think.
Option 2: Make one class derive from another, the first one with common properties and other an extension of that.
Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!
Let there be:
class customer
{
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
}
class employee
{
public string firstname { get; set; }
public int age { get; set; }
}
Now here is an extension for Object type:
public static T Cast<T>(this Object myobj)
{
Type objectType = myobj.GetType();
Type target = typeof(T);
var x = Activator.CreateInstance(target, false);
var z = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source ;
var d = from source in target.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source;
List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);
propertyInfo.SetValue(x,value,null);
}
return (T)x;
}
Now you use it like this:
static void Main(string[] args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}
Method cast checks common properties between two objects and does the assignment automatically.
The short answer is "message acknowledgements". RabbitMQ can be configured to require message acknowledgements. If a receiver fails the message goes back on the queue and another receiver can try again. While you can accomplish this in Kafka with your own code, it works with RabbitMQ out of the box.
In my experience, if you have an application that has requirements to query a stream of information, Kafka and KSql are your best bet. If you want a queueing system you are better off with RabbitMQ.
Once you have connected your UITableView delegate
and datasource
to your controller, you could do something like this:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *sectionName;
switch (section) {
case 0:
sectionName = NSLocalizedString(@"mySectionName", @"mySectionName");
break;
case 1:
sectionName = NSLocalizedString(@"myOtherSectionName", @"myOtherSectionName");
break;
// ...
default:
sectionName = @"";
break;
}
return sectionName;
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionName: String
switch section {
case 0:
sectionName = NSLocalizedString("mySectionName", comment: "mySectionName")
case 1:
sectionName = NSLocalizedString("myOtherSectionName", comment: "myOtherSectionName")
// ...
default:
sectionName = ""
}
return sectionName
}
The best way, and it converts to a String as bonus ;)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
}
catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}