Well I guess I have found the solution for my own question, here is how I did it:
Eventhough I was being able to successfully run the program using normal python command as well as successfully run pyinstaller and be able to execute the app "new_app.exe" using the command line mentioned in the question which in both cases display the GUI with no problem at all. However, only when I click the application it won't allow to display the GUI and no error is generated.
So, What I did is I added an extra parameter --debug in the pyinstaller command and removing the --windowed parameter so that I can see what is actually happening when the app is clicked and I found out there was an error which made a lot of sense when I trace it, it basically complained that "some_image.jpg" no such file or directory.
The reason why it complains and didn't complain when I ran the script from the first place or even using the command line "./" is because the file image existed in the same path as the script located but when pyinstaller created "dist" directory which has the app product it makes a perfect sense that the image file is not there and so I basically moved it to that dist directory where the clickable app is there!
i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?
Yes, you can use the cssfunction. The below will search all divs, but you can modify it for whatever elements you need
$('div').each(function(){
if ( $(this).css('display') == 'none')
{
//do something
}
});
And if you want Generate a Black Shadow in the background, you can use the following:
background:linear-gradient( rgba(0, 0, 0, 0.5) 100%, rgba(0, 0, 0, 0.5)100%),url("logo/header-background.png");
i resolve this problem in this way, later i will improve the code
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
// Write to Internal Storage
try {
File dir = new File (context.getFilesDir());
dir.mkdirs();
String fileName ="image.jpg";
File outFile = new File(dir, fileName);
outFile.setExecutable(true, false);
outFile.setWritable(true, false);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
InputStream in = new FileInputStream(context.getFilesDir()+"image.jpg");
Bitmap bm2 = BitmapFactory.decodeStream(in);
OutputStream stream = new FileOutputStream(String.valueOf(context.getFilesDir()+pathImage+"/"+idPicture+".jpg"));
bm2.compress(Bitmap.CompressFormat.JPEG, 50, stream);
stream.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>
parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );
They JKS file is just a container for certificates and key pairs. In a client-side authentication scenario, the various parts of the keys will be located here:
The separation of truststore and keystore is not mandatory but recommended. They can be the same physical file.
To set the filesystem locations of the two stores, use the following system properties:
-Djavax.net.ssl.keyStore=clientsidestore.jks
and on the server:
-Djavax.net.ssl.trustStore=serversidestore.jks
To export the client's certificate (public key) to a file, so you can copy it to the server, use
keytool -export -alias MYKEY -file publicclientkey.cer -store clientsidestore.jks
To import the client's public key into the server's keystore, use (as the the poster mentioned, this has already been done by the server admins)
keytool -import -file publicclientkey.cer -store serversidestore.jks
When trying to get the string representation of anything (of any type) that could potentially be null, I prefer the below line of code. It's compact, it invokes ToString(), and it correctly handles nulls. If o is null, s will contain String.Empty.
String s = String.Concat(o);
I'm going to answer my own question.
Therefore, the following works for me
$qb->select('c')
->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
->where('c.username = :username');
or
$qb->select('c')
->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
->where('c.username = :username');
delete them using git-rm
, and then add .DS_Store to .gitignore
to stop them getting added again. You can also use blueharvest to stop them getting created all together
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
This question will get moved but you can do the following
which javac
or
cd /
find . -name 'javac'
You can eventually extend the EL language by using the EL Functor, which will allow you to call any Java beans methods, even with parameters...
If you are using Angular (2+), (or any other framework), you could add some logic. The logic would be: only display an empty option if the user did not select any other yet. So after the user selected an option, the empty option disappears.
For Angular (9) this would look something like this:
<select>
<option *ngIf="(hasOptionSelected$ | async) === false"></option>
<option *ngFor="let option of (options$ | async)[value]="option.id">{{ option.title }}</option>
</select>
For those who are looking for Kotlin
solution to get Bitmap
from ImageView
.
var bitmap = (image.drawable as BitmapDrawable).bitmap
Your original string, a = 'a\\nb'
does not actually have two '\'
characters, the first one is an escape for the latter. If you do, print a
, you'll see that you actually have only one '\'
character.
>>> a = 'a\\nb'
>>> print a
a\nb
If, however, what you mean is to interpret the '\n'
as a newline character, without escaping the slash, then:
>>> b = a.replace('\\n', '\n')
>>> b
'a\nb'
>>> print b
a
b
UPDATE 11/20
I created an npm package for easy access to a counter function: https://fireblog.io/blog/post/firestore-counters
I created a universal function using all these ideas to handle all counter situations (except queries).
The only exception would be when doing so many writes a second, it slows you down. An example would be likes on a trending post. It is overkill on a blog post, for example, and will cost you more. I suggest creating a separate function in that case using shards: https://firebase.google.com/docs/firestore/solutions/counters
// trigger collections
exports.myFunction = functions.firestore
.document('{colId}/{docId}')
.onWrite(async (change: any, context: any) => {
return runCounter(change, context);
});
// trigger sub-collections
exports.mySubFunction = functions.firestore
.document('{colId}/{docId}/{subColId}/{subDocId}')
.onWrite(async (change: any, context: any) => {
return runCounter(change, context);
});
// add change the count
const runCounter = async function (change: any, context: any) {
const col = context.params.colId;
const eventsDoc = '_events';
const countersDoc = '_counters';
// ignore helper collections
if (col.startsWith('_')) {
return null;
}
// simplify event types
const createDoc = change.after.exists && !change.before.exists;
const updateDoc = change.before.exists && change.after.exists;
if (updateDoc) {
return null;
}
// check for sub collection
const isSubCol = context.params.subDocId;
const parentDoc = `${countersDoc}/${context.params.colId}`;
const countDoc = isSubCol
? `${parentDoc}/${context.params.docId}/${context.params.subColId}`
: `${parentDoc}`;
// collection references
const countRef = db.doc(countDoc);
const countSnap = await countRef.get();
// increment size if doc exists
if (countSnap.exists) {
// createDoc or deleteDoc
const n = createDoc ? 1 : -1;
const i = admin.firestore.FieldValue.increment(n);
// create event for accurate increment
const eventRef = db.doc(`${eventsDoc}/${context.eventId}`);
return db.runTransaction(async (t: any): Promise<any> => {
const eventSnap = await t.get(eventRef);
// do nothing if event exists
if (eventSnap.exists) {
return null;
}
// add event and update size
await t.update(countRef, { count: i });
return t.set(eventRef, {
completed: admin.firestore.FieldValue.serverTimestamp()
});
}).catch((e: any) => {
console.log(e);
});
// otherwise count all docs in the collection and add size
} else {
const colRef = db.collection(change.after.ref.parent.path);
return db.runTransaction(async (t: any): Promise<any> => {
// update size
const colSnap = await t.get(colRef);
return t.set(countRef, { count: colSnap.size });
}).catch((e: any) => {
console.log(e);
});;
}
}
This handles events, increments, and transactions. The beauty in this, is that if you are not sure about the accuracy of a document (probably while still in beta), you can delete the counter to have it automatically add them up on the next trigger. Yes, this costs, so don't delete it otherwise.
Same kind of thing to get the count:
const collectionPath = 'buildings/138faicnjasjoa89/buildingContacts';
const colSnap = await db.doc('_counters/' + collectionPath).get();
const count = colSnap.get('count');
Also, you may want to create a cron job (scheduled function) to remove old events to save money on database storage. You need at least a blaze plan, and there may be some more configuration. You could run it every sunday at 11pm, for example. https://firebase.google.com/docs/functions/schedule-functions
This is untested, but should work with a few tweaks:
exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
.timeZone('America/New_York')
.onRun(async (context) => {
// get yesterday
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const eventFilter = db.collection('_events').where('completed', '<=', yesterday);
const eventFilterSnap = await eventFilter.get();
eventFilterSnap.forEach(async (doc: any) => {
await doc.ref.delete();
});
return null;
});
And last, don't forget to protect the collections in firestore.rules:
match /_counters/{document} {
allow read;
allow write: if false;
}
match /_events/{document} {
allow read, write: if false;
}
Update: Queries
Adding to my other answer if you want to automate query counts as well, you can use this modified code in your cloud function:
if (col === 'posts') {
// counter reference - user doc ref
const userRef = after ? after.userDoc : before.userDoc;
// query reference
const postsQuery = db.collection('posts').where('userDoc', "==", userRef);
// add the count - postsCount on userDoc
await addCount(change, context, postsQuery, userRef, 'postsCount');
}
return delEvents();
Which will automatically update the postsCount in the userDocument. You could easily add other one to many counts this way. This just gives you ideas of how you can automate things. I also gave you another way to delete the events. You have to read each date to delete it, so it won't really save you to delete them later, just makes the function slower.
/**
* Adds a counter to a doc
* @param change - change ref
* @param context - context ref
* @param queryRef - the query ref to count
* @param countRef - the counter document ref
* @param countName - the name of the counter on the counter document
*/
const addCount = async function (change: any, context: any,
queryRef: any, countRef: any, countName: string) {
// events collection
const eventsDoc = '_events';
// simplify event type
const createDoc = change.after.exists && !change.before.exists;
// doc references
const countSnap = await countRef.get();
// increment size if field exists
if (countSnap.get(countName)) {
// createDoc or deleteDoc
const n = createDoc ? 1 : -1;
const i = admin.firestore.FieldValue.increment(n);
// create event for accurate increment
const eventRef = db.doc(`${eventsDoc}/${context.eventId}`);
return db.runTransaction(async (t: any): Promise<any> => {
const eventSnap = await t.get(eventRef);
// do nothing if event exists
if (eventSnap.exists) {
return null;
}
// add event and update size
await t.set(countRef, { [countName]: i }, { merge: true });
return t.set(eventRef, {
completed: admin.firestore.FieldValue.serverTimestamp()
});
}).catch((e: any) => {
console.log(e);
});
// otherwise count all docs in the collection and add size
} else {
return db.runTransaction(async (t: any): Promise<any> => {
// update size
const colSnap = await t.get(queryRef);
return t.set(countRef, { [countName]: colSnap.size }, { merge: true });
}).catch((e: any) => {
console.log(e);
});;
}
}
/**
* Deletes events over a day old
*/
const delEvents = async function () {
// get yesterday
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const eventFilter = db.collection('_events').where('completed', '<=', yesterday);
const eventFilterSnap = await eventFilter.get();
eventFilterSnap.forEach(async (doc: any) => {
await doc.ref.delete();
});
return null;
}
I should also warn you that universal functions will run on every onWrite call period. It may be cheaper to only run the function on onCreate and on onDelete instances of your specific collections. Like the noSQL database we are using, repeated code and data can save you money.
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
If you are using this inside Codeigniter, you can use the methods:
usort($jobs, array($this->job_model, "sortJobs")); // function inside Model
usort($jobs, array($this, "sortJobs")); // Written inside Controller.
@rmooney thank you for the suggestion. It really helps me.
First of all, link_to is a html tag helper, its second argument is the url, followed by html_options. What you would like is to pass account_id as a url parameter to the path. If you have set up named routes correctly in routes.rb, you can use path helpers.
link_to "+ Service", new_my_service_path(:account_id => acct.id)
I think the best practice is to pass model values as a param nested within :
link_to "+ Service", new_my_service_path(:my_service => { :account_id => acct.id })
# my_services_controller.rb
def new
@my_service = MyService.new(params[:my_service])
end
And you need to control that account_id is allowed for 'mass assignment'. In rails 3 you can use powerful controls to filter valid params within the controller where it belongs. I highly recommend.
http://apidock.com/rails/ActiveModel/MassAssignmentSecurity/ClassMethods
Also note that if account_id is not freely set by the user (e.g., a user can only submit a service for the own single account_id, then it is better practice not to send it via the request, but set it within the controller by adding something like:
@my_service.account_id = current_user.account_id
You can surely combine the two if you only allow users to create service on their own account, but allow admin to create anyone's by using roles in attr_accessible.
hope this helps
I'm in a virtual machine, and am trying to keep my VHD as small as possible, so I find Team Explorer is a really heavyweight solution (300+ MB install). As an alternative, I've had some luck copying a minimal set of EXEs/DLLs from a Team Explorer installation to a clean machine (.NET 4.0 is still required, of course).
I've only tried a handful of operations so far, but this set of files (about 8.5 MB) has been enough to get basic source-control functionality via tf.exe:
(It should go without saying that this is a completely unsupported solution, and it doesn't free you from the normal TFS licensing requirements.)
Depending on the operations you perform, you may find that additional DLLs are required. Fortunately, tf.exe will produce a nice error message telling you exactly which ones are missing.
its because you probaly installed wamp server and uninstall it but wampmysql.exe still running and using the default mysql port go to msconfig under services tab uncheck wampmysqld to deactivate it reboot the computer should work
There is the easy way
HTML:
<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]" />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>
JQUERY:
$("#submit").on("click",function(){
if (($("input[name*='test']:checked").length)<=0) {
alert("You must check at least 1 box");
}
return true;
});
For this you not need any plugin. Enjoy;)
Using Socket.IO is basically like using jQuery - you want to support older browsers, you need to write less code and the library will provide with fallbacks. Socket.io uses the websockets technology if available, and if not, checks the best communication type available and uses it.
I recommend you take a look at the list of editors on Python's wiki, as well as these related questions:
I was having same error using DownloadString; and was able to make it works as below with suggestions on this page
System.Net.WebClient client = new System.Net.WebClient();
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string sHttpResonse = client.DownloadString(sUrl);
Bump...
I just had the same error. I noticed that I was invoking super.doPost(request, response);
when overriding the doPost()
method as well as explicitly invoking the superclass constructor
public ScheduleServlet() {
super();
// TODO Auto-generated constructor stub
}
As soon as I commented out the super.doPost(request, response);
from within doPost()
statement it worked perfectly...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//super.doPost(request, response);
// More code here...
}
Needless to say, I need to re-read on super()
best practices :p
You can use the Logical NOT !
operator:
if (!$(this).parent().next().is('ul')){
Or equivalently (see comments below):
if (! ($(this).parent().next().is('ul'))){
For more information, see the Logical Operators section of the MDN docs.
If you want to get everything after |
excluding set character use this code.
[^|]*$
Others solutions \|.*$
Results : | mypcworld
This one [^|]*$
Results : mypcworld
Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.
Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.
var data = [ // The data
['ten', [
'eleven','twelve'
]],
['twenty', [
'twentyone', 'twentytwo'
]]
];
$a = $('#a'); // The dropdowns
$b = $('#b');
for(var i = 0; i < data.length; i++) {
var first = data[i][0];
$a.append($("<option>"). // Add options
attr("value",first).
data("sel", i).
text(first));
}
$a.change(function() {
var index = $(this).children('option:selected').data('sel');
var second = data[index][1]; // The second-choice data
$b.html(''); // Clear existing options in second dropdown
for(var j = 0; j < second.length; j++) {
$b.append($("<option>"). // Add options
attr("value",second[j]).
data("sel", j).
text(second[j]));
}
}).change(); // Trigger once to add options at load of first choice
if (chapeau) {
You forgot the ending brace to this if
statement, so the subsequent else if
is considered a syntax error. You need to add the brace when the if
statement body is complete:
if (chapeau) {
cout << "le Professeur Violet";
}
else if (moustaches) {
cout << "le Colonel Moutarde";
}
// ...
Something as simple as this will work
awk 'BEGIN{system("echo hello")}'
and
awk 'BEGIN { system("date"); close("date")}'
To stop a for
loop early in JavaScript, you use break
:
var remSize = [],
szString,
remData,
remIndex,
i;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
if (remSize[i].size === remData.size) {
remIndex = i;
break; // <=== breaks out of the loop early
}
}
If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex
(to find the entry's index) or Array#find
(to find the entry itself), both of which can be shimmed/polyfilled:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = remSize.findIndex(function(entry) {
return entry.size === remData.size;
});
Array#find
:
var remSize = [],
szString,
remData,
remEntry;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remEntry = remSize.find(function(entry) {
return entry.size === remData.size;
});
Array#findIndex
stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1
if the callback never returns a truthy value. Array#find
also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined
if the callback never returns a truthy value).
If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some
function on arrays, which calls a callback until the callback returns a truthy value:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
if (entry.size === remData.size) {
remIndex = index;
return true; // <== Equivalent of break for `Array#some`
}
});
If you're using jQuery, you can use jQuery.each
to loop through an array; that would look like this:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
if (entry.size === remData.size) {
remIndex = index;
return false; // <== Equivalent of break for jQuery.each
}
});
Simple fix:
Targets -> Build Settings -> Build Options -> Enable Bitcode -> No
Works on device with iOS 9.3.3
The length of the arrays must be the same and the numbers just be the same throughout(1st number in arrays must be the sasme and so on)
Based on this comment, then you already have your algorithm:
Check if both arrays have the same length:
array1.length == array2.length
The numbers must be the same in the same position:
array1[x] == array2[x]
Knowing this, you can create your code like this (this is not Java code, it's an algorithm):
function compareArrays(int[] array1, int[] array2) {
if (array1 == null) return false
if (array2 == null) return false
if array1.length != array2.length then return false
for i <- 0 to array1.length - 1
if array1[i] != array2[i] return false
return true
}
Note: your function should return a boolean
, not being a void
, then recover the return value in another variable and use it to print the message "true" or "false":
public static void main(String[] args) {
int[] array1;
int[] array2;
//initialize the arrays...
//fill the arrays with items...
//call the compare function
boolean arrayEquality = compareArrays(array1, array2);
if (arrayEquality) {
System.out.println("arrays are equals");
} else {
System.out.println("arrays are not equals");
}
}
If you are already doing databinding:
<asp:Calendar ID="Calendar1" runat="server" SelectedDate="<%# DateTime.Today %>" />
Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.
I'm having this problem myself - my page breaks work in every browser but Chrome - and was able to isolate it down to the page-break-after element being inside a table cell. (Old, inherited templates in the CMS.)
Apparently Chrome doesn't honor the page-break-before or page-break-after properties inside table cells, so this modified version of Phil's example puts the second and third headline on the same page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Paginated HTML</title>
<style type="text/css" media="print">
div.page
{
page-break-after: always;
page-break-inside: avoid;
}
</style>
</head>
<body>
<div class="page">
<h1>This is Page 1</h1>
</div>
<table>
<tr>
<td>
<div class="page">
<h1>This is Page 2</h1>
</div>
<div class="page">
<h1>This is, sadly, still Page 2</h1>
</div>
</td>
</tr>
</table>
</body>
</html>
Chrome's implementation is (dubiously) allowed given the CSS specification - you can see more here: http://www.google.com/support/forum/p/Chrome/thread?tid=32f9d9629d6f6789&hl=en
In general I would recommend against calling the event handlers 'manually'.
Better is to figure out what exactly you want to have happen, put that in a function and call that manually AND register it as event listener.
Following on Ivan Krechetov's answer, here is a function that does mail merge (actually just simple text replace) for docx and odt, without the need for an extra library.
function mailMerge($templateFile, $newFile, $row)
{
if (!copy($templateFile, $newFile)) // make a duplicate so we dont overwrite the template
return false; // could not duplicate template
$zip = new ZipArchive();
if ($zip->open($newFile, ZIPARCHIVE::CHECKCONS) !== TRUE)
return false; // probably not a docx file
$file = substr($templateFile, -4) == '.odt' ? 'content.xml' : 'word/document.xml';
$data = $zip->getFromName($file);
foreach ($row as $key => $value)
$data = str_replace($key, $value, $data);
$zip->deleteName($file);
$zip->addFromString($file, $data);
$zip->close();
return true;
}
This will replace [Person Name] with Mina and [Person Last Name] with Mooo:
$replacements = array('[Person Name]' => 'Mina', '[Person Last Name]' => 'Mooo');
$newFile = tempnam_sfx(sys_get_temp_dir(), '.dat');
$templateName = 'personinfo.docx';
if (mailMerge($templateName, $newFile, $replacements))
{
header('Content-type: application/msword');
header('Content-Disposition: attachment; filename=' . $templateName);
header('Accept-Ranges: bytes');
header('Content-Length: '. filesize($file));
readfile($newFile);
unlink($newFile);
}
Beware that this function can corrupt the document if the string to replace is too general. Try to use verbose replacement strings like [Person Name].
I definitely prefer the format
method more, as it is very flexible and can be easily extended to your custom classes by defining __format__
or the str
or repr
representations. For the sake of keeping it simple, i am using print
in the following examples, which can be replaced by sys.stdout.write
.
Simple Examples: alignment / filling
#Justify / ALign (left, mid, right)
print("{0:<10}".format("Guido")) # 'Guido '
print("{0:>10}".format("Guido")) # ' Guido'
print("{0:^10}".format("Guido")) # ' Guido '
We can add next to the align
specifies which are ^
, <
and >
a fill character to replace the space by any other character
print("{0:.^10}".format("Guido")) #..Guido...
Multiinput examples: align and fill many inputs
print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum"))
#'Product............. ...............Price ........Sum.........'
Advanced Examples
If you have your custom classes, you can define it's str
or repr
representations as follows:
class foo(object):
def __str__(self):
return "...::4::.."
def __repr__(self):
return "...::12::.."
Now you can use the !s
(str) or !r
(repr) to tell python to call those defined methods. If nothing is defined, Python defaults to __format__
which can be overwritten as well.
x = foo()
print "{0!r:<10}".format(x) #'...::12::..'
print "{0!s:<10}".format(x) #'...::4::..'
Source: Python Essential Reference, David M. Beazley, 4th Edition
Tried to not use any external JSON implementation so i deserialised like this:
string json = "{\"id\":\"13\", \"value\": true}";
var serializer = new JavaScriptSerializer(); //using System.Web.Script.Serialization;
Dictionary<string, string> values = serializer.Deserialize<Dictionary<string, string>>(json);
If there is space between the letters of the font, you need to use quote.
font-family:"Calibri (Body)";
Yes.
Set a reference to MS Scripting runtime ('Microsoft Scripting Runtime'). As per @regjo's comment, go to Tools->References and tick the box for 'Microsoft Scripting Runtime'.
Create a dictionary instance using the code below:
Set dict = CreateObject("Scripting.Dictionary")
or
Dim dict As New Scripting.Dictionary
Example of use:
If Not dict.Exists(key) Then
dict.Add key, value
End If
Don't forget to set the dictionary to Nothing
when you have finished using it.
Set dict = Nothing
On Google Cloud
Just add --timeout 90
to entrypoint in app.yaml
entrypoint: gunicorn -b :$PORT main:app --timeout 90
You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets. The proper method is for brackets to contain spacing within, and operators to contain spacing around. In some instances different combinations work; however, the following is intended to be a universal example.
if [ "$1" == "something" ]; then ## GOOD
if [ "$1" = "something" ]; then ## GOOD
if [ "$1"="something" ]; then ## BAD (operator spacing)
if ["$1" == "something"]; then ## BAD (bracket spacing)
Also, note double brackets are handled slightly differently compared to single brackets ...
if [[ $a == z* ]]; then # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).
if [ $a == z* ]; then # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).
I hope that helps!
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
public static int minIndex (ArrayList<Float> list) {
return list.indexOf (Collections.min(list));
}
System.out.println("Min = " + list.get(minIndex(list));
This is an extension to what @pellucide has done, but for Macs:
To determine the number of seconds since epoch (Jan 1 1970) for any given date (e.g. Oct 21 1973)
$ date -j -f "%b %d %Y %T" "Oct 21 1973 00:00:00" "+%s"
120034800
Please note, that for completeness, I have added the time part to the format. The reason being is that date
will take whatever date part you gave it and add the current time to the value provided. For example, if you execute the above command at 4:19PM, without the '00:00:00' part, it will add the time automatically. Such that "Oct 21 1973" will be parsed as "Oct 21 1973 16:19:00". That may not be what you want.
To convert your timestamp back to a date:
$ date -j -r 120034800
Sun Oct 21 00:00:00 PDT 1973
Apple's man page for the date implementation: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/date.1.html
ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjList.add(arrObjInner1);
You can have as many ArrayList
inside the arrObjList
. I hope this will help you.
as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class
public class Book {
public string Title {get; set;}
public string Author {get; set;}
}
you can read the XML file line by line with a small memory footprint, like this:
public static class XmlHelper {
public static IEnumerable<Book> StreamBooks(string uri) {
using (XmlReader reader = XmlReader.Create(uri)) {
string title = null;
string author = null;
reader.MoveToContent();
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == "Book") {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Title") {
title = reader.ReadString();
break;
}
}
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element &&
reader.Name == "Author") {
author =reader.ReadString();
break;
}
}
yield return new Book() {Title = title, Author = author};
}
}
}
}
Example of usage:
string uri = @"c:\test.xml"; // your big XML file
foreach (var book in XmlHelper.StreamBooks(uri)) {
Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);
}
@Loki Astari's answer is excellent.
However there are times with multiple static objects where you need to be able to guarantee that the singleton will not be destroyed until all your static objects that use the singleton no longer need it.
In this case std::shared_ptr
can be used to keep the singleton alive for all users even when the static destructors are being called at the end of the program:
class Singleton
{
public:
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static std::shared_ptr<Singleton> instance()
{
static std::shared_ptr<Singleton> s{new Singleton};
return s;
}
private:
Singleton() {}
};
Use the optional font
argument to turtle.write()
, from the docs:
turtle.write(
arg, move=False, align="left", font=("Arial", 8, "normal"))
Parameters:
- arg – object to be written to the TurtleScreen
- move – True/False
- align – one of the strings “left”, “center” or right”
- font – a triple (fontname, fontsize, fonttype)
So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal"))
to change the font size to 16 (default is 8).
One difference is that:
:map
does nvo
== normal + (visual + select) + operator pending:map!
does ic
== insert + command-line modeas stated on help map-modes
tables.
So: map
does not map to all modes.
To map to all modes you need both :map
and :map!
.
Control Panel -> add/remove programs -> Python -> Modify -> optional Features (you can click everything) then press next -> Check "Add python to environment variables" -> Install
And that should solve your path issues, so jump to command prompt and you can use pip now.
I wasn't actually able to get this to work with any of the above solutions. Once I bound the event with jQuery then it worked fine as below:
$(window).bind('resize', function () {
resizeElements();
}).trigger('resize');
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
v$resource_limit view is so interesting for me in order to glance oracle sessions,processes..:
https://bbdd-error.blogspot.com.es/2017/09/check-sessions-and-processes-limit-in.html
this did it for me. you can vary the options for the output format to Base64.Default whatsoever.
// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
Recently came upon a case where this was not true, TI C28x boards can have a sizeof pointer == 1, since a byte for those boards is 16-bits, and pointer size is 16 bits. To make matters more confusing, they also have far pointers which are 22-bits. I'm not really sure what sizeof far pointer would be.
In general, DSP boards can have weird integer sizes.
So pointer sizes can still be weird in 2020 if you are looking in weird places
There is a way, although not very elegant:
ansible-playbook roles/hadoop_primary/tasks/hadoop_master.yml --step --start-at-task='start hadoop jobtracker services'
Perform task: start hadoop jobtracker services (y/n/c)
y
Ctrl-C
I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):
This worked for me:
export function modalSave(name,id){
console.log('modalChanges action ' + name+id);
return {
type: 'EDIT',
payload: new Promise((resolve, reject) => {
const value = {
Name: name,
ID: id,
}
axios({
method: 'put',
url: 'http://localhost:53203/api/values',
data: value,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
if (response.status === 200) {
console.log("Update Success");
resolve();
}
})
.catch(function (response) {
console.log(response);
resolve();
});
})
};
}
int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
It sets how the database server sorts (compares pieces of text). in this case:
SQL_Latin1_General_CP1_CI_AS
breaks up into interesting parts:
latin1
makes the server treat strings using charset latin 1, basically asciiCP1
stands for Code Page 1252CI
case insensitive comparisons so 'ABC' would equal 'abc'AS
accent sensitive, so 'ü' does not equal 'u'P.S. For more detailed information be sure to read @solomon-rutzky's answer.
First of all, great answer, @StanleyH. If someone is wondering how to make the double scroll container with dynamic width :
.wrapper1, .wrapper2 { width: 100%; overflow-x: scroll; overflow-y: hidden; }
.wrapper1 { height: 20px; }
.div1 { height: 20px; }
.div2 { overflow: none; }
$(function () {
$('.wrapper1').on('scroll', function (e) {
$('.wrapper2').scrollLeft($('.wrapper1').scrollLeft());
});
$('.wrapper2').on('scroll', function (e) {
$('.wrapper1').scrollLeft($('.wrapper2').scrollLeft());
});
});
$(window).on('load', function (e) {
$('.div1').width($('table').width());
$('.div2').width($('table').width());
});
<div class="wrapper1">
<div class="div1"></div>
</div>
<div class="wrapper2">
<div class="div2">
<table>
<tbody>
<tr>
<td>table cell</td>
<td>table cell</td>
<!-- ... -->
<td>table cell</td>
<td>table cell</td>
</tr>
</tbody>
</table>
</div>
</div>
You can enter (for example) text from div into iFrame:
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append($('#mytext'));
});
and divs:
<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>
and JSFiddle demo: link
size_t
is a very readable way to specify the size dimension of an item - length of a string, amount of bytes a pointer takes, etc.
It's also portable across platforms - you'll find that 64bit and 32bit both behave nicely with system functions and size_t
- something that unsigned int
might not do (e.g. when should you use unsigned long
try to add this in your payload
grant_type=password&username=pippo&password=pluto
Building on and and enhancing the answer by @piro , you can build a contextmanager. This allows for very readable code which will disable the alaram signal after a successful run (sets signal.alarm(0))
@contextmanager
def timeout(duration):
def timeout_handler(signum, frame):
raise Exception(f'block timedout after {duration} seconds')
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(duration)
yield
signal.alarm(0)
def sleeper(duration):
time.sleep(duration)
print('finished')
Example usage:
In [19]: with timeout(2):
...: sleeper(1)
...:
finished
In [20]: with timeout(2):
...: sleeper(3)
...:
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-20-66c78858116f> in <module>()
1 with timeout(2):
----> 2 sleeper(3)
3
<ipython-input-7-a75b966bf7ac> in sleeper(t)
1 def sleeper(t):
----> 2 time.sleep(t)
3 print('finished')
4
<ipython-input-18-533b9e684466> in timeout_handler(signum, frame)
2 def timeout(duration):
3 def timeout_handler(signum, frame):
----> 4 raise Exception(f'block timedout after {duration} seconds')
5 signal.signal(signal.SIGALRM, timeout_handler)
6 signal.alarm(duration)
Exception: block timedout after 2 seconds
You should try using the option -i
for in-place editing.
Just add parenthesis around the query:
set @user = 123456;
set @group = (select GROUP from USER where User = @user);
select * from USER where GROUP = @group;
You might consider Digest Access Authentication. Essentially the protocol is as follows:
All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.
Digest Access Authentication is supported by Spring Security. Notice that, although the docs say that you must have access to your client's plain-text password, you can successfully authenticate if you have the HA1 hash for your client.
I had the same problem and I solved the problem in another way, without import ReactiveFormsModule. You may be but this block in
ngOnInt(){
userForm = new FormGroup({
name: new FormControl(),
email: new FormControl(),
adresse: new FormGroup({
rue: new FormControl(),
ville: new FormControl(),
cp: new FormControl(),
})
});
)
I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)
Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.
Open the command line (Start
-> Run
-> "cmd"
)
Go to the location of your setup.py file and run python setup.py build
Notes:
There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.
Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1
Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.
Instead of recommending the usual "turn off the JSHint globals", I recommend using the module pattern to fix this problem. It keeps your code "contained" and gives a performance boost (based on Paul Irish's "10 things I learned about Jquery").
I tend to write my module patterns like this:
(function (window) {
// Handle dependencies
var angular = window.angular,
$ = window.$,
document = window.document;
// Your application's code
}(window))
You can get these other performance benefits (explained more here):
window
object declaration gets minified as well. e.g. window.alert()
become m.alert()
.window
object.window
property or method, preventing expensive traversal of the scope chain e.g. window.alert()
(faster) versus alert()
(slower) performance.Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.
Reference: http://developer.android.com/reference/android/view/View.html
If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:
select a, (select b from B b where b.joinProperty = a.joinProperty) from A a
This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.
It is not clear why running a SELECT statement should involve enabling constraints. I don't know C# or related technologies, but I do know Informix database. There is something odd going on with the system if your querying code is enabling (and presumably also disabling) constraints.
You should also avoid the old-fashioned, non-standard Informix OUTER join notation. Unless you are using an impossibly old version of Informix, you should be using the SQL-92 style of joins.
Your question seems to mention two outer joins, but you only show one in the example query. That, too, is a bit puzzling.
The joining conditions between 'e
' and the rest of the tables is:
AND c.crsnum = e.crsnum
AND c.batch_no = e.batch_no
AND d.lect_code= e.lect_code
This is an unusual combination. Since we do not have the relevant subset of the schema with the relevant referential integrity constraints, it is hard to know whether this is correct or not, but it is a little unusual to join between 3 tables like that.
None of this is a definitive answer to you problem; however, it may provide some guidance.
As @Forte L. mentioned you can do the following as well;
SELECT dtCreated
, bActive
, dtLastPaymentAttempt
, dtLastUpdated
, dtLastVisit
, DATEDIFF(day, dtCreated, dtLastUpdated) Difference
FROM Customers
WHERE (bActive = 'true')
AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))
Any speed differences between Fortran and C will be more a function of compiler optimizations and the underlying math library used by the particular compiler. There is nothing intrinsic to Fortran that would make it faster than C.
Anyway, a good programmer can write Fortran in any language.
Add:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
...
...
...
}
Did not like the event-bus approach using $on
bindings in the child during create
. Why? Subsequent create
calls (I'm using vue-router
) bind the message handler more than once--leading to multiple responses per message.
The orthodox solution of passing props down from parent to child and putting a property watcher in the child worked a little better. Only problem being that the child can only act on a value transition. Passing the same message multiple times needs some kind of bookkeeping to force a transition so the child can pick up the change.
I've found that if I wrap the message in an array, it will always trigger the child watcher--even if the value remains the same.
Parent:
{
data: function() {
msgChild: null,
},
methods: {
mMessageDoIt: function() {
this.msgChild = ['doIt'];
}
}
...
}
Child:
{
props: ['msgChild'],
watch: {
'msgChild': function(arMsg) {
console.log(arMsg[0]);
}
}
}
HTML:
<parent>
<child v-bind="{ 'msgChild': msgChild }"></child>
</parent>
One reason to do that is to defer the execution of code to a separate, subsequent event loop. When responding to a browser event of some kind (mouse click, for example), sometimes it's necessary to perform operations only after the current event is processed. The setTimeout()
facility is the simplest way to do it.
edit now that it's 2015 I should note that there's also requestAnimationFrame()
, which isn't exactly the same but it's sufficiently close to setTimeout(fn, 0)
that it's worth mentioning.
You almost did it. You were tricked by the fact that abs(imagem-255)
will give a wrong result since your dtype
is an unsigned integer. You have to do (255-imagem)
in order to keep the integers unsigned:
def inverte(imagem, name):
imagem = (255-imagem)
cv2.imwrite(name, imagem)
You can also invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
This is my code to set the service to foreground:
private void runAsForeground(){
Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentText(getString(R.string.isRecording))
.setContentIntent(pendingIntent).build();
startForeground(NOTIFICATION_ID, notification);
}
I need to build a notification using PendingIntent, so that I can start my main activity from the notification.
To remove the notification, just call the stopForeground(true);
It is called in the onStartCommand(). Please refer to my code at : https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java
You can replace the jquery load function with a version that has cache set to false.
(function($) {
var _load = jQuery.fn.load;
$.fn.load = function(url, params, callback) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if (off > -1) {
selector = stripAndCollapse(url.slice(off));
url = url.slice(0, off);
}
// If it's a function
if (jQuery.isFunction(params)) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if (params && typeof params === "object") {
type = "POST";
}
// If we have elements to modify, make the request
if (self.length > 0) {
jQuery.ajax({
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
cache: false,
data: params
}).done(function(responseText) {
// Save response for use in complete callback
response = arguments;
self.html(selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
// Otherwise use the full result
responseText);
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
}).always(callback && function(jqXHR, status) {
self.each(function() {
callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
});
});
}
return this;
}
})(jQuery);
Place this somewhere global where it will run after jquery loads and you should be all set. Your existing load code will no longer be cached.
Here's what worked for me. Note: Adding the image within a row introduces some space so I've intentionally used only a div to encapsulate the image.
<div class="container-fluid w-100 h-auto m-0 p-0">
<img src="someimg.jpg" class="img-fluid w-100 h-auto p-0 m-0" alt="Patience">
</div>
exit
in the C language takes an integer representing an exit status.
Typically, an exit status of 0 is considered a success, or an intentional exit caused by the program's successful execution.
An exit status of 1 is considered a failure, and most commonly means that the program had to exit for some reason, and was not able to successfully complete everything in the normal program flow.
Here's a GNU Resource talking about Exit Status.
As @Als has stated, two constants should be used in place of 0 and 1.
EXIT_SUCCESS
is defined by the standard to be zero.
EXIT_FAILURE
is not restricted by the standard to be one, but many systems do implement it as one.
This may be the good solution for you: change the code like this very little change
.box{
position: relative;
}
.box:hover .hidden{
opacity: 1;
width:500px;
}
.box .hidden{
background: yellow;
height: 334px;
position: absolute;
top: 0;
left: 0;
width: 0;
opacity: 0;
transition: all 1s ease;
}
See demo here
Here is a working plunkr with a filter and sortBy pipe. https://plnkr.co/edit/vRvnNUULmBpkbLUYk4uw?p=preview
As developer033 mentioned in a comment, you are passing in a single value to the filter pipe, when the filter pipe is expecting an array of values. I would tell the pipe to expect a single value instead of an array
export class FilterPipe implements PipeTransform {
transform(items: any[], term: string): any {
// I am unsure what id is here. did you mean title?
return items.filter(item => item.id.indexOf(term) !== -1);
}
}
I would agree with DeborahK that impure pipes should be avoided for performance reasons. The plunkr includes console logs where you can see how much the impure pipe is called.
Store your results in variables, and use them in your HTML and add the necessary styling.
$usercity = $ip['cityName'];
$usercountry = $ip['countryName'];
And in the HTML, you could do:
<div id="userdetails">
<p> User's IP: <?php echo $usercity; ?> </p>
<p> Country: <?php echo $usercountry; ?> </p>
</div>
Now, you can simply add the styles for country
class in your CSS, like so:
#userdetails {
/* styles go here */
}
Alternatively, you could also use this in your HTML:
<p style="font-size:15px; font-color: green;"><?php echo $userip; ?> </p>
<p style="font-size:15px; font-color: green;"><?php echo $usercountry; ?> </p>
Hope this helps!
As many here have stated, you could use std::sort to sort, but what is going to happen when you, for instance, want to sort from z-a? This code may be useful
bool cmp(string a, string b)
{
if(a.compare(b) > 0)
return true;
else
return false;
}
int main()
{
string words[] = {"this", "a", "test", "is"};
int length = sizeof(words) / sizeof(string);
sort(words, words + length, cmp);
for(int i = 0; i < length; i++)
cout << words[i] << " ";
cout << endl;
// output will be: this test is a
}
If you want to reverse the order of sorting just modify the sign in the cmp function.
Hope this is helpful :)
Cheers!!!
If you can get their timezone offset, you can just add it to the current timestamp and then use the gmdate function to get their local time.
// let's say they're in the timezone GMT+10
$theirOffset = 10; // $_GET['offset'] perhaps?
$offsetSeconds = $theirOffset * 3600;
echo gmdate("l", time() + $offsetSeconds);
On older browsers, :hover
only worked on <a>
elements. So you'd have to do something like this to get it to work.
<style>
a#aks
{
width:100px;
height:100px;
display:block;
}
a#aks:link
{
background-image: url('http://dummyimage.com/100x100/000/fff');
}
a#aks:hover
{
background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}
</style>
<a href="#" id="aks"></a>
Got it working. Here was my procedure:
Sources
tab in chrome inspectorElements
tab in inspectora=[]
for j in range(3):
a.append([int(i) for i in input().split()])
In this above code the given input i.e Mike 18 Kevin 35 Angel 56, will be stored in an array 'a' and gives the output as [['Mike', '18'], ['Kevin', '35'], ['Angel', '56']].
Use $.prop()
$("#descrip").prop("readonly",true);
$("#descrip").prop("readonly",false);
What worked for me: I finally noticed the Build Executor Status window on the left on the main Jenkins dashboard. I run a dev/test instance on my local system with 2 executors. Both were currently occupied with builds that were not running. Upon cancelling these to jobs, my third (pending) job was able to run.
You could also do it in two steps:
remove = [k for k in mydict if k == val]
for k in remove: del mydict[k]
My favorite approach is usually to just make a new dict:
# Python 2.7 and 3.x
mydict = { k:v for k,v in mydict.items() if k!=val }
# before Python 2.7
mydict = dict((k,v) for k,v in mydict.iteritems() if k!=val)
__init__.py
file in src
folder src
folder as a source rootPYTHONPATH
(see above)Just use a wrapper div with "float: left" and put boxes inside also containing float: left:
CSS:
wrapperline{
width: 300px;
float: left;
height: 60px;
background-color:#CCCCCC;}
.boxinside{
width: 50px;
float: left;
height: 50px;
margin: 5px;
background-color:#9C0;
float:left;}
HTML:
<div class="wrapperline">
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
<div class="boxinside">Box 1</div>
</div>
for windows 10 press windows key type cred and you should see "Credential Manager" in Control Panel click to open and then remove the related cached credentials then try again, it will ask user id password key in the correct password and you'll be good.
Happened with me when I changed my network password
Things have changed quite a bit since 2010 when this was posted and I haven't tried all the other answers but I have tried a few, and I found this to work the best for me using python3.6.
I was able to fetch about ~150 unique domains per second running on AWS.
import pandas as pd
import concurrent.futures
import requests
import time
out = []
CONNECTIONS = 100
TIMEOUT = 5
tlds = open('../data/sample_1k.txt').read().splitlines()
urls = ['http://{}'.format(x) for x in tlds[1:]]
def load_url(url, timeout):
ans = requests.head(url, timeout=timeout)
return ans.status_code
with concurrent.futures.ThreadPoolExecutor(max_workers=CONNECTIONS) as executor:
future_to_url = (executor.submit(load_url, url, TIMEOUT) for url in urls)
time1 = time.time()
for future in concurrent.futures.as_completed(future_to_url):
try:
data = future.result()
except Exception as exc:
data = str(type(exc))
finally:
out.append(data)
print(str(len(out)),end="\r")
time2 = time.time()
print(f'Took {time2-time1:.2f} s')
print(pd.Series(out).value_counts())
Depending on your table type, locking will perform differently, but so will a SELECT count. For MyISAM tables a simple SELECT count(*) FROM table should not lock the table since it accesses meta data to pull the record count. Innodb will take longer since it has to grab the table in a snapshot to count the records, but it shouldn't cause locking.
You should at least have concurrent_insert set to 1 (default). Then, if there are no "gaps" in the data file for the table to fill, inserts will be appended to the file and SELECT and INSERTs can happen simultaneously with MyISAM tables. Note that deleting a record puts a "gap" in the data file which will attempt to be filled with future inserts and updates.
If you rarely delete records, then you can set concurrent_insert equal to 2, and inserts will always be added to the end of the data file. Then selects and inserts can happen simultaneously, but your data file will never get smaller, no matter how many records you delete (except all records).
The bottom line, if you have a lot of updates, inserts and selects on a table, you should make it InnoDB. You can freely mix table types in a system though.
I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.
import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')
In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,
plt.legend(handles=[red_patch, black_patch])
And the legend ought to appear in the pointplot.
UILabel
called: myLabel
.#import <QuartzCore/QuartzCore.h>
in your viewDidLoad
write this line: self.myLabel.layer.cornerRadius = 8;
Good luck
You could use this to wrap urllib2:
def URLRequest(url, params, method="GET"):
if method == "POST":
return urllib2.Request(url, data=urllib.urlencode(params))
else:
return urllib2.Request(url + "?" + urllib.urlencode(params))
That will return a Request object that has result data and response codes.
I have tried several options, but this one finally solved my problem. I re-imported the project by following these steps in IntelliJ:
Choose your project from 'Select File or Directory to Import'
In the next screen choose 'Import Project From external model', and choose 'Maven.
For me re-importing maven projects did not solve the issue for an existing projects.
Strings in C# already have a char indexer
string test = "this is a test";
Console.WriteLine(test[0]);
And...
if(test[0] == 't')
Console.WriteLine("The first letter is 't'");
This works too...
Console.WriteLine("this is a test"[0]);
And this...
foreach (char c in "this is a test")
Console.WriteLine(c);
EDIT:
I noticed the question was updated with regards to char[] arrays. If you must have a string[] array, here's how you split a string at each character in c#:
string[] test = Regex.Split("this is a test", string.Empty);
foreach (string s in test)
{
Console.WriteLine(s);
}
While the code to create a custom Attribute is fairly simple, it's very important that you understand what attributes are:
Attributes are metadata compiled into your program. Attributes themselves do not add any functionality to a class, property or module - just data. However, using reflection, one can leverage those attributes in order to create functionality.
So, for instance, let's look at the Validation Application Block, from Microsoft's Enterprise Library. If you look at a code example, you'll see:
/// <summary>
/// blah blah code.
/// </summary>
[DataMember]
[StringLengthValidator(8, RangeBoundaryType.Inclusive, 8, RangeBoundaryType.Inclusive, MessageTemplate = "\"{1}\" must always have \"{4}\" characters.")]
public string Code { get; set; }
From the snippet above, one might guess that the code will always be validated, whenever changed, accordingly to the rules of the Validator (in the example, have at least 8 characters and at most 8 characters). But the truth is that the Attribute does nothing; as mentioned previously, it only adds metadata to the property.
However, the Enterprise Library has a Validation.Validate
method that will look into your object, and for each property, it'll check if the contents violate the rule informed by the attribute.
So, that's how you should think about attributes -- a way to add data to your code that might be later used by other methods/classes/etc.
You can auto generate Image map from this website for selected area of image. https://www.image-map.net/
Easiest way to execute!
I cross over the same problem
I put the following code in the folder ~/.gvimrc
and it works.
set guifont=Monaco:h20
exit() should do it.
There seems to be a process that suppresses all console.log messages if there are too many alerts in a JS script. That's a problem if you are trying to debug a script. I've been running a script on Chrome and Brave and all of a sudden console.log messages were stopped. Yet with Firefox all the console.log messages still appear... same exact script. The problem is not checking or unchecking the warnings, errors, and debug messages.
I'm at a loss for this... is it Windows blocking "a site"? I tried clearing the cache resetting all settings in Chrome, yet the problem still remains. I suppose I could try reinstalling both browsers.
List<String[]> addresses = new ArrayList<String[]>();
String[] addressesArr = new String[3];
addressesArr[0] = "zero";
addressesArr[1] = "one";
addressesArr[2] = "two";
addresses.add(addressesArr);
in build file change compile files('AF-Android-SDK.jar') to compile files('libs/AF-Android-SDK.jar') it will work
Please refer here https://code.google.com/p/selenium/issues/detail?id=6756 In crux
Please open the system display settings and ensure that font size is set to 100% It worked surprisingly
First, implement indexOf
in JavaScript for browsers that don't already have it. For example, see Erik Arvidsson's array extras (also, the associated blog post). And then you can use indexOf
without worrying about browser support. Here's a slightly optimised version of his indexOf
implementation:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
It's changed to store the length so that it doesn't need to look it up every iteration. But the difference isn't huge. A less general purpose function might be faster:
var include = Array.prototype.indexOf ?
function(arr, obj) { return arr.indexOf(obj) !== -1; } :
function(arr, obj) {
for(var i = -1, j = arr.length; ++i < j;)
if(arr[i] === obj) return true;
return false;
};
I prefer using the standard function and leaving this sort of micro-optimization for when it's really needed. But if you're keen on micro-optimization I adapted the benchmarks that roosterononacid linked to in the comments, to benchmark searching in arrays. They're pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.
For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels
input:checked + label {
color: white;
}
MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.
I don't know about Oracle but I know that the old syntax is being deprecated in SQL Server and will disappear eventually. Before I used that old syntax in a new query I would check what Oracle plans to do with it.
I prefer the newer syntax rather than the mixing of the join criteria with other needed where conditions. In the newer syntax it is much clearer what creates the join and what other conditions are being applied. Not really a big problem in a short query like this, but it gets much more confusing when you have a more complex query. Since people learn on the basic queries, I would tend to prefer people learn to use the join syntax before they need it in a complex query.
And again I don't know Oracle specifically, but I know the SQL Server version of the old style left join is flawed even in SQL Server 2000 and gives inconsistent results (sometimes a left join sometimes a cross join), so it should never be used. Hopefully Oracle doesn't suffer the same issue, but certainly left and right joins can be mcuh harder to properly express in the old syntax.
Plus it has been my experience (and of course this is strictly a personal opinion, you may have differnt experience) that developers who use the ANSII standard joins tend to have a better understanding of what a join is and what it means in terms of getting data out of the database. I belive that is becasue most of the people with good database understanding tend to write more complex queries and those seem to me to be far easier to maintain using the ANSII Standard than the old style.
If you are just looking to get a single value from the XML you may want to use Java's XPath library. For an example see my answer to a previous question:
It would look something like:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Demo {
public static void main(String[] args) {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document dDoc = builder.parse("E:/test.xml");
XPath xPath = XPathFactory.newInstance().newXPath();
Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE);
System.out.println(node.getNodeValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can change colors UITabBarItem by storyboard but if you want to change colors by code it's very easy:
// Use this for change color of selected bar
[[UITabBar appearance] setTintColor:[UIColor blueColor]];
// This for change unselected bar (iOS 10)
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor yellowColor]];
// And this line for change color of all tabbar
[[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
I have a function which returns a CLOB and I was seeing the above error when I'd forgotten to declare the return value as an output parameter. Initially I had:
protected SimpleJdbcCall buildJdbcCall(JdbcTemplate jdbcTemplate)
{
SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(catalog)
.withFunctionName(functionName)
.withReturnValue()
.declareParameters(buildSqlParameters());
return call;
}
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
};
}
The buildSqlParameters method should have included the SqlOutParameter:
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
new SqlOutParameter("l_clob", Types.CLOB) // <-- This was missing!
};
}
This can also be achieved using the Lambda based approach of Linq;
var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);
Go to Eclipse, Click on Window from Menu bar then "Open Perspective -> other -> SVN Repository Exploring -> Click OK"
Now, after performing "Click OK" you need to go to truck (or place where your project is saved in SVN) then select project(which you want to Delete) then right click -> Delete.
This Will Delete project from subversion.
If your <option>
elements don't have value
attributes, then you can just use .val
:
$selectElement.val("text_you're_looking_for")
However, if your <option>
elements have value attributes, or might do in future, then this won't work, because whenever possible .val
will select an option by its value
attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value
attributes, so we'll have to add one ourselves with a simple plugin:
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function () {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$options = $selectElement.find('option');
$targetOption = $options.filter(
function () {return jQuery(this).text() == targetText}
);
// We use `.prop` if it's available (which it should be for any jQuery
// versions above and including 1.6), and fall back on `.attr` (which
// was used for changing DOM properties in pre-1.6) otherwise.
if ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
Just include this plugin somewhere after you add jQuery onto the page, and then do
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
to select options.
The plugin method uses filter
to pick out only the option
matching the targetText, and selects it using either .attr
or .prop
, depending upon jQuery version (see .prop() vs .attr() for explanation).
Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/
As others have pointed out, ideally, the foreign key would be created as a reference to a primary key (usually an IDENTITY column). However, we don't live in an ideal world, and sometimes even a "small" change to a schema can have significant ripple effects to the application logic.
Consider the case of a Customer table with a SSN column (and a dumb primary key), and a Claim table that also contains a SSN column (populated by business logic from the Customer data, but no FK exists). The design is flawed, but has been in use for several years, and three different applications have been built on the schema. It should be obvious that ripping out Claim.SSN and putting in a real PK-FK relationship would be ideal, but would also be a significant overhaul. On the other hand, putting a UNIQUE constraint on Customer.SSN, and adding a FK on Claim.SSN, could provide referential integrity, with little or no impact on the applications.
Don't get me wrong, I'm all for normalization, but sometimes pragmatism wins over idealism. If a mediocre design can be helped with a band-aid, surgery might be avoided.
As of "ConstraintLayout1.1.0-beta1" you can use percent to define widths & heights.
android:layout_width="0dp"
app:layout_constraintWidth_default="percent"
app:layout_constraintWidth_percent=".4"
This will define the width to be 40% of the width of the screen. A combination of this and guidelines in percent allows you to create any percent-based layout you want.
The problem with your desired output is that it is not valid json document,; it's a stream of json documents!
That's okay, if its what you need, but that means that for each document you want in your output, you'll have to call json.dumps
.
Since the newline you want separating your documents is not contained in those documents, you're on the hook for supplying it yourself. So we just need to pull the loop out of the call to json.dump and interpose newlines for each document written.
import csv
import json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
you can try to reinstall the latest version of xcode / dev. tools for snow leopard - this should fix your errors
The assignment operator has lower precedence than &&
, so your condition is equivalent to:
if ((match == 0 && k) = m)
But the left-hand side of this is an rvalue, namely the boolean resulting from the evaluation of the subexpression match == 0 && k
, so you cannot assign to it.
By contrast, comparison has higher precedence, so match == 0 && k == m
is equivalent to:
if ((match == 0) && (k == m))
you can use this function to download file from base64.
function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}
This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.
i hope this will help of you thanks
You can fix it like this:
$scope.hoverIn = function(){
this.hoverEdit = true;
};
$scope.hoverOut = function(){
this.hoverEdit = false;
};
Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.
Also you need to put ngRepeat
on li
:
<ul>
<li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
{{task.name}}
<span ng-show="hoverEdit">
<a>Edit</a>
</span>
</li>
</ul>
However, when possible try to do such things with CSS only, this would be the optimal solution and no JS required:
ul li span {display: none;}
ul li:hover span {display: inline;}
If you're using Cloudera 5.x, Here in this documentation is mentioned that Lily maintains the Real time updations and deletions also.
Configuring the Lily HBase NRT Indexer Service for Use with Cloudera Search
As HBase applies inserts, updates, and deletes to HBase table cells, the indexer keeps Solr consistent with the HBase table contents, using standard HBase replication.
Not sure iftruncate 'hTable'
is also supported in the same.
Else you create a Trigger or Service to clear up your data from both Solr and HBase on a particular Event or anything.
I believe you are not the only one who has problems when trying to deploy Crystal Report for VS 2010. Based on the error message you had, have you checked:
Please make sure you just have one CR version installed on your system. If you do have other CR version installed, consider to uninstall it so that your application is not "confused" about the CR version.
You need to make sure you download the correct CR version. Since you are using VS 2010, you need to refer to CRforVS_redist_install_64bit_13_0_1.zip (for 64 bit machine) or CRforVS_redist_install_32bit_13_0_1.zip (for 32 bit machine). These two are the redistributable packages. You can download full package from the below link as well: CRforVS_13_0_1.exe Note: It is sometimes necessary to install 32bit CR runtime even on 64bit OS
Make sure you setup FULL TRUST permission on your root folder
The LOCAL SERVICE permission must be setup on your application pool
Make sure the aspnet_client folder exists on your root folder.
If you can make sure all the 5 points above, your Crystal Report should work without any fuss.
Another important thing to note down here is that if you host your Crystal Report with a shared host, you need to check it with them of whether they really support Crystal Report. If you still have problems, you can switch to http://www.asphostcentral.com, who provides Crystal Report support.
Good luck!
In your statement, you are comparing a string called start_date with the time.
If start_date is a column, it should either be
SELECT * FROM `la_schedule` WHERE start_date >'2012-11-18';
(no apostrophe) or
SELECT * FROM `la_schedule` WHERE `start_date` >'2012-11-18';
(with backticks).
Hope this helps.
Actually the orderBy
filter can take as a parameter not only a string but also a function. From the orderBy
documentation: https://docs.angularjs.org/api/ng/filter/orderBy):
function: Getter function. The result of this function will be sorted using the <, =, > operator.
So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:
$scope.myValueFunction = function(card) {
return card.values.opt1 + card.values.opt2;
};
and then, in your template:
ng-repeat="card in cards | orderBy:myValueFunction"
The other thing worth noting is that orderBy
is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy
should be enough for most uses cases).
Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxImage.Checked)
{
groupBoxImage.Show();
}
else if (!checkBoxImage.Checked)
{
groupBoxImage.Hide();
}
}
Add the below code
input[type="submit"]:hover {
border: 1px solid #999;
color: #000;
}
If you need only for these button then you can add id name
#paginate input[type="submit"]:hover {
border: 1px solid #999;
color: #000;
}
I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.
Example:
I came up with a solution similar to Christians but without depending on the Community MSBuild tasks, this is not an option for me as I do not want to install these tasks for all of our developers.
I am generating code and compiling to an Assembly and want to auto-increment version numbers. However, I can not use the VS 6.0.* AssemblyVersion trick as it auto-increments build numbers each day and breaks compatibility with Assemblies that use an older build number. Instead, I want to have a hard-coded AssemblyVersion but an auto-incrementing AssemblyFileVersion. I've accomplished this by specifying AssemblyVersion in the AssemblyInfo.cs and generating a VersionInfo.cs in MSBuild like this,
<PropertyGroup>
<Year>$([System.DateTime]::Now.ToString("yy"))</Year>
<Month>$([System.DateTime]::Now.ToString("MM"))</Month>
<Date>$([System.DateTime]::Now.ToString("dd"))</Date>
<Time>$([System.DateTime]::Now.ToString("HHmm"))</Time>
<AssemblyFileVersionAttribute>[assembly:System.Reflection.AssemblyFileVersion("$(Year).$(Month).$(Date).$(Time)")]</AssemblyFileVersionAttribute>
</PropertyGroup>
<Target Name="BeforeBuild">
<WriteLinesToFile File="Properties\VersionInfo.cs" Lines="$(AssemblyFileVersionAttribute)" Overwrite="true">
</WriteLinesToFile>
</Target>
This will generate a VersionInfo.cs file with an Assembly attribute for AssemblyFileVersion where the version follows the schema of YY.MM.DD.TTTT with the build date. You must include this file in your project and build with it.
This might Help You
SpannableStringBuilder ssBuilder;
ssBuilder = new SpannableStringBuilder(" ");
// working code ImageSpan image = new ImageSpan(textView.getContext(), R.drawable.image);
Drawable image = ContextCompat.getDrawable(textView.getContext(), R.drawable.image);
float scale = textView.getContext().getResources().getDisplayMetrics().density;
int width = (int) (12 * scale + 0.5f);
int height = (int) (18 * scale + 0.5f);
image.setBounds(0, 0, width, height);
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BASELINE);
ssBuilder.setSpan(
imageSpan, // Span to add
0, // Start of the span (inclusive)
1, // End of the span (exclusive)
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);// Do not extend the span when text add later
ssBuilder.append(" " + text);
ssBuilder = new SpannableStringBuilder(text);
textView.setText(ssBuilder);
element.offsetLeft
and element.offsetTop
are the pure javascript properties for finding an element's position with respect to its offsetParent
; being the nearest parent element with a position of relative
or absolute
Alternatively, you can always use Zepto to get the position of an element AND its parent, and simply subtract the two:
var childPos = obj.offset();
var parentPos = obj.parent().offset();
var childOffset = {
top: childPos.top - parentPos.top,
left: childPos.left - parentPos.left
}
This has the benefit of giving you the offset of a child relative to its parent even if the parent isn't positioned.
After struggling with this for a few days, it turns out that you can't do a window.location.reload() after a window.history.go(-2)
, because the code stops running after the window.history.go(-2)
. Also the html spec basically views a history.go(-2)
to the the same as hitting the back button and should retrieve the page as it was instead of as it now may be. There was some talk of setting caching headers in the webserver to turn off caching but I did not want to do this.
The solution for me was to use session storage to set a flag in the browser with sessionStorage.setItem('refresh', 'true');
Then in the "theme" or the next page that needs to be refreshed do:
if (sessionStorage.getItem("refresh") == "true") {
sessionStorage.removeItem("refresh"); window.location.reload()
}
So basically tell it to reload in the sessionStorage then check for that at the top of the page that needs to be reloaded.
Hope this helps someone with this bit of frustration.
In case your data are stored as a Pandas DataFrame
, you can use remove_stopwords
from textero that use the NLTK stopwords list by default.
import pandas as pd
import texthero as hero
df['text_without_stopwords'] = hero.remove_stopwords(df['text'])
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
Collection is a base interface for most collection classes (it is the root interface of java collection framework) Collections is a utility class
Collections class is a utility class having static methods It implements Polymorphic algorithms which operate on collections.
Default log location (rhel) are
General messages:
/var/log/messages
Authentication messages:
/var/log/secure
Mail events:
/var/log/maillog
Check your /etc/syslog.conf
or /etc/syslog-ng.conf
(it depends on which of syslog facility you have installed)
Example:
$ cat /etc/syslog.conf
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none /var/log/messages
# The authpriv file has restricted access.
authpriv.* /var/log/secure
# Log all the mail messages in one place.
mail.* /var/log/maillog
#For a start, use this simplified approach.
*.* /var/log/messages
Generate QR Code Image in ASP.NET Using Google Chart API
Google Chart API returns an image in response to a URL GET or POST request. All the data required to create the graphic is included in the URL, including the image type and size.
var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chs={1}x{2}&chl={0}", txtCode.Text, txtWidth.Text, txtHeight.Text);
WebResponse response = default(WebResponse);
Stream remoteStream = default(Stream);
StreamReader readStream = default(StreamReader);
WebRequest request = WebRequest.Create(url);
response = request.GetResponse();
remoteStream = response.GetResponseStream();
readStream = new StreamReader(remoteStream);
System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);
img.Save("D:/QRCode/" + txtCode.Text + ".png");
response.Close();
remoteStream.Close();
readStream.Close();
txtCode.Text = string.Empty;
txtWidth.Text = string.Empty;
txtHeight.Text = string.Empty;
lblMsg.Text = "The QR Code generated successfully";
Click here for complete source code to download
Demo of application for free QR Code generator using C#
Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security
. Your JAVA_HOME should always be ../JAVA/JDK
.
<MyComponent />
compiles to React.createElement(MyComponent, {})
, which expects a string (HTML tag) or a function (ReactClass) as first parameter.
You could just store your component class in a variable with a name that starts with an uppercase letter. See HTML tags vs React Components.
var MyComponent = Components[type + "Component"];
return <MyComponent />;
compiles to
var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});
You can also use this library which wraps HttpWebRequest and Response into simple methods that return objects based on the results. It uses some of the techniques described in these answers and has plenty of code inspired by answers from this and similar threads. It automatically catches any exceptions, seeks to abstract as much boiler plate code needed to make these web requests as possible, and automatically deserializes the response object.
An example of what your code would look like using this wrapper is as simple as
var response = httpClient.Get<SomeResponseObject>(request);
if(response.StatusCode == HttpStatusCode.OK)
{
//do something with the response
console.Writeline(response.Body.Id); //where the body param matches the object you pass in as an anonymous type.
}else {
//do something with the error
console.Writelint(string.Format("{0}: {1}", response.StatusCode.ToString(), response.ErrorMessage);
}
Full disclosure This library is a free open source wrapper library, and I am the author of said library. I make no money off of this but have found it immensely useful over the years and am sure anyone who is still using the HttpWebRequest / HttpWebResponse classes will too.
It is not a silver bullet but supports get, post, delete with both async and non-async for get and post as well as JSON or XML requests and responses. It is being actively maintained as of 6/21/2020
No, a div is a body element, not a head element
EDIT: Then the only thing SEs are going to get is the base HTML, not the ajax modified one.
You can use with express ^4.15.4:
var express = require('express'),
router = express.Router();
router.get('/', function (req, res, next) {
console.log(req.query);
});
Hope this helps.
www.phplivedocx.org is a SOAP based service that means that you always need to be online for testing the Files also does not have enough examples for its use . Strangely I found only after 2 days of downloading (requires additionaly zend framework too) that its a SOAP based program(cursed me !!!)...I think without COM its just not possible on a Linux server and the only idea is to change the doc file in another usable file which PHP can parse...
For Typescript users willing to set and get typed properties:
/**
* Silly wrapper to be able to type the storage keys
*/
export class TypedStorage<T> {
public removeItem(key: keyof T): void {
localStorage.removeItem(key);
}
public getItem<K extends keyof T>(key: K): T[K] | null {
const data: string | null = localStorage.getItem(key);
return JSON.parse(data);
}
public setItem<K extends keyof T>(key: K, value: T[K]): void {
const data: string = JSON.stringify(value);
localStorage.setItem(key, data);
}
}
// write an interface for the storage
interface MyStore {
age: number,
name: string,
address: {city:string}
}
const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();
storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok
const address: {city:string} = storage.getItem("address");
Here is an excerpts from "Effective Python: 90 Specific Ways to Write Better Python" (Amazing book. I highly recommend it).
Things to Remember
? Define new class interfaces using simple public attributes and avoid defining setter and getter methods.
? Use @property to define special behavior when attributes are accessed on your objects, if necessary.
? Follow the rule of least surprise and avoid odd side effects in your @property methods.
? Ensure that @property methods are fast; for slow or complex work—especially involving I/O or causing side effects—use normal methods instead.
One advanced but common use of @property is transitioning what was once a simple numerical attribute into an on-the-fly calculation. This is extremely helpful because it lets you migrate all existing usage of a class to have new behaviors without requiring any of the call sites to be rewritten (which is especially important if there’s calling code that you don’t control). @property also provides an important stopgap for improving interfaces over time.
I especially like @property because it lets you make incremental progress toward a better data model over time.
@property is a tool to help you address problems you’ll come across in real-world code. Don’t overuse it. When you find yourself repeatedly extending @property methods, it’s probably time to refactor your class instead of further paving over your code’s poor design.? Use @property to give existing instance attributes new functionality.
? Make incremental progress toward better data models by using @property.
? Consider refactoring a class and all call sites when you find yourself using @property too heavily.
DOS/Windows standard "newline" is CRLF (= \r\n) and not LFCR (\n\r). If we put the latter, it's likely to produce some unexpected (well, in fact, kind of expected! :D) behaviors.
Nowadays almost all (well written) programs accept the UNIX standard LF (\n) for newline code, even mail sender daemons (RFC sets CRLF as newline for headers and message body).
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
SELECT Top(12) Month, Year, Code FROM TempEmp
ORDER BY Year DESC,month DESC
you can use line.seperator
for appending new line in
You can use bootstrap tooltip. Do not forget to initialize it.
<span class="tooltip-r" data-toggle="tooltip" data-placement="left" title="Explanation">
inside span
</span>
Will be shown text Explanation on the left side.
and run it with js:
$('.tooltip-r').tooltip();
Just adding in for JupyterLab users. Ctrl, (advanced settings) and pasting the below in User References under keyboard shortcuts does the trick for me.
{
"shortcuts": [
{
"command": "notebook:hide-cell-outputs",
"keys": [
"H"
],
"selector": ".jp-Notebook:focus"
},
{
"command": "notebook:show-cell-outputs",
"keys": [
"Shift H"
],
"selector": ".jp-Notebook:focus"
}
]
}
Both questions are answered in git status
.
To unstage adding a new file use git rm --cached filename.ext
# Changes to be committed:
# (use "git rm --cached <file>..." to unstage)
#
# new file: test
To unstage deleting a file use git reset HEAD filename.ext
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: test
In the other hand, git checkout --
never unstage, it just discards non-staged changes.
Inspired from this https://www.youtube.com/watch?v=GafjS0FfAC0
following
1) optimal sub problem
2) Overlapping sub problem principles
introduced in the video
using System;
using System.Collections.Generic;
using System.Linq;
namespace UnitTests.moneyChange
{
public class MoneyChangeCalc
{
private static int[] _coinTypes;
private Dictionary<int, int> _solutions;
public MoneyChangeCalc(int[] coinTypes)
{
_coinTypes = coinTypes;
Reset();
}
public int Minimun(int amount)
{
for (int i = 2; i <= amount; i++)
{
IList<int> candidates = FulfillCandidates(i);
try
{
_solutions.Add(i, candidates.Any() ? (candidates.Min() + 1) : 0);
}
catch (ArgumentException)
{
Console.WriteLine("key [{0}] = {1} already added", i, _solutions[i]);
}
}
int minimun2;
_solutions.TryGetValue(amount, out minimun2);
return minimun2;
}
internal IList<int> FulfillCandidates(int amount)
{
IList<int> candidates = new List<int>(3);
foreach (int coinType in _coinTypes)
{
int sub = amount - coinType;
if (sub < 0) continue;
int candidate;
if (_solutions.TryGetValue(sub, out candidate))
candidates.Add(candidate);
}
return candidates;
}
private void Reset()
{
_solutions = new Dictionary<int, int>
{
{0,0}, {_coinTypes[0] ,1}
};
}
}
}
Test cases:
using NUnit.Framework;
using System.Collections;
namespace UnitTests.moneyChange
{
[TestFixture]
public class MoneyChangeTest
{
[TestCaseSource("TestCasesData")]
public int Test_minimun2(int amount, int[] coinTypes)
{
var moneyChangeCalc = new MoneyChangeCalc(coinTypes);
return moneyChangeCalc.Minimun(amount);
}
private static IEnumerable TestCasesData
{
get
{
yield return new TestCaseData(6, new[] { 1, 3, 4 }).Returns(2);
yield return new TestCaseData(3, new[] { 2, 4, 6 }).Returns(0);
yield return new TestCaseData(10, new[] { 1, 3, 4 }).Returns(3);
yield return new TestCaseData(100, new[] { 1, 5, 10, 20 }).Returns(5);
}
}
}
}
Another possible reason:
That is my server storage space. My server disk space become full. So, I have removed few files and folders in my server and tried.
It was worked!!!
I am saving my session in AWS Dynamo DB, but it still expects some space in my server to process the session. Not sure why!!!
Possibly multiple jquery.js file are added in , and the conflict appeared.
Here is the code on how to merge two sorted linked lists headA and headB:
Node* MergeLists1(Node *headA, Node* headB)
{
Node *p = headA;
Node *q = headB;
Node *result = NULL;
Node *pp = NULL;
Node *qq = NULL;
Node *head = NULL;
int value1 = 0;
int value2 = 0;
if((headA == NULL) && (headB == NULL))
{
return NULL;
}
if(headA==NULL)
{
return headB;
}
else if(headB==NULL)
{
return headA;
}
else
{
while((p != NULL) || (q != NULL))
{
if((p != NULL) && (q != NULL))
{
int value1 = p->data;
int value2 = q->data;
if(value1 <= value2)
{
pp = p->next;
p->next = NULL;
if(result == NULL)
{
head = result = p;
}
else
{
result->next = p;
result = p;
}
p = pp;
}
else
{
qq = q->next;
q->next = NULL;
if(result == NULL)
{
head = result = q;
}
else
{
result->next = q;
result = q;
}
q = qq;
}
}
else
{
if(p != NULL)
{
pp = p->next;
p->next = NULL;
result->next = p;
result = p;
p = pp;
}
if(q != NULL)
{
qq = q->next;
q->next = NULL;
result->next = q;
result = q;
q = qq;
}
}
}
}
return head;
}
Just use os.path.join
to join your path with the filename and extension. Use sys.argv
to access arguments passed to the script when executing it:
#!/usr/bin/env python3
# coding: utf-8
# import netCDF4 as nc
import numpy as np
import numpy.ma as ma
import csv as csv
import os.path
import sys
basedir = '/data/reu_data/soil_moisture/'
suffix = 'nc'
def read_fid(filename):
fid = nc.MFDataset(filename,'r')
fid.close()
return fid
def read_var(file, varname):
fid = nc.Dataset(file, 'r')
out = fid.variables[varname][:]
fid.close()
return out
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please specify a year')
else:
filename = os.path.join(basedir, '.'.join((sys.argv[1], suffix)))
time = read_var(ncf, 'time')
lat = read_var(ncf, 'lat')
lon = read_var(ncf, 'lon')
soil = read_var(ncf, 'soilw')
Simply run the script like:
# on windows-based systems
python script.py year
# on unix-based systems
./script.py year
--force-reinstall
doesn't appear to force reinstall using python2.7 with pip-1.5
I've had to use
--no-deps --ignore-installed
Syntax:
$data = Model::whereIn('field_name', [1, 2, 3])->get();
Use for Users Model
$usersList = Users::whereIn('id', [1, 2, 3])->get();
I find this one-line code as most efficient and useful:
File file = new File(ClassLoader.getSystemResource("com/path/to/file.txt").getFile());
Works like a charm.
Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.
In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like
var items = list
.filter((i, index) => (index < 3))
.map((i, index) => {
return (
<myview item={i} key={i.id} />
);
});
Ohk.. I got it running by typing /usr/bin/phpize
instead of only phpize
.
Assuming you have a Z:
drive mapped:
Get-ChildItem -Path "Z:" -Recurse | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq "hosts" }
These are all close to the right answer, but I wouldn't say any solve the problem while remaining most readable to others reading your code. I'd say that answer is a combination of BrenBarn's Answer and tuomasttik's comment below that answer. BrenBarn's answer utilizes isspace
builtin, but does not support removing empty strings, as OP requested, and I would tend to attribute that as the standard use case of replacing strings with null.
I rewrote it with .apply
, so you can call it on a pd.Series
or pd.DataFrame
.
Python 3:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and x.isspace() else x)
To use this in Python 2, you'll need to replace str
with basestring
.
Python 2:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)
Just use
as.Date("2001-01-01") + 45
from base R, or date functionality in one of the many contributed packages. My RcppBDT package wraps functionality from Boost Date_Time including things like 'date of third Wednesday' in a given month.
Edit: And egged on by @Andrie, here is a bit more from RcppBDT (which is mostly a test case for Rcpp modules, really).
R> library(RcppBDT)
Loading required package: Rcpp
R>
R> str(bdt)
Reference class 'Rcpp_date' [package ".GlobalEnv"] with 0 fields
and 42 methods, of which 31 are possibly relevant:
addDays, finalize, fromDate, getDate, getDay, getDayOfWeek, getDayOfYear,
getEndOfBizWeek, getEndOfMonth, getFirstDayOfWeekAfter,
getFirstDayOfWeekInMonth, getFirstOfNextMonth, getIMMDate, getJulian,
getLastDayOfWeekBefore, getLastDayOfWeekInMonth, getLocalClock, getModJulian,
getMonth, getNthDayOfWeek, getUTC, getWeekNumber, getYear, initialize,
setEndOfBizWeek, setEndOfMonth, setFirstOfNextMonth, setFromLocalClock,
setFromUTC, setIMMDate, subtractDays
R> bdt$fromDate( as.Date("2001-01-01") )
R> bdt$addDays( 45 )
R> print(bdt)
[1] "2001-02-15"
R>
An iterative function to free your list:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
What the function is doing is the follow:
check if head
is NULL, if yes the list is empty and we just return
Save the head
in a tmp
variable, and make head
point to the next node on your list (this is done in head = head->next
free(tmp)
variable, and head
just points to the rest of the list, go back to step 1 Here is a detailed explanation & solution for this problem from ibm.
Problem(Abstract)
Request to HTTP Server fails with Response code 400.
Symptom
Response from the browser could be shown like this:
Bad Request Your browser sent a request that this server could not understand. Size of a request header field exceeds server limit.
HTTP Server Error.log shows the following message: "request failed: error reading the headers"
Cause
This is normally caused by having a very large Cookie, so a request header field exceeded the limit set for Web Server.
Diagnosing the problem
To assist with diagnose of the problem you can add the following to the LogFormat directive in the httpd.conf: error-note: %{error-notes}n
Resolving the problem
For server side: Increase the value for the directive LimitRequestFieldSize in the httpd.conf: LimitRequestFieldSize 12288 or 16384 For How to set the LimitRequestFieldSize, check Increase the value of LimitRequestFieldSize in Apache
For client side: Clear the cache of your web browser should be fine.
I don't have enough rep to put this under comments to the existing answers:
unescape
is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent
converts a js string to escaped UTF-8 and decodeURIComponent
only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error
because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // ©
So you need to know your data when using decodeURIComponent.
decodeURIComponent won't work on "%C2"
or any lone byte over 0x7f
because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you ©
Unescape wouldn't work properly on that // ©
AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.
You have to be cautious of double line breaks, which would cause double spaces. Use this really efficient regular expression:
$string = trim(preg_replace('/\s\s+/', ' ', $string));
Multiple spaces and newlines are replaced with a single space.
Edit: As others have pointed out, this solution has issues matching single newlines in between words. This is not present in the example, but one can easily see how that situation could occur. An alternative is to do the following:
$string = trim(preg_replace('/\s+/', ' ', $string));
If your AWK doesn't have strftime()
:
ping host | perl -nle 'print scalar(localtime), " ", $_'
To redirect it to a file, use standard shell redirection and turn off output buffering:
ping host | perl -nle 'BEGIN {$|++} print scalar(localtime), " ", $_' > outputfile
If you want ISO8601 format for the timestamp:
ping host | perl -nle 'use Time::Piece; BEGIN {$|++} print localtime->datetime, " ", $_' > outputfile
You can try
#include <iostream>
#include <conio.h>
int main() {
//some codes
getch();
return 0;
}
install ngrok in terminal
sudo apt-get install -y ngrok-client
after that run:
ngrok http 8000
or
ngrok http example.com:9000
I am using C# mvc Application. I have created a session in the Controller class like this
string description = accessDB.LookupSomeString(key, ImpDate);
this.Session["description"] = description;
in the View, We access the session value and store it in a variable, like this (this is within an $.ajax, but I think it should work within any jquery)
var Sessiondescription = '@Session["description"]';
alert(Sessiondescription);
Try doing this:
py -m pip install pipwin
py -m pipwin install PyAudio
Another way of achieving the same result is to use the @Value annotation:
public class Main {
private Country country;
@Autowired
public void setCountry(@Value("#{country}") Country country) {
this.country = country;
}
}
In this case, the "#{country}
string is an Spring Expression Language (SpEL) expression which evaluates to a bean named country
.
WinSCp now supports S3 protocol
First, make sure your AWS user with S3 access permissions has an “Access key ID” created. You also have to know the “Secret access key”. Access keys are created and managed on Users page of IAM Management Console.
Make sure New site node is selected.
On the New site node, select Amazon S3 protocol.
Enter your AWS user Access key ID and Secret access key
Save your site settings using the Save button.
Login using the Login button.
Use a packet analyzer to intercept the packets to/from somewhere.com
. Studying those packets should tell you what is going on.
Time-outs or connections refused could mean that the remote host is too busy.
Use double braces {{
or }}
so your code becomes:
sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}",
prop.Type, prop.Name));
// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }
A "method" is a "subroutine" is a "procedure" is a "function" is a "subprogram" is a ... The same concept goes under many different names, but basically is a named segment of code that you can "call" from some other code. Generally the code is neatly packaged somehow, with a "header" of some sort which gives its name and parameters and a "body" set off by BEGIN
& END
or {
& }
or some such.
A "consrtructor" is a special form of method whose purpose is to initialize an instance of a class or structure.
In Java a method's header is <qualifiers> <return type> <method name> ( <parameter type 1> <parameter name 1>, <parameter type 2> <parameter name 2>, ...) <exceptions>
and a method body is bracketed by {}
.
And you can tell a constructor from other methods because the constructor has the class name for its <method name>
and has no declared <return type>
.
(In Java, of course, you create a new class instance with the new
operator -- new <class name> ( <parameter list> )
.)
I need to save the phone's timezone in the format [+/-]hh:mm
No, you don't. Offset on its own is not enough, you need to store the whole time zone name/id. For example I live in Oslo where my current offset is +02:00 but in winter (due to dst) it is +01:00. The exact switch between standard and summer time depends on factors you don't want to explore.
So instead of storing + 02:00
(or should it be + 01:00
?) I store "Europe/Oslo"
in my database. Now I can restore full configuration using:
TimeZone tz = TimeZone.getTimeZone("Europe/Oslo")
Want to know what is my time zone offset today?
tz.getOffset(new Date().getTime()) / 1000 / 60 //yields +120 minutes
However the same in December:
Calendar christmas = new GregorianCalendar(2012, DECEMBER, 25);
tz.getOffset(christmas.getTimeInMillis()) / 1000 / 60 //yields +60 minutes
Enough to say: store time zone name or id and every time you want to display a date, check what is the current offset (today) rather than storing fixed value. You can use TimeZone.getAvailableIDs()
to enumerate all supported timezone IDs.
Try:
exec('drop table #tab') -- you can add condition 'if table exists'
exec('select * into #tab from tab')
For me it was the differences between import
and require
on ES6.
E.g.
// processor.js
class Processor {
}
export default Processor
//index.js
const Processor = require('./processor');
const processor = new Processor() //fails with the error
import Processor from './processor'
const processor = new Processor() // succeeds
For anyone interested in applying this solution on a per request basis, this is an option and uses a Lambda expression. The same Lambda expression can be applied to the global filter mentioned by blak3r as well. This method appears to require .NET 4.5.
String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
In .NET 4.0, the Lambda Expression can be applied to the global filter as such
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;