Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
its happen when you try to delete the same object and then again update the same object use this after delete
session.clear();
I struggled with this for a while and only combining the answers in this thread worked for me (on Windows 10):
1. Open cmd or PowerShell and go to the folder with files
2. takeown /R /F .
3. icacls * /T /grant dan:F
Good luck!
You can do it from string
<resources xmlns:tools="http://schemas.android.com/tools">
<string name="total_review"><b>Total Review: </b> </string>
</resources>
and can access it from the java code like
proDuctReviewNumber.setText(getResources().getString(R.string.total_review)+productDetailsSuccess.getProductTotalReview());
This should give you the result you want.
double total = 0;
int number = 0;
float percentage = number / total * 100
printf("%.2f",percentage);
Note that the first operand is a double
One the elements are added, use the rules method to add the rules
//bug fixed thanks to @Sparky
$('input[name^="fileupload"]').each(function () {
$(this).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
})
Demo: Fiddle
Update
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
var $li = $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");
$('#FileUpload' + filenumber).rules('add', {
required: true,
accept: "image/jpeg, image/pjpeg"
})
filenumber++;
return false;
});
I think the reason it doesn't work has something to do with the fact that you have the right
position set, but not the left
.
If you manually set the left
to the current position, it seems to go:
Live example: http://jsfiddle.net/XqqtN/
var left = $('#coolDiv').offset().left; // Get the calculated left position
$("#coolDiv").css({left:left}) // Set the left to its calculated position
.animate({"left":"0px"}, "slow");
EDIT:
Appears as though Firefox behaves as expected because its calculated left
position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto
for the left position.
Because auto
is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)
Setting the left position manually before the animate as above fixes the issue.
If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:
$("#coolDiv").css('left', function(){ return $(this).offset().left; })
.animate({"left":"0px"}, "slow"); ?
Usually you would do it something like this
public class Foo implements Runnable {
private volatile int value;
@Override
public void run() {
value = 2;
}
public int getValue() {
return value;
}
}
Then you can create the thread and retrieve the value (given that the value has been set)
Foo foo = new Foo();
Thread thread = new Thread(foo);
thread.start();
thread.join();
int value = foo.getValue();
tl;dr
a thread cannot return a value (at least not without a callback mechanism). You should reference a thread like an ordinary class and ask for the value.
Dump DB by mongodump
mongodump --host <database-host> -d <database-name> --port <database-port> --out directory
Restore DB by mongorestore
With Index Restore
mongorestore --host <database-host> -d <database-name> --port <database-port> foldername
Without Index Restore
mongorestore --noIndexRestore --host <database-host> -d <database-name> --port <database-port> foldername
Import Single Collection from CSV [1st Column will be treat as Col/Key Name]
mongoimport --db <database-name> --port <database-port> --collection <collection-name> --type csv --headerline --file /path/to/myfile.csv
Import Single Collection from JSON
mongoimport --db <database-name> --port <database-port> --collection <collection-name> --file input.json
I also don't under stand what the "-" means after the 200 140 section of the log
That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)
While most answers are a copy of SolutionYogi's answer, they all miss an important check to see if 'cell' is not null which will return an error if clicking on the headers. So, here is the answer with the check included:
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
// check if not null
if(!cell) return; // no errors!
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
I don't know why this question was reopened but here is a tidyverse
option.
x %>%
arrange(desc(value)) %>%
mutate(variable=fct_reorder(variable,value)) %>%
ggplot(aes(variable,value,fill=variable)) + geom_bar(stat="identity") +
scale_y_continuous("",label=scales::percent) + coord_flip()
You can use Array.IndexOf()
- note that it will return -1 if the element has not been found and you have to handle this case.
int index = Array.IndexOf(stringArray, value);
>>> x = "2342.34"
>>> float(x)
2342.3400000000001
There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).
try Parsing and Formatting
Take an example Parsing
String input = ...;
try {
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMM d yyyy");
LocalDate date = LocalDate.parse(input, formatter);
System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
System.out.printf("%s is not parsable!%n", input);
throw exc; // Rethrow the exception.
}
Formatting
ZoneId leavingZone = ...;
ZonedDateTime departure = ...;
try {
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
String out = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
The output for this example, which prints both the arrival and departure time, is as follows:
LEAVING: Jul 20 2013 07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013 10:20 PM (Asia/Tokyo)
For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html
Just do what cron does, run the following as root
:
run-parts -v /etc/cron.weekly
... or the next one if you receive the "Not a directory: -v" error:
run-parts /etc/cron.weekly -v
Option -v
prints the script names before they are run.
Happy coding!
If you get an error on Internet Explorer, Change the security settings to allow ActiveX
var CallBackFunction = function(content) {
alert(content);
}
ReadFileAllBrowsers(document.getElementById("file_upload"), CallBackFunction);
//Tested in Mozilla Firefox browser, Chrome
function ReadFileAllBrowsers(FileElement, CallBackFunction) {
try {
var file = FileElement.files[0];
var contents_ = "";
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function(evt) {
CallBackFunction(evt.target.result);
}
reader.onerror = function(evt) {
alert("Error reading file");
}
}
} catch (Exception) {
var fall_back = ieReadFile(FileElement.value);
if (fall_back != false) {
CallBackFunction(fall_back);
}
}
}
///Reading files with Internet Explorer
function ieReadFile(filename) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile(filename, 1);
var contents = fh.ReadAll();
fh.Close();
return contents;
} catch (Exception) {
alert(Exception);
return false;
}
}
The most commonly used way is using jQuery for this purpose:
var safestring = $('<div>').text(unsafestring).html();
If you want to to encode all the HTML entities you will have to use a library or write it yourself.
You can use a more compact library than jQuery, like HTML Encoder and Decode
You can use a variety of methods, one uses Javascript window.onload function in a simple function call from a script or from the body as in the solutions above, you can also use jQuery to do this but its just a modification of Javascript...Just add Jquery to your header by pasting
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
to your head section and open another script tag where you display the alert when the DOM is ready i.e. `
<script>
$("document").ready( function () {
alert("Hello, world");
});
</script>
`
This uses Jquery to run the function but since jQuery is a Javascript framework it contains Javascript code hence the Javascript alert function..hope this helps...
The issue I had is that sometimes I will need to get at a value that is deeply
nested. Normally you would need to do a type assertion at each level, so I went
ahead and just made a method that takes a map[string]interface{}
and a
string
key, and returns the resulting map[string]interface{}
.
The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:
package main
type Slice []interface{}
type Map map[string]interface{}
func (m Map) M(s string) Map {
return m[s].(map[string]interface{})
}
func (m Map) A(s string) Slice {
return m[s].([]interface{})
}
func (a Slice) M(n int) Map {
return a[n].(map[string]interface{})
}
and example code:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
o, e := os.Open("a.json")
if e != nil {
log.Fatal(e)
}
in_m := Map{}
json.NewDecoder(o).Decode(&in_m)
out_m := in_m.
M("contents").
M("sectionListRenderer").
A("contents").
M(0).
M("musicShelfRenderer").
A("contents").
M(0).
M("musicResponsiveListItemRenderer").
M("navigationEndpoint").
M("browseEndpoint")
fmt.Println(out_m)
}
Try this jQuery:
$(function() {
// Handler for .ready() called.
});
Yes there is retainAll
check out this
Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);
Using newInstance()
directly is deprecated as of Java 8. You need to use Class.getDeclaredConstructor(...).newInstance(...)
with the corresponding exceptions.
In IE 5.5+, you can use the contentWindow property:
iframe.height = iframe.contentWindow.document.scrollHeight;
In Netscape 6 (assuming firefox as well), contentDocument property:
iframe.height = iframe.contentDocument.scrollHeight
Add servlet-api.jar into your classpath. It will be available into Tomcat's lib folder.
public static int [] locations={1,2,3};
public static test dot=new test();
Declare the above variables above the main method and the code compiles fine.
public static void main(String[] args){
You can always cancel()
the Notification
from whatever is being invoked by the action (e.g., in onCreate()
of the activity tied to the PendingIntent
you supply to addAction()
).
This is what may be happening, if the value of item.photo
is undefined then item.photo != ''
will always show as true. And if you think logically it actually makes sense, item.photo
is not an empty string (so this condition comes true) since it is undefined
.
Now for people who are trying to check if the value of input is empty or not in Angular 6, can go by this approach.
Lets say this is the input field -
<input type="number" id="myTextBox" name="myTextBox"_x000D_
[(ngModel)]="response.myTextBox"_x000D_
#myTextBox="ngModel">
_x000D_
To check if the field is empty or not this should be the script.
<div *ngIf="!myTextBox.value" style="color:red;">_x000D_
Your field is empty_x000D_
</div>
_x000D_
Do note the subtle difference between the above answer and this answer. I have added an additional attribute .value
after my input name myTextBox
.
I don't know if the above answer worked for above version of Angular, but for Angular 6 this is how it should be done.
Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too:
so you have to create a companion objet to create new newInstance function
you can set the paremter of the function whatever you want. using
val args = Bundle()
you can set your args.
You can now use args.putSomthing
to add you args which u give as a prameter in your newInstance function.
putString(key:String,str:String)
to add string for example and so on
Now to get the argument you can use
arguments.getSomthing(Key:String)
=> like arguments.getString("1")
here is a full example
class IntervModifFragment : DialogFragment(), ModContract.View
{
companion object {
fun newInstance( plom:String,type:String,position: Int):IntervModifFragment {
val fragment =IntervModifFragment()
val args = Bundle()
args.putString( "1",plom)
args.putString("2",type)
args.putInt("3",position)
fragment.arguments = args
return fragment
}
}
...
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fillSpinerPlom(view,arguments.getString("1"))
fillSpinerType(view, arguments.getString("2"))
confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))})
val dateSetListener = object : DatePickerDialog.OnDateSetListener {
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int,
dayOfMonth: Int) {
val datep= DateT(year,monthOfYear,dayOfMonth)
updateDateInView(datep.date)
}
}
}
...
}
Now how to create your dialog you can do somthing like this in another class
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
like this for example
class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
holder.btn_update!!.setOnClickListener {
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
dialog.show(ft, ContentValues.TAG)
}
...
}
..
}
I had the same problem, I'm using a AfterViewChecked
and @ViewChild
combination (Angular2 beta.3).
The Component:
import {..., AfterViewChecked, ElementRef, ViewChild, OnInit} from 'angular2/core'
@Component({
...
})
export class ChannelComponent implements OnInit, AfterViewChecked {
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
ngOnInit() {
this.scrollToBottom();
}
ngAfterViewChecked() {
this.scrollToBottom();
}
scrollToBottom(): void {
try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch(err) { }
}
}
The Template:
<div #scrollMe style="overflow: scroll; height: xyz;">
<div class="..."
*ngFor="..."
...>
</div>
</div>
Of course this is pretty basic. The AfterViewChecked
triggers every time the view was checked:
Implement this interface to get notified after every check of your component's view.
If you have an input-field for sending messages for instance this event is fired after each keyup (just to give an example). But if you save whether the user scrolled manually and then skip the scrollToBottom()
you should be fine.
Use grep or grepl to find observations with white spaces and sub to get rid of them.
names<-c("Ganga Din\t", "Shyam Lal", "Bulbul ")
grep("[[:space:]]+$", names)
[1] 1 3
grepl("[[:space:]]+$", names)
[1] TRUE FALSE TRUE
sub("[[:space:]]+$", "", names)
[1] "Ganga Din" "Shyam Lal" "Bulbul"
That should work. Better if you pass a function to val
:
$('#replyBox').val(function(i, text) {
return text + quote;
});
This way you avoid searching the element and calling val
twice.
I write this function
def larger(x, than=0):
if not x or min(x) > than:
return True
return False
Then
print larger([5, 6, 7], than=5) # False
print larger([6, 7, 8], than=5) # True
print larger([], than=5) # True
print larger([6, 7, 8, None], than=5) # False
Empty list on min() will raise ValueError. So I added if not x
in condition.
A directive
allows you to extend the HTML vocabulary in a declarative fashion for building web components. The ng-app
attribute is a directive, so is ng-controller
and all of the ng- prefixed attributes
. Directives can be attributes
, tags
or even class
names
, comments
.
How directives are born (compilation
and instantiation
)
Compile: We’ll use the compile
function to both manipulate
the DOM before it’s rendered and return a link
function (that will handle the linking for us). This also is the place to put any methods that need to be shared around with all of the instances
of this directive.
link: We’ll use the link
function to register all listeners on a specific DOM element (that’s cloned from the template) and set up our bindings to the page.
If set in the compile()
function they would only have been set once (which is often what you want). If set in the link()
function they would be set every time the HTML element is bound to data in the
object.
<div ng-repeat="i in [0,1,2]">
<simple>
<div>Inner content</div>
</simple>
</div>
app.directive("simple", function(){
return {
restrict: "EA",
transclude:true,
template:"<div>{{label}}<div ng-transclude></div></div>",
compile: function(element, attributes){
return {
pre: function(scope, element, attributes, controller, transcludeFn){
},
post: function(scope, element, attributes, controller, transcludeFn){
}
}
},
controller: function($scope){
}
};
});
Compile
function returns the pre
and post
link function. In the pre link function we have the instance template and also the scope from the controller
, but yet the template is not bound to scope and still don't have transcluded content.
Post
link function is where post link is the last function to execute. Now the transclusion
is complete, the template is linked to a scope
, and the view will update with data bound values after the next digest cycle
. The link
option is just a shortcut to setting up a post-link
function.
controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.
You have to specify the name of the directive to be required – It should be bound to same element or its parent. The name can be prefixed with:
? – Will not raise any error if a mentioned directive does not exist.
^ – Will look for the directive on parent elements, if not available on the same element.
Use square bracket [‘directive1', ‘directive2', ‘directive3']
to require multiple directives controller.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $element) {
});
app.directive('parentDirective', function() {
return {
restrict: 'E',
template: '<child-directive></child-directive>',
controller: function($scope, $element){
this.variable = "Hi Vinothbabu"
}
}
});
app.directive('childDirective', function() {
return {
restrict: 'E',
template: '<h1>I am child</h1>',
replace: true,
require: '^parentDirective',
link: function($scope, $element, attr, parentDirectCtrl){
//you now have access to parentDirectCtrl.variable
}
}
});
A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.
The Runnable Interface requires of the class to implement the method run()
like so:
public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
And then use it like this:
Thread t = new Thread(new MyRunnableTask());
t.start();
If you did not have the Runnable
interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run()
method in your class, so you could get errors. That is why you need to implement the interface.
Note that you do not need to define a class as usual, you can do all of that inline:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}
});
t.start();
This is similar to the above, only you don't create another named class.
According to the latest doc you can do the following-
Add a day
moment().add(1, 'days').calendar();
Add Year
moment().add(1, 'years').calendar();
Add Month
moment().add(1, 'months').calendar();
Just to add to this in 2019 w Angular 8,
instead of keypress I had to use keydown
@HostListener('document:keypress', ['$event'])
to
@HostListener('document:keydown', ['$event'])
Working Stacklitz
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
Try this:
private SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());
To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server. eg:
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
.setUri(someURL)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
client.execute(request);
Default header is SET ON HTTPCLIENT to send on every request to the server.
For iterations using a selector doesn't seem to make any sense though:
var some = $( '...' );
for( i = some.length -1; i>=0; --i )
{
// Have to transform in a jquery object again:
//
var item = $( some[ i ] );
// use item at will
// ...
}
var xxxx : { [key:number]: MyType };
Having effects on append won't work because the content the browser displays is updated as soon as the div is appended. So, to combine Mark B's and Steerpike's answers:
Style the div you're appending as hidden before you actually append it. You can do it with inline or external CSS script, or just create the div as
<div id="new_div" style="display: none;"> ... </div>
Then you can chain effects to your append (demo):
$('#new_div').appendTo('#original_div').show('slow');
Or (demo):
var $new = $('#new_div');
$('#original_div').append($new);
$new.show('slow');
I think you have not installed these features. see below in picture.
I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.
Install Process:
Use
Intent myIntent = new Intent(v.getContext(), MyClass.class);
or
Intent myIntent = new Intent(MyFragment.this.getActivity(), MyClass.class);
to start a new Activity. This is because you will need to pass Application or component context as a first parameter to the Intent Constructor when you are creating an Intent for a specific component of your application.
if $("form")[0].checkValidity()
$.ajax(
url: "url"
type: "post"
data: {
}
dataType: "json"
success: (data) ->
)
else
#important
$("form")[0].reportValidity()
from: html5 form validation
The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.
I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float:
territory):
<br />s
to split the options apart and some CSS to vertically align them:<style type='text/css'>
.input input
{
width: 20px;
}
</style>
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<br />
<input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div>
Styling the <label>
is why you'll need to resort to Javascript. A library like jQuery
is perfect for this:
<style type='text/css'>
.input label.focused
{
background-color: #EEEEEE;
font-style: italic;
}
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('.input :radio').focus(updateSelectedStyle);
$('.input :radio').blur(updateSelectedStyle);
$('.input :radio').change(updateSelectedStyle);
})
function updateSelectedStyle() {
$('.input :radio').removeClass('focused').next().removeClass('focused');
$('.input :radio:checked').addClass('focused').next().addClass('focused');
}
</script>
The focus
and blur
hooks are needed to make this work in IE.
Sorry to beat a dead horse, but it is kind-of weird that no-one pointed this out - "Yes you can, but this is the opposite of how you use capturing groups in real life".
If you use Regex the way it is meant to be used, the solution is as simple as this:
"6 example input 4".replaceAll("(?:\\d)(.*)(?:\\d)", "number$11");
Or as rightfully pointed out by shmosel below,
"6 example input 4".replaceAll("\d(.*)\d", "number$11");
...since in your regex there is no good reason to group the decimals at all.
You don't usually use capturing groups on the parts of the string you want to discard, you use them on the part of the string you want to keep.
If you really want groups that you want to replace, what you probably want instead is a templating engine (e.g. moustache, ejs, StringTemplate, ...).
As an aside for the curious, even non-capturing groups in regexes are just there for the case that the regex engine needs them to recognize and skip variable text. For example, in
(?:abc)*(capture me)(?:bcd)*
you need them if your input can look either like "abcabccapture mebcdbcd" or "abccapture mebcd" or even just "capture me".
Or to put it the other way around: if the text is always the same, and you don't capture it, there is no reason to use groups at all.
A valid entry looks like:
public static class ConsoleProgram
{
[STAThread]
static void Main()
{
Console.WriteLine("Got here");
Console.ReadLine();
}
}
I had issues as I'm writing a web application, but for the dreadly loading time, I wanted to quickly convert the same project to a console application and perform quick method tests without loading the entire solution.
My entry point was placed in /App_Code/Main.cs, and I had to do the following:
After this, I can set the output (as mentioned in Step 1) to Class Library to start the web site, or Console Application to enter the console mode.
Why I did this instead of 2 separate projects?
Simply because I had references to Entity Framework and other specific references that created problems running 2 separate projects.
For easier solutions, I would still recommend 2 separate projects as the console output is mainly test code and you probably don't want to risk that going out in production code.
You can also evaluate your output as a sub-process, by surrounding everything with back ticks or with putting it inside $():
`ps aux | grep -ie amarok | awk '{print "kill -9 " $2}'`
$(ps aux | grep -ie amarok | awk '{print "kill -9 " $2}')
You have to change the values in the CATALINA_OPTS option defined in the Tomcat Catalina start file. To increase the PermGen
memory change the value of the MaxPermSize
variable, otherwise change the value of the Xmx
variable.
Linux & Mac OS: Open or create setenv.sh
file placed in the "bin" directory. You have to apply the changes to this line:
export CATALINA_OPTS="$CATALINA_OPTS -server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m"
Windows:
Open or create the setenv.bat
file placed in the "bin" directory:
set CATALINA_OPTS=-server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m
Example:
use: android:textStyle="bold"
<TextView
android:id="@+id/txtVelocidade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/txtlatitude"
android:layout_centerHorizontal="true"
android:layout_marginBottom="34dp"
android:textStyle="bold"
android:text="Aguardando GPS"
android:textAppearance="?android:attr/textAppearanceLarge" />
Some options:
Using a constant:
class Card
COLOURS = ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
end
Lazy loaded using class instance variable:
class Card
def self.colours
@colours ||= ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
end
end
If it is a truly global constant (avoid global constants of this nature, though), you could also consider putting
a top-level constant in config/initializers/my_constants.rb
for example.
Pandas: How to replace NaN (nan
) values with the average (mean), median or other statistics of one column
Say your DataFrame is df
and you have one column called nr_items
. This is: df['nr_items']
If you want to replace the NaN
values of your column df['nr_items']
with the mean of the column:
Use method .fillna()
:
mean_value=df['nr_items'].mean()
df['nr_item_ave']=df['nr_items'].fillna(mean_value)
I have created a new df
column called nr_item_ave
to store the new column with the NaN
values replaced by the mean
value of the column.
You should be careful when using the mean
. If you have outliers is more recommendable to use the median
for me, I do double click of ListView in this code section .
this.listView.Activation = ItemActivation.TwoClick;
this.listView.ItemActivate += ListView1_ItemActivate;
ItemActivate specify how user activate with items
When user do double click, ListView1_ItemActivate will be trigger. Property of ListView ItemActivate refers to access the collection of items selected.
private void ListView1_ItemActivate(Object sender, EventArgs e)
{
foreach (ListViewItem item in listView.SelectedItems)
//do something
}
it works for me.
\
is used as for escape sequence in many programming languages, including Java.
If you want to
\n
or \r
, \t
\
or "
which are special in string literal you have to escape it with another \
which gives us \\
and \"
That is the output of Object's "toString()" implementation. If your class overrides toString(), it will print something entirely different.
Let's break down the full URL that a client would type into their address bar to reach your servlet:
http://www.example.com:80/awesome-application/path/to/servlet/path/info?a=1&b=2#boo
The parts are:
http
www.example.com
80
awesome-application
path/to/servlet
path/info
a=1&b=2
boo
The request URI (returned by getRequestURI) corresponds to parts 4, 5 and 6.
(incidentally, even though you're not asking for this, the method getRequestURL would give you parts 1, 2, 3, 4, 5 and 6).
Now:
The following always holds (except for URL encoding differences):
requestURI = contextPath + servletPath + pathInfo
The following example from the Servlet 3.0 specification is very helpful:
Note: image follows, I don't have the time to recreate in HTML:
Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99
.
I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html
Specifically:
Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.
Apple annoyingly rejects many HTML5 web standards on their iOS devices, for a variety of business reasons. Ultimately, you can't pre-load or auto-play sound files before a touch event, it only plays one sound at a time, and it doesn't support Ogg/Vorbis. However, I did find one nifty workaround to let you have a little more control over the audio.
<audio id="soundHandle" style="display:none;"></audio>
<script type="text/javascript">
var soundHandle = document.getElementById('soundHandle');
$(document).ready(function() {
addEventListener('touchstart', function (e) {
soundHandle.src = 'audio.mp3';
soundHandle.loop = true;
soundHandle.play();
soundHandle.pause();
});
});
</script>
Basically, you start playing the audio file on the very first touch event, then you pause it immediately. Now, you can use the soundHandle.play() and soundHandle.pause() commands throughout your Javascript and control the audio without touch events. If you can time it perfectly, just have the pause come in right after the sound is over. Then next time you play it again, it will loop back to the beginning. This won't resolve all the mess Apple has made here, but it's one solution.
Firstly you can use this steps
For Laravel 5:
1. Rename server.php in your Laravel root folder to index.php
2. Copy the .htaccess file from /public directory to your Laravel root folder.
source: https://stackoverflow.com/a/28735930
after you follow these steps then you need to change all css and script path, but this will be tiring.
Solution Proposal :simply you can make minor change the helpers::asset
function.
For this:
open vendor\laravel\framework\src\Illuminate\Foundation\helpers.php
goto line 130
write "public/".$path
instead of $path
,
function asset($path, $secure = null){
return app('url')->asset("public/".$path, $secure);
}
You could put a crontab file in /etc/cron.d
which would run a script that would run your command and then delete the crontab file in /etc/cron.d
. Of course, that means your script would need to run as root.
Using dialog methods:
$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');
Or directly, hacky though:
$("span.ui-dialog-title").text('My New Title');
For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com
Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.
You can use this class : class="sticky-top alert alert-dismissible"
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
This is asking for your MySQL username and password.
You should enter these details, which will default to "root" and "" (i.e.: nothing) if you've not specified a password.
Another solution would be to use the ManagedTask and ManagedTaskListener.
You need a Callable or Runnable which implements the interface ManagedTask.
The method getManagedTaskListener
returns the instance you want.
public ManagedTaskListener getManagedTaskListener() {
And you implement in ManagedTaskListener the taskDone
method:
@Override
public void taskDone(Future<?> future, ManagedExecutorService executor, Object task, Throwable exception) {
if (exception != null) {
LOGGER.log(Level.SEVERE, exception.getMessage());
}
}
More details about managed task lifecycle and listener.
I had this exact same problem with Xampp portable on Windows 10 Home. I went through all the suggestions and none worked. I did get it working with Windows Firewall Settings and an error on my part.
My pen drive was labelled Drive E on my laptop and Drive F on my Desktop. Once I corrected that using disk partition and changed the drive letter to E for my desktop to windows asked for access for the firewall and everything clicked.
The steps to correct the drive letter were: 1. Hit the windows key and type Partition, "create and format harddisks partitions" should be at the top, hit enter 2. Find the drive you are looking for at the top panel and click on it. 3. Right click on it and select change drive letter and path, click okay 4. Now try to start xampp control panel and start Apache and Mysql 5. if you get the windows firewall click allow.
I can't say this will work but it did for me and is what I added to this discussion. I also think it might have been just the firewall did not allow the oither drive letter.
Should also be able to do this:
total += eval(myInt1) + eval(myInt2) + eval(myInt3);
This helped me in a different, but similar, situation.
How about:
private List<String> Parse(String str) {
List<String> output = new ArrayList<String>();
Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
while (match.find()) {
output.add(match.group());
}
return output;
}
a = [1, 2, 2, 3, 1]
to_remove = 1
a = [i for i in a if i != to_remove]
print(a)
Perhaps not the most pythonic but still the easiest for me haha
You can use this
Javascript
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)&&(charCode!=46)) {
return false;
}
return true;
}
Usage
<input onkeypress="return isNumber(event)" class="form-control">
The latest build of the sublime even allows the direct command instead of double quotes. Try the below code for the build system
{
"cmd" : ["gcc $file_name -o ${file_base_name} && ./${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path",
}
To switch between tabs action class does not always works on all browser and on all webdriver. the best way is to use robot class. try this code.
String website = "https://www.google.com";
String website1 = "https://www.msn.com/en-in/";
String controlpath = "C:\\Libraries\\msedgedriver.exe";
System.setProperty("webdriver.edge.driver", controlpath);
driver = new EdgeDriver();
driver.manage().window().maximize(); // Maximize browser
driver.get(website);
System.out.println("Google page");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
//Switch focus to new tab
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
//System.out.println("Handle info"+ driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
//Launch URL in the new tab
driver.get(website1);
System.out.println("msn page");
Thread.sleep(5000);
driver.switchTo().window(tabs.get(0));
Thread.sleep(5000);
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Not Intersect(Target, Range("C6:ZZ6")) Is Nothing Then
If InStr(UCase(Target.Value), "TOTAL") > 0 Then
Target.Offset(1, 0) = "-"
End If
End If
End Sub
This will allow you to add columns dynamically and automatically insert a dash underneath any columns in the C row after 6 containing case insensitive "Total". Note: If you go past ZZ6, you will need to change the code, but this should get you where you need to go.
This is an old questions with old answers. I wanted to add a new look at this problem and to answer why is this happens and not why is this useful.
So you have two functions:
var f1 = function () {
setTimeout(function(){
console.log("f1", "First function call...");
}, 0);
};
var f2 = function () {
console.log("f2", "Second call...");
};
and then call them in the following order f1(); f2();
just to see that the second one executed first.
And here is why: it is not possible to have setTimeout
with a time delay of 0 milliseconds. The Minimum value is determined by the browser and it is not 0 milliseconds. Historically browsers sets this minimum to 10 milliseconds, but the HTML5 specs and modern browsers have it set at 4 milliseconds.
If nesting level is greater than 5, and timeout is less than 4, then increase timeout to 4.
Also from mozilla:
To implement a 0 ms timeout in a modern browser, you can use window.postMessage() as described here.
P.S. information is taken after reading the following article.
Here's an updated answer for Angular 4 & 5. TransformRequest and angular.identity were dropped. I've also included the ability to combine files with JSON data in one request.
Angular 5 Solution:
import {HttpClient} from '@angular/common/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = {} as any; // Set any options you like
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.httpClient.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
Angular 4 Solution:
// Note that these imports below are deprecated in Angular 5
import {Http, RequestOptions} from '@angular/http';
uploadFileToUrl(files, restObj, uploadUrl): Promise<any> {
// Note that setting a content-type header
// for mutlipart forms breaks some built in
// request parsers like multer in express.
const options = new RequestOptions();
const formData = new FormData();
// Append files to the virtual form.
for (const file of files) {
formData.append(file.name, file)
}
// Optional, append other kev:val rest data to the form.
Object.keys(restObj).forEach(key => {
formData.append(key, restObj[key]);
});
// Send it.
return this.http.post(uploadUrl, formData, options)
.toPromise()
.catch((e) => {
// handle me
});
}
new StringBuilder().append(str.charAt(0))
.append(str.charAt(10))
.append(str.charAt(20))
.append(str.charAt(30))
.toString();
This way you can get the new string with whatever characters you want.
I've had the same issue when re-attaching database after detaching it and moving ldf and mdf files from drive C to F.
In order to fix it I had to add OWNER RIGHTS principal to both files and gave it full control over them in the Security tab of the Properties dialog.
1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>
Follow the following steps:
This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671
This solution requires both an UPDATE
and INSERT
.
UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
SELECT 3, 'C', 'Z'
WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507
create alert, tested in xcode 9
let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: self.finishAlert))
self.present(alert, animated: true, completion: nil)
and the function
func finishAlert(alert: UIAlertAction!)
{
}
You could use sed -n 5p file
.
You can also get a range, e.g., sed -n 5,10p file
.
string Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum , Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease;
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = string.Empty;
Here's my code that works:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace SnagFree.TrayApp.Core
{
class GlobalKeyboardHookEventArgs : HandledEventArgs
{
public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }
public GlobalKeyboardHookEventArgs(
GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
GlobalKeyboardHook.KeyboardState keyboardState)
{
KeyboardData = keyboardData;
KeyboardState = keyboardState;
}
}
//Based on https://gist.github.com/Stasonix
class GlobalKeyboardHook : IDisposable
{
public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;
public GlobalKeyboardHook()
{
_windowsHookHandle = IntPtr.Zero;
_user32LibraryHandle = IntPtr.Zero;
_hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.
_user32LibraryHandle = LoadLibrary("User32");
if (_user32LibraryHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
if (_windowsHookHandle == IntPtr.Zero)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// because we can unhook only in the same thread, not in garbage collector thread
if (_windowsHookHandle != IntPtr.Zero)
{
if (!UnhookWindowsHookEx(_windowsHookHandle))
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_windowsHookHandle = IntPtr.Zero;
// ReSharper disable once DelegateSubtraction
_hookProc -= LowLevelKeyboardProc;
}
}
if (_user32LibraryHandle != IntPtr.Zero)
{
if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
}
_user32LibraryHandle = IntPtr.Zero;
}
}
~GlobalKeyboardHook()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private IntPtr _windowsHookHandle;
private IntPtr _user32LibraryHandle;
private HookProc _hookProc;
delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool FreeLibrary(IntPtr hModule);
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events are
/// associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">hook type</param>
/// <param name="lpfn">hook procedure</param>
/// <param name="hMod">handle to application instance</param>
/// <param name="dwThreadId">thread identifier</param>
/// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="hhk">handle to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="hHook">handle to current hook</param>
/// <param name="code">hook code passed to hook procedure</param>
/// <param name="wParam">value passed to hook procedure</param>
/// <param name="lParam">value passed to hook procedure</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("USER32", SetLastError = true)]
static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
public struct LowLevelKeyboardInputEvent
{
/// <summary>
/// A virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int VirtualCode;
/// <summary>
/// A hardware scan code for the key.
/// </summary>
public int HardwareScanCode;
/// <summary>
/// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
/// </summary>
public int Flags;
/// <summary>
/// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
/// </summary>
public int TimeStamp;
/// <summary>
/// Additional information associated with the message.
/// </summary>
public IntPtr AdditionalInformation;
}
public const int WH_KEYBOARD_LL = 13;
//const int HC_ACTION = 0;
public enum KeyboardState
{
KeyDown = 0x0100,
KeyUp = 0x0101,
SysKeyDown = 0x0104,
SysKeyUp = 0x0105
}
public const int VkSnapshot = 0x2c;
//const int VkLwin = 0x5b;
//const int VkRwin = 0x5c;
//const int VkTab = 0x09;
//const int VkEscape = 0x18;
//const int VkControl = 0x11;
const int KfAltdown = 0x2000;
public const int LlkhfAltdown = (KfAltdown >> 8);
public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
{
bool fEatKeyStroke = false;
var wparamTyped = wParam.ToInt32();
if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
{
object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;
var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);
EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
handler?.Invoke(this, eventArguments);
fEatKeyStroke = eventArguments.Handled;
}
return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
}
}
Usage:
using System;
using System.Windows.Forms;
namespace SnagFree.TrayApp.Core
{
internal class Controller : IDisposable
{
private GlobalKeyboardHook _globalKeyboardHook;
public void SetupKeyboardHooks()
{
_globalKeyboardHook = new GlobalKeyboardHook();
_globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}
private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
{
//Debug.WriteLine(e.KeyboardData.VirtualCode);
if (e.KeyboardData.VirtualCode != GlobalKeyboardHook.VkSnapshot)
return;
// seems, not needed in the life.
//if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.SysKeyDown &&
// e.KeyboardData.Flags == GlobalKeyboardHook.LlkhfAltdown)
//{
// MessageBox.Show("Alt + Print Screen");
// e.Handled = true;
//}
//else
if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
{
MessageBox.Show("Print Screen");
e.Handled = true;
}
}
public void Dispose()
{
_globalKeyboardHook?.Dispose();
}
}
}
Following two steps worked perfectly fine for me:
Comment out the bind address from the file /etc/mysql/my.cnf
:
#bind-address = 127.0.0.1
Run following query in phpMyAdmin:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'; FLUSH PRIVILEGES;
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
I made the upgrade to OSX Mavericks and Pycharm 3 and start to get this error, i used pip and easy install and got the error:
command'/usr/bin/clang' failed with exit status 1.
So i need to update to Xcode 5 and tried again to install using pip.
pip install mysql-python
That fix all the problems.
You can also do like this
select *
from table
where columnName like '%' + case when @varColumn is null then '' else @varColumn end + ' %'
and if you want to check div has a perticular children(say <p>
use:
if ($('#myfav').children('p').length > 0) {
// do something
}
If the file that you want to open is in the same folder as your batch(.bat) file then you can simply try:
start filename.filetype
example: start image.png
Use typings to access node functions from TypeScript:
typings install env~node --global
If you don't have typings install it:
npm install typings --global
I will explain bind theoretically as well as practically
bind in javascript is a method -- Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the 'this' refers to the first parameter passed to the bind method. Its syntax is
var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
Example:--
var checkRange = function(value){
if(typeof value !== "number"){
return false;
}
else {
return value >= this.minimum && value <= this.maximum;
}
}
var range = {minimum:10,maximum:20};
var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
var result = boundedFunc(15); //passing value
console.log(result) // will give true;
For me only excluding the following classes worked:
import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}) {
// ...
}
A better solution for your problem might be the Charts library. It enables you to use the excellent Highcharts javascript library to make beautiful and interactive plots. Highcharts uses the HTML svg
tag so all your charts are actually vector images.
Some features:
Disclaimer: I'm the developer of the library
I think , your app installed by other account.( multiple account mode feature ) You can uninstall app in Setting>Apps>"app name"> Uninstall
# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0
d = b**2-4*a*c # discriminant
if d < 0:
print 'No solutions'
elif d == 0:
x1 = -b / (2*a)
print 'The sole solution is',x1
else: # if d > 0
x1 = (-b + math.sqrt(d)) / (2*a)
x2 = (-b - math.sqrt(d)) / (2*a)
print 'Solutions are',x1,'and',x2
You are iterating trough items in words but you have to iterate through item's length:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in range(len(words)):
w1 = words[i]
if w1[0] == w1[len(w1) - 1]:
c += 1
print (c)
In your case i[0] is 'aba' because i is calculated from items in words:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
c = 0
for i in words:
print(i)
the output is:
aba
There is a few benefits of using modules. You can use it only with Apple's framework unless module map is created. @import
is a bit similar to pre-compiling headers files when added to .pch
file which is a way to tune app the compilation process. Additionally you do not have to add libraries in the old way, using @import
is much faster and efficient in fact. If you still look for a nice reference I will highly recommend you reading this article.
You can use curl
or wget
to retrieve the raw data, or you can use w3m -dump
to have a nice text representation of a web page.
$ foo=$(w3m -dump http://www.example.com/); echo $foo
You have reached this web page by typing "example.com", "example.net","example.org" or "example.edu" into your web browser. These domain names are reserved for use in documentation and are not available for registration. See RFC 2606, Section 3.
I don't know why chrome team don't allow this silly feature ... but the only way I could change variable values with success is to modify the script directly in the chrome editor under "Sources" Tab (this changes the behavior of your script until you refresh the page), but that changes will lost when refresh, so be carefull.
You try with the :before
was pretty close, the only thing you had to change was actually using skew instead of the borders: http://jsfiddle.net/Hfkk7/1101/
Edit: Your border approach would work too, the only thing you did wrong was having the before element on top of your div, so the transparent border wasnt showing. If you would have position the pseudo element to the left of your div, everything would have worked too: http://jsfiddle.net/Hfkk7/1102/
Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431
So if you want to validate if your date string (let's call it datestr
) is in the correct format, it is best to parse it with date
and ask date
to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.
if [[ "$datestr" == $(date -d "$datestr" "+%Y%m%d" 2>/dev/null) ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email', :checked => true %>
<%= label :contactmethod_email, 'Email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= label :contactmethod_sms, 'SMS' %>
<% end %>
Have a look at the link below, which suggests it is possible to alter the contents of an iFrame within your page with Javascript, although you are most likely to run into a few cross browser issues. If you can do this you can use the javascript in your page to add hidden dom elements to the iFrame containing your values, which the iFrame can read. Accessing the document inside an iFrame
Have you tried passing the Update panel's client id to the __doPostBack function? My team has done this to refresh an update panel and as far as I know it worked.
__doPostBack(UpdatePanelClientID, '**Some String**');
I´m in Brazil. Because of the regional details sometimes the city cames in differents ways. I think its the same in India and other countries. So, to prevent errors I make this verification:
private fun getAddress(latLng: LatLng): String {
// 1
val geocoder = Geocoder(this)
val addresses: List<Address>?
var city = "no"
try {
addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
if (null != addresses && !addresses.isEmpty()) { //prevent from error
//sometimes the city comes in locality, sometimes in subAdminArea.
if (addresses[0].locality == null) {
city = addresses[0].subAdminArea
} else {
city = addresses[0].locality
}
}
} catch (e: IOException) {
Log.e("MapsActivity", e.localizedMessage)
}
return city
}
You can also check if city returns "no". If so, wasn´t possible to get the user location. Hope it helps.
In case of image stacks, I find it easier to use scikit-image
to read, and matplotlib
to show or save. I have handled 16-bit TIFF image stacks with the following code.
from skimage import io
import matplotlib.pyplot as plt
# read the image stack
img = io.imread('a_image.tif')
# show the image
plt.imshow(mol,cmap='gray')
plt.axis('off')
# save the image
plt.savefig('output.tif', transparent=True, dpi=300, bbox_inches="tight", pad_inches=0.0)
As far as I know a Panel can have a transparent color only, you can not control the opacity of the panel. So, you can have some parts of a panel completely transparent but not a 50% to say something.
To use transparency you must define the transparent color property.
public class FindDigitFromString
{
public static void main(String[] args)
{
String s=" Hi How Are You 11 ";
String s1=s.replaceAll("[^0-9]+", "");
//*replacing all the value of string except digit by using "[^0-9]+" regex.*
System.out.println(s1);
}
}
Output: 11
There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.
UPDATE Feb. 2021
As in Activity v1.2.0 and Fragment v1.3.0, the new Activity Result APIs
have been introduced.
The Activity Result APIs provide components for registering for a result, launching the result, and handling the result once it is dispatched by the system.
So there is no need of using startActivityForResult
and onActivityResult
anymore.
In order to use the new API, you need to create an ActivityResultLauncher in your origin Activity, specifying the callback that will be run when the destination Activity finishes and returns the desired data:
private val intentLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
result.data?.getStringExtra("streetkey")
result.data?.getStringExtra("citykey")
result.data?.getStringExtra("homekey")
}
}
and then, launching your intent whenever you need to:
intentLauncher.launch(Intent(this, YourActivity::class.java))
And to return data from the destination Activity, you just have to add an intent with the values to return to the setResult()
method:
val data = Intent()
data.putExtra("streetkey", "streetname")
data.putExtra("citykey", "cityname")
data.putExtra("homekey", "homename")
setResult(Activity.RESULT_OK, data)
finish()
For any additional information, please refer to Android Documentation
If you have installed openssl
, you can use:
echo -n "foobar" | openssl dgst -sha256
For other algorithms you can replace -sha256
with -md4
, -md5
, -ripemd160
, -sha
, -sha1
, -sha224
, -sha384
, -sha512
or -whirlpool
.
To increase the heap size you can use the -Xmx argument when starting Java; e.g.
-Xmx256M
emacs hello.c -nw
This is to open a hello.c file using Emacs inside the terminal.
Okay, just to clarify things that have already been posted.
You should have the directory com
, containing the directory company
, containing the directory example
, containing the file MyClass.java
.
From the folder containing com
, run:
$ javac com\company\example\MyClass.java
Then:
$ java com.company.example.MyClass Hello from MyClass!
These must both be done from the root of the source tree. Otherwise, javac
and java
won't be able to find any other packages (in fact, java
wouldn't even be able to run MyClass
).
I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:
package testpackage;
import testpackage2.MyClass;
public class TestPackageClass {
public static void main(String[] args) {
System.out.println("Hello from testpackage.TestPackageClass!");
System.out.println("Now accessing " + MyClass.NAME);
}
}
Inside testpackage2, I created MyClass.java containing the following code:
package testpackage2;
public class MyClass {
public static String NAME = "testpackage2.MyClass";
}
From the directory containing the two new folders, I ran:
C:\examples>javac testpackage\*.java C:\examples>javac testpackage2\*.java
Then:
C:\examples>java testpackage.TestPackageClass Hello from testpackage.TestPackageClass! Now accessing testpackage2.MyClass
Does that make things any clearer?
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
ORDER BY COUNT(*) DESC
I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.
Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = "été"' will not match while 'charField(ete) = "été"' might (again not sure about Oracle).
You can also do this easily in Pandas, if your data is represented in a Dataframe, as described here:
http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#scatter-plot
If you know you are going to return two objects, you can also use a generic pair:
public class Pair<A,B> {
public final A a;
public final B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
};
Edit A more fully formed implementation of the above:
package util;
public class Pair<A,B> {
public static <P, Q> Pair<P, Q> makePair(P p, Q q) {
return new Pair<P, Q>(p, q);
}
public final A a;
public final B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + ((b == null) ? 0 : b.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("rawtypes")
Pair other = (Pair) obj;
if (a == null) {
if (other.a != null) {
return false;
}
} else if (!a.equals(other.a)) {
return false;
}
if (b == null) {
if (other.b != null) {
return false;
}
} else if (!b.equals(other.b)) {
return false;
}
return true;
}
public boolean isInstance(Class<?> classA, Class<?> classB) {
return classA.isInstance(a) && classB.isInstance(b);
}
@SuppressWarnings("unchecked")
public static <P, Q> Pair<P, Q> cast(Pair<?, ?> pair, Class<P> pClass, Class<Q> qClass) {
if (pair.isInstance(pClass, qClass)) {
return (Pair<P, Q>) pair;
}
throw new ClassCastException();
}
}
Notes, mainly around rustiness with Java & generics:
a
and b
are immutable. makePair
static method helps you with boiler plate typing, which the diamond operator in Java 7 will make less annoying. There's some work to make this really nice re: generics, but it should be ok-ish now. (c.f. PECS)hashcode
and equals
are generated by eclipse.cast
method is ok, but doesn't seem quite right.isInstance
are necessary.Since you don't explicitly invoke a parent constructor as part of your child class constructor, there is an implicit call to a parameterless parent constructor inserted. That constructor does not exist, and so you get that error.
To correct the situation, you need to add an explicit call:
public Child(int i) : base(i)
{
Console.WriteLine("child");
}
Or, you can just add a parameterless parent constructor:
protected Parent() { }
if ( ! $("input").is(':checked') )
Doesn't work?
You might also try iterating over the elements like so:
var iz_checked = true;
$('input').each(function(){
iz_checked = iz_checked && $(this).is(':checked');
});
if ( ! iz_checked )
Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).
So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
produces a format that can parse both "2013-03-11T01:38:18.309Z"
and "2013-03-11T01:38:18.309+0000"
and will give you the same result.
Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.
I actually have more trouble on the JavaScript side to deal with both formats.
I ran into this same problem these days and maybe some more detail might be helpful to somebody else.
I was looking some security guidelines for REST APIs and crossed a very intriguing issue with json arrays. Check the link for details, but basically, you should wrap them within an Object as we already saw in this post question.
So, instead of:
[
{
"name": "order1"
},
{
"name": "order2"
}
]
It's advisable that we always do:
{
"data": [
{
"name": "order1"
},
{
"name": "order2"
}
]
}
This is pretty straight-forward when you doing a GET, but might give you some trouble if, instead, your trying to POST/PUT the very same json.
In my case, I had more than one GET that was a List and more than one POST/PUT that would receive the very same json.
So what I end up doing was to use a very simple Wrapper object for a List:
public class Wrapper<T> {
private List<T> data;
public Wrapper() {}
public Wrapper(List<T> data) {
this.data = data;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
}
Serialization of my lists were made with a @ControllerAdvice:
@ControllerAdvice
public class JSONResponseWrapper implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
@SuppressWarnings("unchecked")
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (body instanceof List) {
return new Wrapper<>((List<Object>) body);
}
else if (body instanceof Map) {
return Collections.singletonMap("data", body);
}
return body;
}
}
So, all the Lists and Maps where wrapped over a data object as below:
{
"data": [
{...}
]
}
Deserialization was still default, just using de Wrapper Object:
@PostMapping("/resource")
public ResponseEntity<Void> setResources(@RequestBody Wrapper<ResourceDTO> wrappedResources) {
List<ResourceDTO> resources = wrappedResources.getData();
// your code here
return ResponseEntity
.ok()
.build();
}
That was it! Hope it helps someone.
Note: tested with SpringBoot 1.5.5.RELEASE.
Comment.find(:all, :conditions =>["date(created_at) BETWEEN ? AND ? ", '2011-11-01','2011-11-15'])
In my case (using IntelliJ) File
- Invalidate Caches / Restart...
did the trick.
This is an old question, but I found the code useful and saved me three minutes of thinking :) So I am adding a small expansion to @opsb's answer.
If you wanted to convert this arc into a slice (to allow for fill) we can modify the code slightly:
function describeArc(x, y, radius, spread, startAngle, endAngle){_x000D_
var innerStart = polarToCartesian(x, y, radius, endAngle);_x000D_
var innerEnd = polarToCartesian(x, y, radius, startAngle);_x000D_
var outerStart = polarToCartesian(x, y, radius + spread, endAngle);_x000D_
var outerEnd = polarToCartesian(x, y, radius + spread, startAngle);_x000D_
_x000D_
var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";_x000D_
_x000D_
var d = [_x000D_
"M", outerStart.x, outerStart.y,_x000D_
"A", radius + spread, radius + spread, 0, largeArcFlag, 0, outerEnd.x, outerEnd.y,_x000D_
"L", innerEnd.x, innerEnd.y, _x000D_
"A", radius, radius, 0, largeArcFlag, 1, innerStart.x, innerStart.y, _x000D_
"L", outerStart.x, outerStart.y, "Z"_x000D_
].join(" ");_x000D_
_x000D_
return d;_x000D_
}_x000D_
_x000D_
function polarToCartesian(centerX, centerY, radius, angleInDegrees) {_x000D_
var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;_x000D_
_x000D_
return {_x000D_
x: centerX + (radius * Math.cos(angleInRadians)),_x000D_
y: centerY + (radius * Math.sin(angleInRadians))_x000D_
};_x000D_
}_x000D_
_x000D_
var path = describeArc(150, 150, 50, 30, 0, 50)_x000D_
document.getElementById("p").innerHTML = path_x000D_
document.getElementById("path").setAttribute('d',path)
_x000D_
<p id="p">_x000D_
</p>_x000D_
<svg width="300" height="300" style="border:1px gray solid">_x000D_
<path id="path" fill="blue" stroke="cyan"></path>_x000D_
</svg>
_x000D_
and there you go!
With GNU sed's -z
option you could process the whole file as if it was only one line. That way a s/…/…/
would only replace the first match in the whole file. Remember: s/…/…/
only replaces the first match in each line, but with the -z
option sed
treats the whole file as a single line.
sed -z 's/#include/#include "newfile.h"\n#include'
In the general case you have to rewrite your sed expression since the pattern space now holds the whole file instead of just one line. Some examples:
s/text.*//
can be rewritten as s/text[^\n]*//
. [^\n]
matches everything except the newline character. [^\n]*
will match all symbols after text
until a newline is reached.s/^text//
can be rewritten as s/(^|\n)text//
.s/text$//
can be rewritten as s/text(\n|$)//
.Note that if there are ties in top 10 values, you will only get the top 10 rows, not the top 10 values with the answers provided.
Ex: if the top 5 values are 10, 11, 12, 13, 14, 15 but your data contains
10, 10, 11, 12, 13, 14, 15 you will only get 10, 10, 11, 12, 13, 14 as your top 5 with a LIMIT
Here is a solution which will return more than 10 rows if there are ties but you will get all the rows where some_value_column
is technically in the top 10.
select
*
from
(select
*,
rank() over (order by some_value_column desc) as my_rank
from mytable) subquery
where my_rank <= 10
For linux ubuntu 18.04:
Go to terminal and command:$ sudo systemctl status tomcat
From the documentation:
In order to execute a command and have it not hang your PHP script while
it runs, the program you run must not output back to PHP. To do this,
redirect both stdout and stderr to /dev/null, then background it.
> /dev/null 2>&1 &
In order to execute a command and have
it spawned off as another process that
is not dependent on the Apache thread
to keep running (will not die if
somebody cancels the page) run this:
exec('bash -c "exec nohup setsid your_command > /dev/null 2>&1 &"');
What you seem to be thinking is that most of the processing is handled in the node event loop. Node actually farms off the I/O work to threads. I/O operations typically take orders of magnitude longer than CPU operations so why have the CPU wait for that? Besides, the OS can handle I/O tasks very well already. In fact, because Node does not wait around it achieves much higher CPU utilisation.
By way of analogy, think of NodeJS as a waiter taking the customer orders while the I/O chefs prepare them in the kitchen. Other systems have multiple chefs, who take a customers order, prepare the meal, clear the table and only then attend to the next customer.
check it useing loop for each index in comboxlist.Items[i]
bool CheckedOrUnchecked= comboxlist.CheckedItems.Contains(comboxlist.Items[0]);
I think it solve your purpose
With the latest version of phpmyadmin 5.0.2+ at least
Check that the actual installation was completed correctly,
Mine had been copied over into a sub folder on a linux machine rather that being at the
/usr/share/phpmyadmin/
Or change it to height: 0.1em;
orso, minimal size of anything displayable is 1px.
The 0.05 em you are using means, get the current font size in pixels of this elements and give me 5% of it. Which for 12 pixels returns 0.6 pixels which is too little to display. if you would turn up the font size of the div to atleast 20pixels it would display fine. I suppose Chrome doesnt round up sizes to be atleast 1pixel where other browsers do.
In order to match a digit, you can use [0-9]
.
So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9]
and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]
. I do this a lot for zip codes.
I am in ubuntu 14.04 and mongod is registered as an upstart service. The answers in this post sent me in the right direction. The only adaptation I had to do to make things work with the upstart service was to edit /etc/mongod.conf
. Look for the lines that read:
# Enable the HTTP interface (Defaults to port 28017).
# httpinterface = true
Just remove the #
in front of httpinterface and restart the mongod service:
sudo restart mongod
Note: You can also enable the rest interface by adding a line that reads
rest=true
right below the httpinterface line mentioned above.
For api 21+ you can use system image with Google Play as I describe below.
For api 19+ (Android 4.4 Kitkat) you can use system image x86 with Google Api (I was able to use it).
For api 17+ (Android 4.2.2) you can TRY to use system image ARM with Google Api (It didn't work for me).
I was able to install Google Play and Google Services as separate apks to pure system image api 16 and 17, but they don't really work after that (services crush and play not opens). So seems like it is not possible to make them work on pure AVD image because they should be installed with root access. The same for updating Google Services on AVD system image with Google API preinstalled - can't update because of incompatible certificates, can't uninstall even using adb because don't have access.
Now even better solution exist: using AVD image with build-in Google Play Services. It will enable you to use Google Services including Google Play. Also you will be able update it without re-creating AVD image.
Open AVD manager and choose create new device. You should use device definition with play store icon.
Then choose system image for it. You should choose one with Google Play and NOT with Google API.
Then launch new device.
You can update Play Services as shown on screenshot, or manually on device..
Updated Answer
* Updated answer which support the v2.1.1** bootstrap version stylesheet.
**But be careful because this solution has been removed from v3
Just wanted to point out that this solution is not needed anymore as the latest bootstrap now supports multi-level dropdowns by default. You can still use it if you're on older versions but for those who updated to the latest (v2.1.1 at the time of writing) it is not needed anymore. Here is a fiddle with the updated default multi-level dropdown straight from the documentation:
http://jsfiddle.net/2Smgv/2858/
Original Answer
There have been some issues raised on submenu support over at github and they are usually closed by the bootstrap developers, such as this one, so i think it is left to the developers using the bootstrap to work something out. Here is a demo i put together showing you how you can hack together a working sub-menu.
Relevant code
CSS
.dropdown-menu .sub-menu {
left: 100%;
position: absolute;
top: 0;
visibility: hidden;
margin-top: -1px;
}
.dropdown-menu li:hover .sub-menu {
visibility: visible;
display: block;
}
.navbar .sub-menu:before {
border-bottom: 7px solid transparent;
border-left: none;
border-right: 7px solid rgba(0, 0, 0, 0.2);
border-top: 7px solid transparent;
left: -7px;
top: 10px;
}
.navbar .sub-menu:after {
border-top: 6px solid transparent;
border-left: none;
border-right: 6px solid #fff;
border-bottom: 6px solid transparent;
left: 10px;
top: 11px;
left: -6px;
}
Created my own .sub-menu
class to apply to the 2-level drop down menus, this way we can position them next to our menu items. Also modified the arrow to display it on the left of the submenu group.
You can fix the issue with the following steps:
sudo cd /var/lib/php/session
. If it does not exist then sudo mkdir /var/lib/php/session
or double check the logs to make sure you have the correct path.sudo chmod 666 /var/lib/php/session
.Rerun you script and it should be working fine, however, it's not recommended to leave the folder with full permissions. For security, files and folders should only have the minimum permissions required. The following steps will fix that:
sudo ls -l
to find out the owner of the session file.sudo chown user /var/lib/php/session
.sudo chmod 600 /var/lib/php/session
.NB
You might not need to use the sudo
command.
No need to redirect logs.
Docker by default store logs to one log file. To check log file path run command:
docker inspect --format='{{.LogPath}}' containername
/var/lib/docker/containers/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334-json.log
Open that log file and analyse.
if you redirect logs then you will only get logs before redirection. you will not be able to see live logs.
EDIT:
To see live logs you can run below command
tail -f `docker inspect --format='{{.LogPath}}' containername`
Note:
This log file /var/lib/docker/containers/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334/f844a7b45ca5a9589ffaa1a5bd8dea0f4e79f0e2ff639c1d010d96afb4b53334-json.log
will be created only if docker generating logs if there is no logs then this file will not be there. it is similar like sometime if we run command docker logs containername
and it returns nothing. In that scenario this file will not be available.
As is clear from above explanations, by implementing the SingleThreadModel, a servlet can be assured thread-safety by the servlet container. The container implementation can do this in 2 ways:
1) Serializing requests (queuing) to a single instance - this is similar to a servlet NOT implementing SingleThreadModel BUT synchronizing the service/ doXXX methods; OR
2) Creating a pool of instances - which's a better option and a trade-off between the boot-up/initialization effort/time of the servlet as against the restrictive parameters (memory/ CPU time) of the environment hosting the servlet.
There are 4 ways to do it as far as I know.
Number(x);
parseInt(x, 10);
parseFloat(x);
+x;
By this quick test I made, it actually depends on browsers.
http://jsperf.com/best-of-string-to-number-conversion/2
Implicit
marked the fastest on 3 browsers, but it makes the code hard to read… So choose whatever you feel like it!
Have you tried:
db.posts.find({"created_on": {"$gte": new Date(2012, 7, 14), "$lt": new Date(2012, 7, 15)}})
The problem you're going to run into is that dates are stored as timestamps in Mongo. So, to match a date you're asking it to match a timestamp. In your case I think you're trying to match a day (ie. from 00:00 to 23:59 on a specific date). If your dates are stored without times then you should be okay. Otherwise, try specifying your date as a range of time on the same day (ie. start=00:00, end=23:59) if gte doesn't work.
Instead of calling /usr/bin/gcc
, use /usr/bin/c99
. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc
after having added the -std=c99
flag, which is precisely what you want.
Tooting my own horn if I may, I'd also like to suggest taking a look at an option parsing library that I've written: dropt.
One feature that it offers that many others don't is the ability to override earlier options. For example, if you have a shell alias:
alias bar="foo --flag1 --flag2 --flag3"
and you want to use bar
but with--flag1
disabled, it allows you to do:
bar --flag1=0
I think there are applications where "hash" is faster than comparing byte by byte. If you need to compare a file with others or have a thumbnail of a photo that can change. It depends on where and how it is using.
private bool CompareFilesByte(string file1, string file2)
{
using (var fs1 = new FileStream(file1, FileMode.Open))
using (var fs2 = new FileStream(file2, FileMode.Open))
{
if (fs1.Length != fs2.Length) return false;
int b1, b2;
do
{
b1 = fs1.ReadByte();
b2 = fs2.ReadByte();
if (b1 != b2 || b1 < 0) return false;
}
while (b1 >= 0);
}
return true;
}
private string HashFile(string file)
{
using (var fs = new FileStream(file, FileMode.Open))
using (var reader = new BinaryReader(fs))
{
var hash = new SHA512CryptoServiceProvider();
hash.ComputeHash(reader.ReadBytes((int)file.Length));
return Convert.ToBase64String(hash.Hash);
}
}
private bool CompareFilesWithHash(string file1, string file2)
{
var str1 = HashFile(file1);
var str2 = HashFile(file2);
return str1 == str2;
}
Here, you can get what is the fastest.
var sw = new Stopwatch();
sw.Start();
var compare1 = CompareFilesWithHash(receiveLogPath, logPath);
sw.Stop();
Debug.WriteLine(string.Format("Compare using Hash {0}", sw.ElapsedTicks));
sw.Reset();
sw.Start();
var compare2 = CompareFilesByte(receiveLogPath, logPath);
sw.Stop();
Debug.WriteLine(string.Format("Compare byte-byte {0}", sw.ElapsedTicks));
Optionally, we can save the hash in a database.
Hope this can help
[a-zA-Z]{2}\d{6}
[a-zA-Z]{2}
means two letters
\d{6}
means 6 digits
If you want only uppercase letters, then:
[A-Z]{2}\d{6}
For Mac OS X Mojave and above
To Uninstall Homebrew, run following command:
sudo ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
To Install Homebrew, run following command:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And if you run into Permission denied issue, try running this command followed by install command again:
sudo chown -R $(whoami):admin /usr/local/* && sudo chmod -R g+rwx /usr/local/*
Set the seed(x)
before generating a set of random numbers and use the same seed to generate the same set of random numbers. Useful in case of reproducing the issues.
>>> from random import *
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>>
I'd use the accepted answer, but another possibility is to use a table variable to hold a numbered set of values (in this case just the ID field of a table) and loop through those by Row Number with a JOIN to the table to retrieve whatever you need for the action within the loop.
DECLARE @RowCnt int; SET @RowCnt = 0 -- Loop Counter
-- Use a table variable to hold numbered rows containg MyTable's ID values
DECLARE @tblLoop TABLE (RowNum int IDENTITY (1, 1) Primary key NOT NULL,
ID INT )
INSERT INTO @tblLoop (ID) SELECT ID FROM MyTable
-- Vars to use within the loop
DECLARE @Code NVarChar(10); DECLARE @Name NVarChar(100);
WHILE @RowCnt < (SELECT COUNT(RowNum) FROM @tblLoop)
BEGIN
SET @RowCnt = @RowCnt + 1
-- Do what you want here with the data stored in tblLoop for the given RowNum
SELECT @Code=Code, @Name=LongName
FROM MyTable INNER JOIN @tblLoop tL on MyTable.ID=tL.ID
WHERE tl.RowNum=@RowCnt
PRINT Convert(NVarChar(10),@RowCnt) +' '+ @Code +' '+ @Name
END
If you're doing computations:
isCancelled()
periodically.If you're doing a HTTP request:
HttpGet
or HttpPost
somewhere (eg. a public field).cancel
, call request.abort()
. This will cause IOException
be thrown inside your doInBackground
.In my case, I had a connector class which I used in various AsyncTasks. To keep it simple, I added a new abortAllRequests
method to that class and called this method directly after calling cancel
.
This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:
//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
...
}
Hope it helps
?Handling errors is very important in programming. You do need to show the user what went wrong. In very few cases you can ignore the errors. This is it is very bad programming practice.
I have tried the accepted answer; however:
console.log(typeof me.onChange);
returns 'undefined'. I've noticed that the specification states an event called 'onchange' instead of 'onChange' (notice the camelCase).
Changing the original accepted answer to the following worked for me:
if (typeof me.onchange === "function") {
// safe to use the function
}
You can do:
hash=$(genhash --use-ssl -s $IP -p 443 --url $URL)
or
hash=`genhash --use-ssl -s $IP -p 443 --url $URL`
If you want to result of the entire pipe to be assigned to the variable, you can use the entire pipeline in the above assignments.
We can use setProperty or cssText to add !important
to a DOM element using JavaScript.
Example 1:
elem.style.setProperty ("color", "green", "important");
Example 2:
elem.style.cssText='color: red !important;'
For Android Studio (or IntelliJ IDEA),
If everything looks OK in your project and that you're still receiving the error in all your layouts, try to 'Invalidate caches & restart'.
Wait until Android Studio has finished to create all the caches & indexes.
The setHours
method can take optional minutes
, seconds
and ms
arguments, for example:
var d = new Date();
d.setHours(0,0,0,0);
That will set the time to 00:00:00.000
of your current timezone, if you want to work in UTC time, you can use the setUTCHours
method.
There is also direct support for white space removal in Bash variable substitution:
testvar=$(wc -l < log.txt)
trailing_space_removed=${testvar%%[[:space:]]}
leading_space_removed=${testvar##[[:space:]]}
You could use the following extension:
public extension Date {
func daysTo(_ date: Date) -> Int? {
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: self)
let date2 = calendar.startOfDay(for: date)
let components = calendar.dateComponents([.day], from: date1, to: date2)
return components.day // This will return the number of day(s) between dates
}
}
Then, you can call it like this:
startDate.daysTo(endDate)
A lot of dancing around the answer. You can add the UDF context help, but you have to export the Module and edit the contents in a text editor, then re-import it to VBA. Here's the example from Chip Pearson: Adding Code Attributes
Lets see two efficient ways that deal with escaped quotes. These patterns are not designed to be concise nor aesthetic, but to be efficient.
These ways use the first character discrimination to quickly find quotes in the string without the cost of an alternation. (The idea is to discard quickly characters that are not quotes without to test the two branches of the alternation.)
Content between quotes is described with an unrolled loop (instead of a repeated alternation) to be more efficient too: [^"\\]*(?:\\.[^"\\]*)*
Obviously to deal with strings that haven't balanced quotes, you can use possessive quantifiers instead: [^"\\]*+(?:\\.[^"\\]*)*+
or a workaround to emulate them, to prevent too much backtracking. You can choose too that a quoted part can be an opening quote until the next (non-escaped) quote or the end of the string. In this case there is no need to use possessive quantifiers, you only need to make the last quote optional.
Notice: sometimes quotes are not escaped with a backslash but by repeating the quote. In this case the content subpattern looks like this: [^"]*(?:""[^"]*)*
The patterns avoid the use of a capture group and a backreference (I mean something like (["']).....\1
) and use a simple alternation but with ["']
at the beginning, in factor.
Perl like:
["'](?:(?<=")[^"\\]*(?s:\\.[^"\\]*)*"|(?<=')[^'\\]*(?s:\\.[^'\\]*)*')
(note that (?s:...)
is a syntactic sugar to switch on the dotall/singleline mode inside the non-capturing group. If this syntax is not supported you can easily switch this mode on for all the pattern or replace the dot with [\s\S]
)
(The way this pattern is written is totally "hand-driven" and doesn't take account of eventual engine internal optimizations)
ECMA script:
(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')
POSIX extended:
"[^"\\]*(\\(.|\n)[^"\\]*)*"|'[^'\\]*(\\(.|\n)[^'\\]*)*'
or simply:
"([^"\\]|\\.|\\\n)*"|'([^'\\]|\\.|\\\n)*'
I tried using the iframe embed code and the HTML5 player appeared, however, for some reason the iframe was completely breaking my site.
I messed around with the old object embed code and it works perfectly fine. So if you're having problems with the iframe here's the code i used:
<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/VIDEO_ID?html5=1&rel=0&hl=en_US&version=3"/>
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/VIDEO_ID?html5=1&rel=0&hl=en_US&version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>
hope this is useful for someone
Try this:
Define a funciton:
<?php
function phpAlert($msg) {
echo '<script type="text/javascript">alert("' . $msg . '")</script>';
}
?>
Call it like this:
<?php phpAlert( "Hello world!\\n\\nPHP has got an Alert Box" ); ?>
The above steps, though helpful, didnt work for me on Windows 8. I don't know the co-relation, but the below steps worked. Basically a change in the cacert.pem file. Hope this helps someone.
In a crontab
file, the fields are:
So:
10 * * * * blah
means execute blah
at 10 minutes past every hour.
If you want every five minutes, use either:
*/5 * * * * blah
meaning every minute but only every fifth one, or:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah
for older cron
executables that don't understand the */x
notation.
If it still seems to be not working after that, change the command to something like:
date >>/tmp/debug_cron_pax.txt
and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron
daemon.
l = []
x = 0
l.extend([x]*100)
I would always use a Unix timestamp when working with MySQL and PHP. The main reason for this being the default date method in PHP uses a timestamp as the parameter, so there would be no parsing needed.
To get the current Unix timestamp in PHP, just do time();
and in MySQL do SELECT UNIX_TIMESTAMP();
.
Documenting in detail for future readers:
The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url)
method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.
The below is the skeleton on how you would accomplish this:
class CustomWebViewClient extends WebViewClient {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final Uri uri = Uri.parse(url);
return handleUri(uri);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return handleUri(uri);
}
private boolean handleUri(final Uri uri) {
Log.i(TAG, "Uri =" + uri);
final String host = uri.getHost();
final String scheme = uri.getScheme();
// Based on some condition you need to determine if you are going to load the url
// in your web view itself or in a browser.
// You can use `host` or `scheme` or any part of the `uri` to decide.
if (/* any condition */) {
// Returning false means that you are going to load this url in the webView itself
return false;
} else {
// Returning true means that you need to handle what to do with the url
// e.g. open web page in a Browser
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
}
}
Just like shouldOverrideUrlLoading
, you can come up with a similar approach for shouldInterceptRequest
method.
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
While there is no valid way to omit an image's source, there are sources which won't cause server hits. I recently had a similar issue with iframe
s and determined //:0
to be the best option. No, really!
Starting with //
(omitting the protocol) causes the protocol of the current page to be used, preventing "insecure content" warnings in HTTPS pages. Skipping the host name isn't necessary, but makes it shorter. Finally, a port of :0
ensures that a server request can't be made (it isn't a valid port, according to the spec).
This is the only URL which I found caused no server hits or error messages in any browser. The usual choice — javascript:void(0)
— will cause an "insecure content" warning in IE7 if used on a page served via HTTPS. Any other port caused an attempted server connection, even for invalid addresses. (Some browsers would simply make the invalid request and wait for them to time out.)
This was tested in Chrome, Safari 5, FF 3.6, and IE 6/7/8, but I would expect it to work in any browser, as it should be the network layer which kills any attempted request.
You should use the as
operator combined with the ??
operator for default values. Value types will need to be read as nullable and given a default.
employee.FirstName = sqlreader[indexFirstName] as string;
employee.Age = sqlreader[indexAge] as int? ?? default(int);
The as
operator handles the casting including the check for DBNull.
Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.
For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept
property to "application/json".
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
1.Post-Build Actions > Select ”Trigger parameterized build on other projects”
2.Enter the environment variable with value.Value can also be Jenkins Build Parameters.
Detailed steps can be seen here :-
Hope it's helpful :)
Might want to check out jQuery Timer to manage one or multiple timers.
http://code.google.com/p/jquery-timer/
var timer = $.timer(yourfunction, 10000);
function yourfunction() { alert('test'); }
Then you can control it with:
timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...
As a practical matter, the advantage of synchronized methods over synchronized blocks is that they are more idiot-resistant; because you can't choose an arbitrary object to lock on, you can't misuse the synchronized method syntax to do stupid things like locking on a string literal or locking on the contents of a mutable field that gets changed out from under the threads.
On the other hand, with synchronized methods you can't protect the lock from getting acquired by any thread that can get a reference to the object.
So using synchronized as a modifier on methods is better at protecting your cow-orkers from hurting themselves, while using synchronized blocks in conjunction with private final lock objects is better at protecting your own code from the cow-orkers.
Since I spent quite some time trying to solve this and always came back to this page when looking for this error, I'll leave my solution here hoping that somebody saves the time I've lost. Although in my case I am using mariadb rather than MySql, you might still be able to adapt this solution to your needs.
is the same, but my setup is a bit different (mariadb instead of mysql):
Installed mariadb with homebrew
$ brew install mariadb
Started the daemon
$ brew services start mariadb
Tried to connect and got the above mentioned error
$ mysql -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
find out which my.cnf
files are used by mysql
(as suggested in this comment):
$ mysql --verbose --help | grep my.cnf
/usr/local/etc/my.cnf ~/.my.cnf
order of preference, my.cnf, $MYSQL_TCP_PORT,
check where the Unix socket file is running (almost as described here):
$ netstat -ln | grep mariadb
.... /usr/local/mariadb/data/mariadb.sock
(you might want to grep mysql
instead of mariadb)
Add the socket file you found to ~/.my.cnf
(create the file if necessary)(assuming ~/.my.cnf
was listed when running the mysql --verbose ...
-command from above):
[client]
socket = /usr/local/mariadb/data/mariadb.sock
Restart your mariadb:
$ brew services restart mariadb
After this I could run mysql and got:
$ mysql -uroot
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
So I run the command with superuser privileges instead and after entering my password I got:
$ sudo mysql -uroot
MariaDB [(none)]>
Notes:
I'm not quite sure about the groups where you have to add the socket, first I had it [client-server] but then I figured [client] should be enough. So I changed it and it still works.
When running mariadb_config | grep socket
I get:
--socket [/tmp/mysql.sock]
which is a bit confusing since it seems that /usr/local/mariadb/data/mariadb.sock
is the actual place (at least on my machine)
I wonder where I can configure the /usr/local/mariadb/data/mariadb.sock
to actually be /tmp/mysql.sock
so I can use the default settings instead of having to edit my .my.cnf
(but I'm too tired now to figure that out...)
At some point I also did things mentioned in other answers before coming up with this.
Class which can have both concrete and non-concrete methods i.e. with and without body.
Little out of date but here is a function you can use!
function calculateAge(birthMonth, birthDay, birthYear) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDate();
var calculatedAge = currentYear - birthYear;
if (currentMonth < birthMonth - 1) {
calculatedAge--;
}
if (birthMonth - 1 == currentMonth && currentDay < birthDay) {
calculatedAge--;
}
return calculatedAge;
}
var age = calculateAge(12, 8, 1993);
alert(age);
https://github.com/dualface/cocos2d-x-extensions/blob/master/TODO.tasks , he is developing nice features on cocos2d-x
WHERE clause can be used with SELECT, INSERT, and UPDATE statements, whereas HAVING can be used only with SELECT statement.
WHERE filters rows before aggregation (GROUP BY), whereas HAVING filter groups after aggregations are performed.
Aggregate function cannot be used in WHERE clause unless it is in a subquery contained in HAVING clause, whereas aggregate functions can be used in HAVING clause.
if the project is not a big ,
1- change the name of folder project
2- make a new project with the same project (before renaming)
3- add existing files from the old project to the new project (totally same , same folders , same names , ...)
4- open the the new project file (as xml ) and the old project
5- copy the new project file (xml content ) and paste it in the old project file
6- delete the old project
7- rename the old folder project to old name
I know this question is old but it can be done in one line of code
String deviceID = Build.SERIAL;
The executable packer maven plugin can be used for exactly that purpose: creating standalone java applications containing all dependencies as JAR files in a specific folder.
Just add the following to your pom.xml
inside the <build><plugins>
section (be sure to replace the value of mainClass
accordingly):
<plugin>
<groupId>de.ntcomputer</groupId>
<artifactId>executable-packer-maven-plugin</artifactId>
<version>1.0.1</version>
<configuration>
<mainClass>com.example.MyMainClass</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>pack-executable-jar</goal>
</goals>
</execution>
</executions>
</plugin>
The built JAR file is located at target/<YourProjectAndVersion>-pkg.jar
after you run mvn package
. All of its compile-time and runtime dependencies will be included in the lib/
folder inside the JAR file.
Disclaimer: I am the author of the plugin.
Without proper language support for thread syncronization, it doesn't even make sense for new implementations to try. Existing complex JS apps (e.g. anything using ExtJS) would most likely crash unexpectedly, but without a synchronized
keyword or something similar, it would also be very hard or even impossible to write new programs that behave correctly.
You can use the multiprocessing module. For this case I might use a processing pool:
from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(solve1, [A]) # evaluate "solve1(A)" asynchronously
result2 = pool.apply_async(solve2, [B]) # evaluate "solve2(B)" asynchronously
answer1 = result1.get(timeout=10)
answer2 = result2.get(timeout=10)
This will spawn processes that can do generic work for you. Since we did not pass processes
, it will spawn one process for each CPU core on your machine. Each CPU core can execute one process simultaneously.
If you want to map a list to a single function you would do this:
args = [A, B]
results = pool.map(solve1, args)
Don't use threads because the GIL locks any operations on python objects.
You can use #0
as href, since 0
isn't allowed as an id, the page won't jump.
<a href="#0" class="someclass">Text</a>
You can always, reshape like:
temp = [1,2,3,4,5,5,6,7]
temp = temp.reshape(len(temp), 1)
Because, the major issue is when your, temp.shape is: (8,)
and you need (8,1)
There is a way to get count of runes without any packages by converting string to []rune as len([]rune(YOUR_STRING))
:
package main
import "fmt"
func main() {
russian := "??????? ? ??????"
english := "Sputnik & pogrom"
fmt.Println("count of bytes:",
len(russian),
len(english))
fmt.Println("count of runes:",
len([]rune(russian)),
len([]rune(english)))
}
count of bytes 30 16
count of runes 16 16
Try inserting this clearing div before the last </div>
<div style="clear: both; line-height: 0;"> </div>
To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:
select profile from DBA_USERS where username = '<username>';
Then you can change the limit to never expire using:
alter profile <profile_name> limit password_life_time UNLIMITED;
If you want to previously check the limit you may use:
select resource_name,limit from dba_profiles where profile='<profile_name>';
This can be achieved using a Spannable String. You will need to import the following
import android.text.SpannableString;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
And then you can change the background of the text using something like the following:
TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Add all your funky text in here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);
Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!
You can add a new column at the end of your table
ALTER TABLE assessment ADD q6 VARCHAR( 255 )
Add column to the begining of table
ALTER TABLE assessment ADD q6 VARCHAR( 255 ) FIRST
Add column next to a specified column
ALTER TABLE assessment ADD q6 VARCHAR( 255 ) after q5
and more options here