Button clicks are client side whereas PHP is executed server side, but you can achieve this by using Ajax:
$('.button').click(function() {
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In your PHP file:
<?php
function abc($name){
// Your code here
}
?>
Figured this out:
<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />
<script>
function searchKeyPress(e)
{
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13)
{
document.getElementById('btnSearch').click();
return false;
}
return true;
}
</script>
I think you can find your answer here : Is an anchor tag without the href attribute safe?
Also if you want to no link operation with href , you can use it like :
<a href="javascript:void(0);">something</a>
Yes, you can make a button not submit a form by adding an attribute of type of value button:
<button type="button"><button>
Here, i am using link in the form of button for CANCEL operation.
<button><a href="main.html">cancel</a></button>
You can set padding to your view by pro grammatically throughout below code -
view.setPadding(0,1,20,3);
And, also there are different type of padding available -
These, links will refer Android Developers site. Hope this helps you lot.
Yes numpy has a size function, and shape and size are not quite the same.
Input
import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)
print(data)
print(arrData.size)
print(arrData.shape)
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
8 # size
(2, 4) # shape
Your makefile should ideally be named makefile
, not make
. Note that you can call your makefile anything you like, but as you found, you then need the -f
option with make
to specify the name of the makefile. Using the default name of makefile
just makes life easier.
For the instance of
render :json => @projects, :include => :tasks
You are stating that you want to render @projects
as JSON, and include the association tasks
on the Project model in the exported data.
For the instance of
render :json => @projects, :callback => 'updateRecordDisplay'
You are stating that you want to render @projects
as JSON, and wrap that data in a javascript call that will render somewhat like:
updateRecordDisplay({'projects' => []})
This allows the data to be sent to the parent window and bypass cross-site forgery issues.
In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:
$.ajax(
'https://foo.bar.com,
{
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: successFunc
}
);
The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:
An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT
While you could use a continue
, why not just inverse the logic in your if?
while(rs.next())
{
if(!f.exists() || f.isDirectory()){
//proceed
}
}
You don't even need an else {continue;}
as it will continue anyway if the if
conditions are not satisfied.
When I received this error I believe it was a bug, however you should keep in mind that if you do a separate query with a SELECT statement and the same WHERE clause, then you can grab the primary ID's from that SELECT: SELECT CONCAT(primary_id, ',')
) statement and insert them into the failed UPDATE query with conditions -> "WHERE [primary_id] IN ([list of comma-separated primary ID's from the SELECT statement)" which allows you to alleviate any issues being caused by the original (failed) query's WHERE clause.
For me, personally, when I was using quotes for the values in the "WHERE ____ IN ([values here])", only 10 of the 300 expected entries were being affected which, in my opinion, seems like a bug.
With the new (yet in Editor's draft) CSS 4 properties you can achieve this by using min()
and max()
(also you can use clamp()
as a - kind of - shorthand for both min()
and max()
clamp(MIN, VAL, MAX)
is resolved asmax(MIN, min(VAL, MAX))
min()
syntax:
min( <calc-sum># ) where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]* where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
max()
syntax:
max( <calc-sum># ) where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]* where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
clamp()
syntax:
clamp( <calc-sum>#{3} ) where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]* where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
.min {
/* demo */
border: green dashed 5px;
/*this your min padding-left*/
padding-left: min(50vw, 50px);
}
.max {
/* demo */
border: blue solid 5px;
/*this your max padding-left*/
padding-left: max(50vw, 500px);
}
.clamp {
/* demo */
border: red dotted 5px;
/*this your clamp padding-left*/
padding-left: clamp(50vw, 70vw, 1000px);
}
/* demo */
* {
box-sizing: border-box
}
section {
width: 50vw;
}
div {
height: 100px
}
/* end of demo */
_x000D_
<section>
<div class="min"></div>
<div class="max"></div>
<div class="clamp"></div>
</section>
_x000D_
No you can't.
margin
and padding
properties don't have the min
/max
prefixes
An approximately way would be using relative units (vh
/vw
), but still not min/max
And as @vigilante_stark pointed out in the answer, the CSS calc()
function could be another workaround, something like these:
/* demo */
* {
box-sizing: border-box
}
section {
background-color: red;
width: 50vw;
height: 50px;
position: relative;
}
div {
width: inherit;
height: inherit;
position: absolute;
top: 0;
left: 0
}
/* end of demo */
.min {
/* demo */
border: green dashed 4px;
/*this your min padding-left*/
padding-left: calc(50vw + 50px);
}
.max {
/* demo */
border: blue solid 3px;
/*this your max padding-left*/
padding-left: calc(50vw + 200px);
}
_x000D_
<section>
<div class="min"></div>
<div class="max"></div>
</section>
_x000D_
If you already have a database, keep it in your asset folder and copy it in your application. For more detail, see Android database basics.
I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.
public static void RemoveEverythingButUserInfo()
{
foreach (String o in HttpContext.Current.Session.Keys)
{
if (o != "UserInfoIDontWantToAskForAgain")
keys.Add(o);
}
}
For Kotlin on fragment just do this
activity?.runOnUiThread(Runnable {
//on main thread
})
should be handled as a whitespace.
should be handled as two whitespaces
' ' can be handled as a non interesting whitespace
' ' + ' ' can be handled as a single ' '
You could make the element containing the bg text have a lower stacking order ( z-index, position ) and possibly even set opacity. So the element you need on top would need a higher stacking order ( z-index:5; position:relative; for ex ) and the element behind would need something lower ( default or just a lower z-index like 3 and position:relative; ).
It means that es3.c
does not define a main
function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.
To compile only to an object file, use the -c
option:
gcc es3.c -c
gcc es3.o main.c -o es3
The above compiles es3.c
to an object file, then compiles a file main.c
that would contain the main
function, and the linker merges es3.o
and main.o
into an executable called es3
.
I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/
It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.
The Makefile looking like:
EXECUTABLE = src/Main.cpp
CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32
src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)
all: myprog
myprog: $(obj)
$(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)
.PHONY: clean
clean:
del $(obj) $(EXECUTABLE)
My BASIC interpreter chops beginning and ending quotes with
str->pop_back();
str->erase(str->begin());
Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert
if not:
assert(str->front() == '"' && str->back() == '"');
Just my two cents.
A workaround that worked for me (using Backbone.js), was to add "#/" to the end of the redirect URL passed to Facebook. Facebook will keep the provided fragment, and not append its own "_=_".
Upon return, Backbone will remove the "#/" part. For AngularJS, appending "#!" to the return URL should work.
Note that the fragment identifier of the original URL is preserved on redirection (via HTTP status codes 300, 301, 302 and 303) by most browsers, unless the redirect URL also has a fragment identifier. This seems to be recommended behaviour.
If you use a handler script that redirects the user elsewhere, you can append "#" to the redirect URL here to replace the fragment identifier with an empty string.
The file .bashrc
is read when you start an interactive shell. This is the file that you should update. E.g:
export PATH=$PATH:/opt/ActiveTcl-8.5/bin
Restart the shell for the changes to take effect or source it, i.e.:
source .bashrc
If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:
from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places
From the documentation:
class matplotlib.ticker.StrMethodFormatter(fmt)
Use a new-style format string (as used by str.format()) to format the tick.
The field used for the value must be labeled x and the field used for the position must be labeled pos.
Here's a simple, yet powerful example, using the apache class HierarchicalINIConfiguration:
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile);
// Get Section names in ini file
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();
while(sectionNames.hasNext()){
String sectionName = sectionNames.next().toString();
SubnodeConfiguration sObj = iniObj.getSection(sectionName);
Iterator it1 = sObj.getKeys();
while (it1.hasNext()) {
// Get element
Object key = it1.next();
System.out.print("Key " + key.toString() + " Value " +
sObj.getString(key.toString()) + "\n");
}
Commons Configuration has a number of runtime dependencies. At a minimum, commons-lang and commons-logging are required. Depending on what you're doing with it, you may require additional libraries (see previous link for details).
This is actually a documented feature, and can be found here
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
yourTextView.setTextColor(color);
Or, in your case: yourTextView.setTextColor(0xffbdbdbd);
Wait, are you really needing to render it using javascript?
Be aware that in HTML5 there is srcdoc
, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)
See here [srcdoc
]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp
Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox
mode.
See here [sandbox
]: https://www.w3schools.com/tags/att_iframe_sandbox.asp
LATEST UPDATE:
Use the official version from jCenter instead.
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
The dependencies below points to deprecated volley that is no longer maintained.
ORIGINAL ANSWER
You can use this in dependency section of your build.gradle file to use volley
dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}
UPDATED:
Its not official but a mirror copy of official Volley. It is regularly synced and updated with official Volley Repository so you can go ahead to use it without any worry.
A simple jquery solution for those who don't need a pure css solution:
$(".letter").hover(function() {_x000D_
$(this).closest("#word").toggleClass("hovered")_x000D_
});
_x000D_
.hovered {_x000D_
background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
margin: 20px;_x000D_
background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
<div class="letter">T</div>_x000D_
<div class="letter">E</div>_x000D_
<div class="letter">S</div>_x000D_
<div class="letter">T</div>_x000D_
</div>
_x000D_
pChart is another great PHP graphing library.
Node is able to concatenate buffers on its own now.
var newBuffer = Buffer.concat([buffer1, buffer2]);
I use a module to add a .concat
function, among others:
https://github.com/coolaj86/node-bufferjs
I know it isn't a "pure" solution, but it works very well for my purposes.
All the answers above are great, I see one thing missing and could be considered for running javascripts(*.js)
files, the unrelated brother of javascript
the Java
.
JDK
comes up with two nice tools, could be utilized for executing javascripts
.
Here are command goes like. Make sure to navigate to JDK\bin
.
jjs example.js
Its comes up with another commmand
tool that goes like this-
jrunscript example.js
I hope this may be helpful to others.
The Chrome Browser versión should matches with the chromeDriver versión. Go to : chrome://settings/help
How do I confirm I'm using the right chromedriver?
I just removed all the private libraries in JavaBuildPath and added the jars again.. It worked
I know this question is old, but it deserves an answer. I personally prefer to create a WSDL by hand and test for compliance using SoapUI. But sometimes (specially for complex WSDLs), you have three ways to generate one out of an XSD:
I prefer the CXF approach since I'm a CLI guy. If it has a CLI, you can automate (that's my motto). And I like the Spring WS approach the least since it uses a lot of framework specific conventions.
There are more people who know CXF (I believe) than Spring WS. So anything that can throw a learning curve for a new engineer (without any clear advantage or ROI) is something I frown upon.
It should also go w/o saying that any generated WSDL should be tested for validity and compliance (and tweaked till it complies), and that your application publishes a static wsdl (as opposed to returning an auto-generated one.)
It's been my experience that you start with a WS-I compliant wsdl and then your application auto-generates (and returns to consumers) a non-compliant one.
In other words, beware of auto magic.
how about sysdate?
SELECT field,datetime_field
FROM database
WHERE datetime_field > (sysdate-1)
Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:
GridLines="None"
CellSpacing="-1"
Another place you could stop the timer is the FormClosing event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.
Your code is a no-op. By the definition of the loop, "item" has to be in Z. A "For ... in" loop in Python means "Loop though the list called 'z', each time you loop, give me the next item in the list, and call it 'item'"
http://docs.python.org/tutorial/controlflow.html#for-statements
I think your confusion arises from the fact that you're using the variable name "item" twice, to mean two different things.
This worked for me:
sudo apt-get install php5-sqlite
This installed sqlite for php5, then I ran the php artisan migrate command again and worked perfectly.
Try \n\n , it will work! :)
public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}
To answer that question, I'd like to describe member's accessors first in my own words. If you already know this, skip to the heading "next:".
There are three accessors that I'm aware of: public
, protected
and private
.
Let:
class Base {
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};
Base
is also aware that Base
contains publicMember
.Base
contains protectedMember
.Base
is aware of privateMember
.By "is aware of", I mean "acknowledge the existence of, and thus be able to access".
The same happens with public, private and protected inheritance. Let's consider a class Base
and a class Child
that inherits from Base
.
public
, everything that is aware of Base
and Child
is also aware that Child
inherits from Base
.protected
, only Child
, and its children, are aware that they inherit from Base
.private
, no one other than Child
is aware of the inheritance.My solution:
public static class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final MainActivity mParentActivity;
private final List<DummyContent.DummyItem> mValues;
private final boolean mTwoPane;
private static int lastClickedPosition=-1;
**private static View viewOld=null;**
private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
DummyContent.DummyItem item = (DummyContent.DummyItem) view.getTag();
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, item.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
mParentActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = view.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, item.id);
context.startActivity(intent);
}
**view.setBackgroundColor(mParentActivity.getResources().getColor(R.color.SelectedColor));
if(viewOld!=null)
viewOld.setBackgroundColor(mParentActivity.getResources().getColor(R.color.DefaultColor));
viewOld=view;**
}
};
viewOld
is null
at the beginning, then points to the last selected view.
With onClick
you change the background of the selected view and redefine the background of the penultimate view selected.
Simple and functional.
=>
is used in associative array key value assignment. Take a look at:
http://php.net/manual/en/language.types.array.php.
->
is used to access an object method or property. Example: $obj->method()
.
Your code works also for me. However, another workaround can be to get the plot's axis and then change only the y-values:
x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))
Try this :
####################
# GZIP COMPRESSION #
####################
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/x-httpd-php
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip
It's not possible to define member functions or derive structs from each other in C.
Also, C++ is not only C + "derive structs". Templates, references, user defined namespaces and operator overloading all do not exist in C.
<tbody>
<tr data-href='www.bbc.co.uk'>
<td>Blah Blah</td>
<td>1234567</td>
<td>£158,000</td>
</tr>
<tr data-href='www.google.com'>
<td>Blah Blah</td>
<td>1234567</td>
<td>£158,000</td>
</tr>
</tbody>
<script>
jQuery(document).ready(function ($) {
$('[data-href]').click(function () {
window.location = $(this).data("href");
});
});
</script>
Whilst the main solution on here is great, my solution removes the need for classes. All you need to do is add the data-href attribute with the URL in it.
This one is simple
const upper = lower.replace(/^\w/, c => c.toUpperCase());
In my case i had to move the html code of the element i wanted at the front at the end of the html file, because if one element has z-index and the other doesn't have z index it doesn't work.
You can try this UITextfield subclass which you can set a condition for the text to dynamically change the UIReturnKey:
https://github.com/codeinteractiveapps/OBReturnKeyTextField
jQuery Solution!
Demo: http://jsfiddle.net/69wP6/2/
Another Demo Below(updated!)
I needed something similar in a case when i had some fixed Options and i wanted one other option to be editable! In this case i made a hidden input that would overlap the select option and would be editable and used jQuery to make it all work seamlessly.
I am sharing the fiddle with all of you!
HTML
<div id="billdesc">
<select id="test">
<option class="non" value="option1">Option1</option>
<option class="non" value="option2">Option2</option>
<option class="editable" value="other">Other</option>
</select>
<input class="editOption" style="display:none;"></input>
</div>
CSS
body{
background: blue;
}
#billdesc{
padding-top: 50px;
}
#test{
width: 100%;
height: 30px;
}
option {
height: 30px;
line-height: 30px;
}
.editOption{
width: 90%;
height: 24px;
position: relative;
top: -30px
}
jQuery
var initialText = $('.editable').val();
$('.editOption').val(initialText);
$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();
if(selected == "editable"){
$('.editOption').show();
$('.editOption').keyup(function(){
var editText = $('.editOption').val();
$('.editable').val(editText);
$('.editable').html(editText);
});
}else{
$('.editOption').hide();
}
});
Edit : Added some simple touches design wise, so people can clearly see where the input ends!
JS Fiddle : http://jsfiddle.net/69wP6/4/
I've only tested this in Rails 4 but there's an interesting way to use a range with a where
hash to get this behavior.
User.where(id: 201..Float::INFINITY)
will generate the SQL
SELECT `users`.* FROM `users` WHERE (`users`.`id` >= 201)
The same can be done for less than with -Float::INFINITY
.
I just posted a similar question asking about doing this with dates here on SO.
>=
vs >
To avoid people having to dig through and follow the comments conversation here are the highlights.
The method above only generates a >=
query and not a >
. There are many ways to handle this alternative.
For discrete numbers
You can use a number_you_want + 1
strategy like above where I'm interested in Users with id > 200
but actually look for id >= 201
. This is fine for integers and numbers where you can increment by a single unit of interest.
If you have the number extracted into a well named constant this may be the easiest to read and understand at a glance.
Inverted logic
We can use the fact that x > y == !(x <= y)
and use the where not chain.
User.where.not(id: -Float::INFINITY..200)
which generates the SQL
SELECT `users`.* FROM `users` WHERE (NOT (`users`.`id` <= 200))
This takes an extra second to read and reason about but will work for non discrete values or columns where you can't use the + 1
strategy.
Arel table
If you want to get fancy you can make use of the Arel::Table
.
User.where(User.arel_table[:id].gt(200))
will generate the SQL
"SELECT `users`.* FROM `users` WHERE (`users`.`id` > 200)"
The specifics are as follows:
User.arel_table #=> an Arel::Table instance for the User model / users table
User.arel_table[:id] #=> an Arel::Attributes::Attribute for the id column
User.arel_table[:id].gt(200) #=> an Arel::Nodes::GreaterThan which can be passed to `where`
This approach will get you the exact SQL you're interested in however not many people use the Arel table directly and can find it messy and/or confusing. You and your team will know what's best for you.
Starting in Rails 5 you can also do this with dates!
User.where(created_at: 3.days.ago..DateTime::Infinity.new)
will generate the SQL
SELECT `users`.* FROM `users` WHERE (`users`.`created_at` >= '2018-07-07 17:00:51')
Once Ruby 2.6 is released (December 25, 2018) you'll be able to use the new infinite range syntax! Instead of 201..Float::INFINITY
you'll be able to just write 201..
. More info in this blog post.
This is an old question but I didn't find the fix I used, so I've added it here.
In my case it was a namespace with the same name as a class in the parent namespace.
To find this, I used the object browser and searched for the name of the item that was already defined.
If it won't let you do this while you still have the error then temporarily change the name of the item it is complaining about and then find the offending item.
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
.vue
files<script>
var mylib = require('./mylib');
export default {
....
mylib
exports.myfunc = () => {....}
import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
Inside container(in docker, not in VM), by default these are not installed. Even apt-get, wget will not work. My VM is running on Ubuntu 17.10. For me yum package manaager worked.
Yum is not part of debian or ubuntu. It is part of red-hat. But, it works in Ubuntu and it is installed by default like apt-get
Tu install vim, use this command
yum install -y vim-enhanced
To uninstall vim :
yum uninstall -y vim-enhanced
Similarly,
yum install -y wget
yum install -y sudo
-y is for assuming yes if prompted for any qustion asked after doing yum install packagename
To run org.apache.http.legacy perfectely in Android 9.0 Pie create an xml file res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
And add 2 tags tag in your AndroidManifest.xml
android:networkSecurityConfig="@xml/network_security_config" android:name="org.apache.http.legacy"
<?xml version="1.0" encoding="utf-8"?>
<manifest......>
<application android:networkSecurityConfig="@xml/network_security_config">
<activity..../>
......
......
<uses-library
android:name="org.apache.http.legacy"
android:required="false"/>
</application>
Also add useLibrary 'org.apache.http.legacy'
in your app build gradle
android {
compileSdkVersion 28
defaultConfig {
applicationId "your application id"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
useLibrary 'org.apache.http.legacy'
}
font-size:35px;
So like this:
<html>
<tr>
<td style="padding-left:5px;padding-bottom:3px;">
<strong style="font-size:35px;">Datum:</strong>
<br/>
November 2010
</td>
</tr>
</html>
Although inline styles are a bad practice and you should class things. Also you should use a <strong></strong>
tag instead of <b></b>
Export extensions (Bash):
code --list-extensions |
xargs -L 1 echo code --install-extension |
sed 's/$/ --force/' |
sed '$!s/$/ \&\&/' > install-extensions.sh
With bash alias:
alias eve="code --list-extensions |
xargs -L 1 echo code --install-extension |
sed 's/$/ --force/' |
sed '\$!s/$/ \&\&/' > install-extensions.sh"
Just run
eve
Install extensions (Bash):
sh install-extensions.sh
ps ax | grep processName
if yor debug script in pycharm always exit
pydevd.py --multiproc --client 127.0.0.1 --port 33882 --file processName
If it is on the stack, the contents of uninitialized members that don't have their own constructor will be random and undefined. Even if it is global, it would be a bad idea to rely on them being zeroed out. Whether it is on the stack or not, if a member has its own constructor, that will get called to initialize it.
So, if you have string* pname, the pointer will contain random junk. but for string name, the default constructor for string will be called, giving you an empty string. For your reference type variables, I'm not sure, but it'll probably be a reference to some random chunk of memory.
If you want to cut out the last or the first do this:
list = ["This", "is", "a", "list"]
listnolast = list[:-1]
listnofirst = list[1:]
If you change 1 to 2 the first 2 characters will be removed not the second. Hope this still helps!
Arguments
property in Execute Process Task available on the Control Flow tab is expecting a value of data type DT_WSTR
and not DT_STR
.
Create an SSIS package in Business Intelligence Development Studio (BIDS) 2008 R2 and name it as SO_13177007.dtsx
. Create a package variable with the following information.
Name Scope Data Type Value
------ ------------ ---------- -----
IdVar SO_13177007 Int32 123
Drag and drop an Execute Process Task onto the Control Flow tab and name it as Pass arguments
Double-click the Execute Process Task to open the Execute Process Task Editor
. Click Expressions page and then click the Ellipsis button against the Expressions property to view the Property Expression Editor
.
On the Property Expression Editor, select the property Arguments
and click the Ellipsis button against the property to open the Expression Builder
.
On the Expression Builder, enter the following expression and click Evaluate Expression
. This expression tries to convert the integer value in the variable IdVar
to string data type.
(DT_STR, 10, 1252) @[User::IdVar]
Clicking Evaluate Expression will display the following error message because the Arguments property on Execute Process Task expects a value of data type DT_WSTR
.
To fix the issue, update the expression as shown below to convert the integer value to data type DT_WSTR
. Clicking Evaluate Expression will display the value in the Evaluated value text area.
(DT_WSTR, 10) @[User::IdVar]
To understand the differences between the data types DT_STR
and DT_WSTR
in SSIS, read the documentation Integration Services Data Types on MSDN. Here are the quotes from the documentation about these two string data types.
A null-terminated ANSI/MBCS character string with a maximum length of 8000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)
A null-terminated Unicode character string with a maximum length of 4000 characters. (If a column value contains additional null terminators, the string will be truncated at the occurrence of the first null.)
As per your question, I understand that you need to display some conditional data in Component 3 which is based on state of Component 5. Approach :
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Class Component3 extends React.Component {
state = {
someData = true
}
checkForData = (result) => {
this.setState({someData : result})
}
render() {
if(this.state.someData) {
return(
<Component5 hasData = {this.checkForData} />
//Other Data
);
}
else {
return(
//Other Data
);
}
}
}
export default Component3;
class Component5 extends React.Component {
state = {
dataValue = "XYZ"
}
checkForData = () => {
if(this.state.dataValue === "XYZ") {
this.props.hasData(true);
}
else {
this.props.hasData(false);
}
}
render() {
return(
<div onLoad = {this.checkForData}>
//Conditional Data
</div>
);
}
}
export default Component5;
_x000D_
typeof(callback) == "function"
You would want to use a set
instead of a list
.
To expand on the above and make a quick reference:
ALTER USER username WITH SUPERUSER;
ALTER USER username WITH NOSUPERUSER;
ALTER USER username CREATEDB;
You can also use CREATEROLE
and CREATEUSER
to allow a user privileges without making them a superuser.
You can define the default value from the 'data' attribute. This is part of the Abstract "field" type (http://symfony.com/doc/2.0/reference/forms/types/field.html)
$form = $this->createFormBuilder()
->add('status', 'choice', array(
'choices' => array(
0 => 'Published',
1 => 'Draft'
),
'data' => 1
))
->getForm();
In this example, 'Draft' would be set as the default selected value.
You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important
.
#zoomTarget .slikezamenjanje img {
max-height: auto;
padding-right: 0px;
}
I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.
For example, all CSS height
and width
attributes default to auto
.
You can use regexp or strcmp to eliminate .
and ..
Or you could use the isdir
field if you only want files in the directory, not folders.
list=dir(pwd); %get info of files/folders in current directory
isfile=~[list.isdir]; %determine index of files vs folders
filenames={list(isfile).name}; %create cell array of file names
or combine the last two lines:
filenames={list(~[list.isdir]).name};
For a list of folders in the directory excluding . and ..
dirnames={list([list.isdir]).name};
dirnames=dirnames(~(strcmp('.',dirnames)|strcmp('..',dirnames)));
From this point, you should be able to throw the code in a nested for loop, and continue searching each subfolder until your dirnames returns an empty cell for each subdirectory.
Answers here are a bit outdated. Though the code remains the same there are some changes in the behavior.
public class MyListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
TextView footerView = (TextView) ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_view, null, false);
getListView().addFooterView(footerView);
setListAdapter(new ArrayAdapter<String>(this, getResources().getStringArray(R.array.news)));
}
}
Info about addFooterView()
method
Add a fixed view to appear at the bottom of the list. If
addFooterView()
is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want.
Most of the answers above stress very important point -
addFooterView()
must be called before callingsetAdapter()
.This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.
From Kitkat this has changed.
Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.
First make sure the PHP files themselves are UTF-8 encoded.
The meta tag is ignored by some browser. If you only use ASCII-characters, it doesn't matter anyway.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
header('Content-Type: text/html; charset=utf-8');
Like @zane-hooper, I've had a similar problem on NFS. On parallel / distributed filesystems the lag between you creating a file on one machine and the other machine "seeing" it can be very large, so I could wait up to a full minute after the creation of the file before the while loop exits (and there also is an aftereffect of it "seeing" an already deleted file).
This creates the illusion that the script "doesn't work", while in fact it is the filesystem that is dropping the ball.
This took me a while to figure out, hope it saves somebody some time.
PS This also causes an annoying number of "Stale file handler" errors.
Upping the directive in the virtualhost for KeepAliveTimeout to 60 solved this for me.
The above works but this does not. Note the ON DELETE CASCADE
CREATE DATABASE t;
USE t;
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT NULL,
parent_id INT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;
INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)
You cannot change the img src using css. You can use the following pure css solution though. HTML:
<div id="asks"></div>
CSS:
#asks {
width: 100px;
height: 100px;
background-image: url('http://dummyimage.com/100x100/0000/fff');
}
#asks:hover {
background-image: url('http://dummyimage.com/100x100/eb00eb/fff');
}
Or, if you don't want to use a div with a background image, you can use a javascript/jQuery solution. Html:
<img id="asks" src="http://dummyimage.com/100x100/000/fff" />
jQuery:
$('#asks')
.mouseenter(function(){$('#asks').attr('src', 'http://dummyimage.com/100x100/eb00eb/fff');})
.mouseleave(function(){$('#asks').attr('src', 'http://dummyimage.com/100x100/000/fff');});
By looking at the call stack we can get the filepath of each script being executed, the two most useful will probably either be the currently executing script, or the first script to be sourced (entry).
script.dir.executing = (function() return( if(length(sys.parents())==1) getwd() else dirname( Filter(is.character,lapply(rev(sys.frames()),function(x) x$ofile))[[1]] ) ))()
script.dir.entry = (function() return( if(length(sys.parents())==1) getwd() else dirname(sys.frame(1)$ofile) ))()
In Addition to the suggestions, I would also suggest annotating your Repository interface with @Repository.
The Spring IOC may not detect this as a repository and thus be unable to detect the entity and its corresponding property.
Been using this in production for some time now without any complaints (May take some tweaking to look right on your site.. for instance, subtracting the width of a sidebar, etc)
$(window).bind('resize', function() {
$("#jqgrid").setGridWidth($(window).width());
}).trigger('resize');
Compare getApplication()
and getApplicationContext()
.
getApplication
returns an Application
object which will allow you to manage your global application state and respond to some device situations such as onLowMemory()
and onConfigurationChanged()
.
getApplicationContext
returns the global application context - the difference from other contexts is that for example, an activity context may be destroyed (or otherwise made unavailable) by Android when your activity ends. The Application context remains available all the while your Application object exists (which is not tied to a specific Activity
) so you can use this for things like Notifications that require a context that will be available for longer periods and independent of transient UI objects.
I guess it depends on what your code is doing whether these may or may not be the same - though in normal use, I'd expect them to be different.
Try this,
1. If you want to skip a particular iteration, use continue.
2. If you want to break out of the immediate loop use break
3 If there are 2 loop, outer and inner.... and you want to break out of both the loop from
the inner loop, use break with label.
eg:
continue
for(int i=0 ; i<5 ; i++){
if (i==2){
continue;
}
}
eg:
break
for(int i=0 ; i<5 ; i++){
if (i==2){
break;
}
}
eg:
break with label
lab1: for(int j=0 ; j<5 ; j++){
for(int i=0 ; i<5 ; i++){
if (i==2){
break lab1;
}
}
}
Maybe worth looking at QRGen, which is built on top of ZXing and supports UTF-8 with this kind of syntax:
// if using special characters don't forget to supply the encoding
VCard johnSpecial = new VCard("Jöhn D?e")
.setAdress("ëåäö? Sträät 1, 1234 Döestüwn");
QRCode.from(johnSpecial).withCharset("UTF-8").file();
Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.
IF NOT EXISTS (SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = 'newSchemaName' )
BEGIN
EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END
To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.
instancelist = [ MyClass() for i in range(29)]
and then access the instances through the index of the list.
instancelist[5].attr1 = 'whamma'
You also need add these lines in PostgreSQL and restart the server:
log_directory = 'pg_log'
log_filename = 'postgresql-dateformat.log'
log_statement = 'all'
logging_collector = on
To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the Paramiko library, you would do something like this:
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on).
You want the path.join() function from os.path.
>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'
This builds your path with os.sep (instead of the less portable '/'
) and does it more efficiently (in general) than using +
.
However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:
start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
os.makedirs (final_path)
All you need is a bit of improved markup. Wrap the second within the first and it will render under.
<div id="wrapper">
<div id="first">
Here comes the first content
<div id="second">I will render below the first content</div>
</div>
</div>
using system ping command to ping a list of hosts:
import re
from subprocess import Popen, PIPE
from threading import Thread
class Pinger(object):
def __init__(self, hosts):
for host in hosts:
pa = PingAgent(host)
pa.start()
class PingAgent(Thread):
def __init__(self, host):
Thread.__init__(self)
self.host = host
def run(self):
p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
m = re.search('Average = (.*)ms', p.stdout.read())
if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
else: print 'Error: Invalid Response -', self.host
if __name__ == '__main__':
hosts = [
'www.pylot.org',
'www.goldb.org',
'www.google.com',
'www.yahoo.com',
'www.techcrunch.com',
'www.this_one_wont_work.com'
]
Pinger(hosts)
I had similar problem while using Silverlight web project...
I got resolved issue by setting startup page (In silverlight .aspx is the startup page).
In project browser right click your startup page and set it.!
No additional view is required. https://docs.djangoproject.com/en/3.0/ref/views/
Just put the error files in the root of templates directory
And it should use your error page when debug is False
Load your "base" environment -- as OP's py34
-- when you load your terminal/shell.
If you use Bash, put the line:
conda activate py34
in your .bash_profile
(or .bashrc
):
$ echo 'conda activate py34' >> ~/.bash_profile
Every time you run a new terminal, conda environment py34
will be loaded.
import time
int(time.time())
Output:
1521462189
There are several problems with your code:
WordList
is not defined anywhere. You should define it before you use it.#include <string>
before you can use the string class and iostream before you use cout
or endl
.string
, cout
and endl
live in the std
namespace, so you can not access them without prefixing them with std::
unless you use the using
directive to bring them into scope first.So here is a solution for both your requests in the manner you originally asked for. It will give human readability filesize without the filesize limits everyone is experiencing. Compatible with Win Vista or newer. XP only available if Robocopy is installed. Just drop a folder on this batch file or use the better method mentioned below.
@echo off
setlocal enabledelayedexpansion
set "vSearch=Files :"
For %%i in (%*) do (
set "vSearch=Files :"
For /l %%M in (1,1,2) do (
for /f "usebackq tokens=3,4 delims= " %%A in (`Robocopy "%%i" "%%i" /E /L /NP /NDL /NFL ^| find "!vSearch!"`) do (
if /i "%%M"=="1" (
set "filecount=%%A"
set "vSearch=Bytes :"
) else (
set "foldersize=%%A%%B"
)
)
)
echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!
REM remove the word "REM" from line below to output to txt file
REM echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!>>Folder_FileCountandSize.txt
)
pause
To be able to use this batch file conveniently put it in your SendTo folder. This will allow you to right click a folder or selection of folders, click on the SendTo option, and then select this batch file.
To find the SendTo folder on your computer simplest way is to open up cmd then copy in this line as is.
explorer C:\Users\%username%\AppData\Roaming\Microsoft\Windows\SendTo
(No root required) There is one best, easy and with UI method for Android Studio
IntelliJ and Android Studio plugin created to quickly connect your Android device over WiFi to install, run and debug your applications without a USB connected. Press one button and forget about your USB cable.
just install plugin Android WiFi ADB
Download and install Android WiFi ADB directly from
Intellij / Android Studio: Preferences/Settings->Plugins->Browse Repositories
.
Remember! for first time to initialize the device you must have to connect using usb
Alternatively, you can download the plugin from the JetBrains plugin site and install it manually in: Preferences/Settings->Plugins->Install plugin from disk.
You can connect and manage your devices easily....... for more information read here https://github.com/pedrovgs/AndroidWiFiADB
Check if it is integer parseable
public boolean isInteger(String string) {
try {
Integer.valueOf(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
or use Scanner
Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
Double doubleValue = scanner.nextDouble();
} else {
String stringValue = scanner.next();
}
}
or use Regular Expression like
private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");
public boolean isDouble(String string) {
return doublePattern.matcher(string).matches();
}
Deparse tells us this is what is being executed:
$find = 'start (.*) end';
$replace = "foo \cA bar";
$var = 'start middle end';
$var =~ s/$find/$replace/;
However,
/$find/foo \1 bar/
Is interpreted as :
$var =~ s/$find/foo $1 bar/;
Unfortunately it appears there is no easy way to do this.
You can do it with a string eval, but thats dangerous.
The most sane solution that works for me was this:
$find = "start (.*) end";
$replace = 'foo \1 bar';
$var = "start middle end";
sub repl {
my $find = shift;
my $replace = shift;
my $var = shift;
# Capture first
my @items = ( $var =~ $find );
$var =~ s/$find/$replace/;
for( reverse 0 .. $#items ){
my $n = $_ + 1;
# Many More Rules can go here, ie: \g matchers and \{ }
$var =~ s/\\$n/${items[$_]}/g ;
$var =~ s/\$$n/${items[$_]}/g ;
}
return $var;
}
print repl $find, $replace, $var;
As I said in my answer, I avoid evals for a reason.
$find="start (.*) end";
$replace='do{ print "I am a dirty little hacker" while 1; "foo $1 bar" }';
$var = "start middle end";
$var =~ s/$find/$replace/ee;
print "var: $var\n";
this code does exactly what you think it does.
If your substitution string is in a web application, you just opened the door to arbitrary code execution.
Good Job.
Also, it WON'T work with taints turned on for this very reason.
$find="start (.*) end";
$replace='"' . $ARGV[0] . '"';
$var = "start middle end";
$var =~ s/$find/$replace/ee;
print "var: $var\n"
$ perl /tmp/re.pl 'foo $1 bar'
var: foo middle bar
$ perl -T /tmp/re.pl 'foo $1 bar'
Insecure dependency in eval while running with -T switch at /tmp/re.pl line 10.
However, the more careful technique is sane, safe, secure, and doesn't fail taint. ( Be assured tho, the string it emits is still tainted, so you don't lose any security. )
or you can even try executing onClick this (more violent solution):
window.location.assign("/sample");
I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).
I went with a list.Sort solution something like this.
var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
OrderId = o.id,
OrderDate = o.orderDate,
OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
});
data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));
Try Base64 encoding/decoding your binary data. Also look into CDATA sections
I've found this works:
Rows(CStr(iVar1) & ":" & CStr(iVar2)).Select
i think right now is Firefox 3.6.2, but when internet explorer 9 launched, it will support HTML5
Hello i now it past a lot of time from the original post but i got a similar problem and i want to share.
I got a datetime field with this format YYYY-MM-DD hh:mm:ss, and i want to access a whole day, so here is my solution.
The function DATE(), in MySQL: Extract the date part of a date or datetime expression.
SELECT * FROM `your_table` WHERE DATE(`your_datatime_field`)='2017-10-09'
with this i get all the row register in this day.
I hope its help anyone.
If you are like me using ubuntu 10.10 & cant find the lastest version which is now
this is where you can get it http://www.ubuntuupdates.org/package/brightbox_ruby_ng_experimental/maverick/main/base/ruby1.9.3
or download the *.deb file :)
& remember that it wont alter you old version of ruby
Find the <SHA#>
for the commit you want to go. You can find it in github or by typing git log
or git reflog show
at the command line and then do
git reset --hard <SHA#>
If you want to reload the page , you can easily go to your component then do :
location.reload();
What you've written actually almost works (it would work if all the variables were numbers), but it's not an idiomatic way at all.
(…)
parentheses indicate a subshell. What's inside them isn't an expression like in many other languages. It's a list of commands (just like outside parentheses). These commands are executed in a separate subprocess, so any redirection, assignment, etc. performed inside the parentheses has no effect outside the parentheses.
$(…)
is a command substitution: there is a command inside the parentheses, and the output from the command is used as part of the command line (after extra expansions unless the substitution is between double quotes, but that's another story).{ … }
braces are like parentheses in that they group commands, but they only influence parsing, not grouping. The program x=2; { x=4; }; echo $x
prints 4, whereas x=2; (x=4); echo $x
prints 2. (Also braces require spaces around them and a semicolon before closing, whereas parentheses don't. That's just a syntax quirk.)
${VAR}
is a parameter expansion, expanding to the value of a variable, with possible extra transformations.((…))
double parentheses surround an arithmetic instruction, that is, a computation on integers, with a syntax resembling other programming languages. This syntax is mostly used for assignments and in conditionals.
$((…))
, which expand to the integer value of the expression.[[ … ]]
double brackets surround conditional expressions. Conditional expressions are mostly built on operators such as -n $variable
to test if a variable is empty and -e $file
to test if a file exists. There are also string equality operators: "$string1" == "$string2"
(beware that the right-hand side is a pattern, e.g. [[ $foo == a* ]]
tests if $foo
starts with a
while [[ $foo == "a*" ]]
tests if $foo
is exactly a*
), and the familiar !
, &&
and ||
operators for negation, conjunction and disjunction as well as parentheses for grouping. Note that you need a space around each operator (e.g. [[ "$x" == "$y" ]]
, not [[ "$x"=="$y" ]]
;
both inside and outside the brackets (e.g. [[ -n $foo ]]
, not [[-n $foo]]
[ … ]
single brackets are an alternate form of conditional expressions with more quirks (but older and more portable). Don't write any for now; start worrying about them when you find scripts that contain them.This is the idiomatic way to write your test in bash:
if [[ $varA == 1 && ($varB == "t1" || $varC == "t2") ]]; then
If you need portability to other shells, this would be the way (note the additional quoting and the separate sets of brackets around each individual test, and the use of the traditional =
operator rather than the ksh/bash/zsh ==
variant):
if [ "$varA" = 1 ] && { [ "$varB" = "t1" ] || [ "$varC" = "t2" ]; }; then
If you want to do it from the command line and not built into the script itself, use:
.\myscript.ps1 | Out-File c:\output.csv
If you only want non-negative integers, try:
^\d+$
Should the benchmark measure time/iteration or iterations/time, and why?
It depends on what you are trying to test.
If you are interested in latency, use time/iteration and if you are interested in throughput, use iterations/time.
I've been doing it this way:
class Event(list):
"""Event subscription.
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
Example Usage:
>>> def f(x):
... print 'f(%s)' % x
>>> def g(x):
... print 'g(%s)' % x
>>> e = Event()
>>> e()
>>> e.append(f)
>>> e(123)
f(123)
>>> e.remove(f)
>>> e()
>>> e += (f, g)
>>> e(10)
f(10)
g(10)
>>> del e[0]
>>> e(2)
g(2)
"""
def __call__(self, *args, **kwargs):
for f in self:
f(*args, **kwargs)
def __repr__(self):
return "Event(%s)" % list.__repr__(self)
However, like with everything else I've seen, there is no auto generated pydoc for this, and no signatures, which really sucks.
If you have an async method called " RefreshList " then, you can call that async method from a non-async method like below.
Task.Run(async () => { await RefreshList(); });
You can use
alter table <tblname> drop column <colname>
install vim from online, and then you can just do: vim "filename" to edit that file
public class HtmlTextView extends AppCompatTextView {
public HtmlTextView(Context context) {
super(context);
init();
}
private void init(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setText(Html.fromHtml(getText().toString(), Html.FROM_HTML_MODE_COMPACT));
} else {
setText(Html.fromHtml(getText().toString()));
}
}
}
update of answer above
The caller-saved / callee-saved terminology is based on a pretty braindead inefficient model of programming where callers actually do save/restore all the call-clobbered registers (instead of keeping long-term-useful values elsewhere), and callees actually do save/restore all the call-preserved registers (instead of just not using some or any of them).
Or you have to understand that "caller-saved" means "saved somehow if you want the value later".
In reality, efficient code lets values get destroyed when they're no longer needed. Compilers typically make functions that save a few call-preserved registers at the start of a function (and restore them at the end). Inside the function, they use those regs for values that need to survive across function calls.
I prefer "call-preserved" vs. "call-clobbered", which are unambiguous and self-describing once you've heard of the basic concept, and don't require any serious mental gymnastics to think about from the caller's perspective or the callee's perspective. (Both terms are from the same perspective).
Plus, these terms differ by more than one letter.
The terms volatile / non-volatile are pretty good, by analogy with storage which loses its value on power-loss or not, (like DRAM vs. Flash). But the C volatile
keyword has a totally different technical meaning, so that's a downside to "(non)-volatile" when describing C calling conventions.
From the callee's perspective, your function can freely overwrite (aka clobber) these registers without saving/restoring.
From a caller's perspective, call foo
destroys (aka clobbers) all the call-clobbered registers, or at least you have to assume it does.
You can write private helper functions that have a custom calling convention, e.g. you know they don't modify a certain register. But if all you know (or want to assume or depend on) is that the target function follows the normal calling convention, then you have to treat a function call as if it does destroy all the call-clobbered registers. That's literally what the name come from: a call clobbers those registers.
Some compilers that do inter-procedural optimization can also create internal-use-only definitions of functions that don't follow the ABI, using a custom calling convention.
From a callee's perspective, these registers can't be modified unless you save the original value somewhere so you can restore it before returning. Or for registers like the stack pointer (which is almost always call-preserved), you can subtract a known offset and add it back again before returning, instead of actually saving the old value anywhere. i.e. you can restore it by dead reckoning, unless you allocate a runtime-variable amount of stack space. Then typically you restore the stack pointer from another register.
A function that can benefit from using a lot of registers can save/restore some call-preserved registers just so it can use them as more temporaries, even if it doesn't make any function calls. Normally you'd only do this after running out of call-clobbered registers to use, because save/restore typically costs a push/pop at the start/end of the function. (Or if your function has multiple exit paths, a pop
in each of them.)
The name "caller-saved" is misleading: you don't have to specially save/restore them. Normally you arrange your code to have values that need to survive a function call in call-preserved registers, or somewhere on the stack, or somewhere else that you can reload from. It's normal to let a call
destroy temporary values.
See for example What registers are preserved through a linux x86-64 function call for the x86-64 System V ABI.
Also, arg-passing registers are always call-clobbered in all function-calling conventions I'm aware of. See Are rdi and rsi caller saved or callee saved registers?
But system-call calling conventions typically make all the registers except the return value call-preserved. (Usually including even condition-codes / flags.) See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64
Here's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.
>>> a = [1, 2, 3, -4, 5]
>>> def zero_if_negative(x):
... if x < 0:
... return 0
... return x
...
>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]
>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]
O(1) - Deleting an element from a doubly linked list. e.g.
typedef struct _node {
struct _node *next;
struct _node *prev;
int data;
} node;
void delete(node **head, node *to_delete)
{
.
.
.
}
The final
keyword has several usages in Java. It corresponds to both the sealed
and readonly
keywords in C#, depending on the context in which it is used.
To prevent subclassing (inheritance from the defined class):
Java
public final class MyFinalClass {...}
C#
public sealed class MyFinalClass {...}
Prevent overriding of a virtual
method.
Java
public class MyClass
{
public final void myFinalMethod() {...}
}
C#
public class MyClass : MyBaseClass
{
public sealed override void MyFinalMethod() {...}
}
As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as virtual
, whereas C# marks them as sealed
. Hence, you only need to use the sealed
keyword in C# if you want to stop further overriding of a method that has been explicitly marked virtual
in the base class.
To only allow a variable to be assigned once:
Java
public final double pi = 3.14; // essentially a constant
C#
public readonly double pi = 3.14; // essentially a constant
As a side note, the effect of the readonly
keyword differs from that of the const
keyword in that the readonly
expression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.
Please take a look at ack, which is designed for exactly these situations. Your example of
grep -ircl --exclude=*.{png,jpg} "foo=" *
is done with ack as
ack -icl "foo="
because ack never looks in binary files by default, and -r is on by default. And if you want only CPP and H files, then just do
ack -icl --cpp "foo="
Pyflakes does what you ask, it just checks the syntax. From the docs:
Pyflakes makes a simple promise: it will never complain about style, and it will try very, very hard to never emit false positives.
Pyflakes is also faster than Pylint or Pychecker. This is largely because Pyflakes only examines the syntax tree of each file individually.
To install and use:
$ pip install pyflakes
$ pyflakes yourPyFile.py
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
$(".classForHoverEffect").mouseover(function(){
$('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});
the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,
$(".classForHoverEffect").mouseout(function(){
$('#DivToShow').fadeOut('slow');
});
If you DIV is already positioned, you can simply use
$('.classForHoverEffect').hover(function(){
$('#DivToShow').fadeIn('slow');
});
Also, keep in mind, your DIV style needs to be set to display:none;
in order for it to fadeIn or show.
string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
newAlpha = alpha.Insert(i, "-");
alpha = newAlpha;
}
If the text you're putting in the TextView
is short, it will not automatically expand to four lines. If you want the TextView
to always have four lines regardless of the length of the text in it, set the android:lines
attribute:
<TextView
android:id="@+id/address1"
android:gravity="left"
android:layout_height="fill_parent"
android:layout_width="wrap_content"
android:maxLines="4"
android:lines="4"
android:text="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."></TextView>
You can do this with TableRow, see below code
<TableRow >
<TextView
android:id="@+id/tv_description_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="8dp"
android:text="@string/rating_review"
android:textColor="@color/black"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:maxLines="4"`enter code here`
android:padding="8dp"
android:text="The food test was very good."
android:textColor="@color/black"
android:textColorHint="@color/hint_text_color" />
</TableRow>
this is a sample case, which will make sense I believe!
node('master'){
stage('stage1'){
def commit = sh (returnStdout: true, script: '''echo hi
echo bye | grep -o "e"
date
echo lol''').split()
echo "${commit[-1]} "
}
}
Create your Datafile like this:
# X Y
10000.0 0.01
100000.0 0.05
1000000.0 0.45
And plot it with
$ gnuplot -p -e "plot 'filename.dat'"
There is a good tutorial: http://www.gnuplotting.org/introduction/plotting-data/
//This function allows remove even array from array
var removeFromArr = function(arr, elem) {
var i, len = arr.length, new_arr = [],
sort_fn = function (a, b) { return a - b; };
for (i = 0; i < len; i += 1) {
if (typeof elem === 'object' && typeof arr[i] === 'object') {
if (arr[i].toString() === elem.toString()) {
continue;
} else {
if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
continue;
}
}
}
if (arr[i] !== elem) {
new_arr.push(arr[i]);
}
}
return new_arr;
}
Example of using
var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]
var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]
I also had same problem and I fixed it by using right proxy. Please double check your proxy settings if you are using proxy network.
Hope this will help you -
Try setting the charset on your Content-Type:
httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );
I like jjvainio's answer. As Zan Lnyx says, it uses the local routing table to find the IP address of the ethernet interface that would be used for a connection to a specific external host. By using a connected UDP socket, you can get the information without actually sending any packets. The approach requires that you choose a specific external host. Most of the time, any well-known public IP should do the trick. I like Google's public DNS server address 8.8.8.8 for this purpose, but there may be times you'd want to choose a different external host IP. Here is some code that illustrates the full approach.
void GetPrimaryIp(char* buffer, size_t buflen)
{
assert(buflen >= 16);
int sock = socket(AF_INET, SOCK_DGRAM, 0);
assert(sock != -1);
const char* kGoogleDnsIp = "8.8.8.8";
uint16_t kDnsPort = 53;
struct sockaddr_in serv;
memset(&serv, 0, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);
serv.sin_port = htons(kDnsPort);
int err = connect(sock, (const sockaddr*) &serv, sizeof(serv));
assert(err != -1);
sockaddr_in name;
socklen_t namelen = sizeof(name);
err = getsockname(sock, (sockaddr*) &name, &namelen);
assert(err != -1);
const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, buflen);
assert(p);
close(sock);
}
Time package in Golang has some methods that might be worth looking.
func (Time) Format
func (t Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time,
Mon Jan 2 15:04:05 -0700 MST 2006 would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value. Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard and convenient representations of the reference time. For more information about the formats and the definition of the reference time, see the documentation for ANSIC and the other constants defined by this package.
Source (http://golang.org/pkg/time/#Time.Format)
I also found an example of defining the layout (http://golang.org/src/pkg/time/example_test.go)
func ExampleTime_Format() {
// layout shows by example how the reference time should be represented.
const layout = "Jan 2, 2006 at 3:04pm (MST)"
t := time.Date(2009, time.November, 10, 15, 0, 0, 0, time.Local)
fmt.Println(t.Format(layout))
fmt.Println(t.UTC().Format(layout))
// Output:
// Nov 10, 2009 at 3:00pm (PST)
// Nov 10, 2009 at 11:00pm (UTC)
}
Because recursion is always the answer.
function getPosition(input, search, nth, curr, cnt) {
curr = curr || 0;
cnt = cnt || 0;
var index = input.indexOf(search);
if (curr === nth) {
if (~index) {
return cnt;
}
else {
return -1;
}
}
else {
if (~index) {
return getPosition(input.slice(index + search.length),
search,
nth,
++curr,
cnt + index + search.length);
}
else {
return -1;
}
}
}
The following code writes python lists into columns in csv
import csv
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j']
d = [list1, list2]
export_data = zip_longest(*d, fillvalue = '')
with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile)
wr.writerow(("List1", "List2"))
wr.writerows(export_data)
myfile.close()
The output looks like this
Without the question if it is proper or not, you can add PCH file manually:
Add new PCH file to the project: New file > Other > PCH file.
At the Target's Build Settings option, set the value of Prefix Header to your PCH file name, with the project name as prefix (i.e. for project named TestProject
and PCH file named MyPrefixHeaderFile
, add the value TestProject/MyPrefixHeaderFile.pch
to the plist).
TIP: You can use things like $(SRCROOT)
or $(PROJECT_DIR)
to get to the path of where you put the .pch
in the project.
At the Target's Build Settings option, set the value of Precompile Prefix Header to YES
.
When you already have an older version of NumPy, use this:
pip install numpy --upgrade
If it still doesn't work, try:
pip install numpy --upgrade --ignore-installed
W3Schools is your friend: http://www.w3schools.com/php/func_filesystem_fgets.asp
And here: http://php.net/manual/en/function.fopen.php has more info on fopen including what the modes are.
What W3Schools says:
<?php
$file = fopen("test.txt","r");
while(! feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
fopen opens the file (in this case test.txt with mode 'r' which means read-only and places the pointer at the beginning of the file)
The while loop tests to check if it's at the end of file (feof) and while it isn't it calls fgets which gets the current line where the pointer is.
Continues doing this until it is the end of file, and then closes the file.
Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.
git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67
Then, abort the rebase again.
Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet
extends java.util.HashSet
. The method add()
is overridden in LinkedHashSet
. If you have a variable that is of type HashSet
, and you call its add()
method, it will call the appropriate implementation of add()
, based on whether it is a HashSet
or a LinkedHashSet
. This is called polymorphism.
Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println()
is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.
All the solutions given in this thread don't mention an existing - and native - way to solve this problem without reordering DOM and/or using event preventing tricks. But there's a good reason: this way is proprietary - and available on MS web platform only. Quoting MSDN:
-ms-scroll-chaining property - specifies the scrolling behavior that occurs when a user hits the scroll limit during a manipulation. Property values:
chained - Initial value. The nearest scrollable parent element begins scrolling when the user hits a scroll limit during a manipulation. No bounce effect is shown.
none - A bounce effect is shown when the user hits a scroll limit during a manipulation.
Granted, this property is supported on IE10+/Edge only. Still, here's a telling quote:
To give you a sense of how popular preventing scroll chaining may be, according to my quick http-archive search "-ms-scroll-chaining: none" is used in 0.4% of top 300K pages despite being limited in functionality and only supported on IE/Edge.
And now good news, everyone! Starting from Chrome 63, we finally have a native cure for Blink-based platforms too - and that's both Chrome (obviously) and Android WebView (soon).
Quoting the introducing article:
The overscroll-behavior property is a new CSS feature that controls the behavior of what happens when you over-scroll a container (including the page itself). You can use it to cancel scroll chaining, disable/customize the pull-to-refresh action, disable rubberbanding effects on iOS (when Safari implements overscroll-behavior), and more.[...]
The property takes three possible values:
auto - Default. Scrolls that originate on the element may propagate to ancestor elements.
contain - prevents scroll chaining. Scrolls do not propagate to ancestors but local effects within the node are shown. For example, the overscroll glow effect on Android or the rubberbanding effect on iOS which notifies the user when they've hit a scroll boundary. Note: using overscroll-behavior: contain on the html element prevents overscroll navigation actions.
none - same as contain but it also prevents overscroll effects within the node itself (e.g. Android overscroll glow or iOS rubberbanding).
[...] The best part is that using overscroll-behavior does not adversely affect page performance like the hacks mentioned in the intro!
Here's this feature in action. And here's corresponding CSS Module document.
UPDATE: Firefox, since version 59, has joined the club, and MS Edge is expected to implement this feature in version 18. Here's the corresponding caniusage.
None of the solutions above worked for me straight away. So I followed these steps:
pom.xml:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Go to Project Properties
> Java Build Path
, then remove the JRE
System Library pointing to JRE1.5
.
Force updated the project.
Let's split the problem into two parts:
n
in the range 0 through (max-min).The first part is obviously the hardest. Let's assume that the return value of rand() is perfectly uniform. Using modulo will add bias
to the first (RAND_MAX + 1) % (max-min+1)
numbers. So if we could magically change RAND_MAX
to RAND_MAX - (RAND_MAX + 1) % (max-min+1)
, there would no longer be any bias.
It turns out that we can use this intuition if we are willing to allow pseudo-nondeterminism into the running time of our algorithm. Whenever rand() returns a number which is too large, we simply ask for another random number until we get one which is small enough.
The running time is now geometrically distributed, with expected value 1/p
where p
is the probability of getting a small enough number on the first try. Since RAND_MAX - (RAND_MAX + 1) % (max-min+1)
is always less than (RAND_MAX + 1) / 2
,
we know that p > 1/2
, so the expected number of iterations will always be less than two
for any range. It should be possible to generate tens of millions of random numbers in less than a second on a standard CPU with this technique.
EDIT:
Although the above is technically correct, DSimon's answer is probably more useful in practice. You shouldn't implement this stuff yourself. I have seen a lot of implementations of rejection sampling and it is often very difficult to see if it's correct or not.
If you have your dates in DateTime variables, they don't have a format.
You can use the Date
property to return a DateTime value with the time portion set to midnight. So, if you have:
DateTime dt1 = DateTime.Parse("07/12/2011");
DateTime dt2 = DateTime.Now;
if(dt1.Date > dt2.Date)
{
//It's a later date
}
else
{
//It's an earlier or equal date
}
You want to grab the value of the first option in the select element.
$("*[id$='" + originalId + "']").val($("*[id$='" + originalId + "'] option:first").attr('value'));
There are multiple ways to get a string representation of a type. Switches can also be used with user types:
var user interface{}
user = User{name: "Eugene"}
// .(type) can only be used inside a switch
switch v := user.(type) {
case int:
// Built-in types are possible (int, float64, string, etc.)
fmt.Printf("Integer: %v", v)
case User:
// User defined types work as well
fmt.Printf("It's a user: %s\n", user.(User).name)
}
// You can use reflection to get *reflect.rtype
userType := reflect.TypeOf(user)
fmt.Printf("%+v\n", userType)
// You can also use %T to get a string value
fmt.Printf("%T", user)
// You can even get it into a string
userTypeAsString := fmt.Sprintf("%T", user)
if userTypeAsString == "main.User" {
fmt.Printf("\nIt's definitely a user")
}
Link to a playground: https://play.golang.org/p/VDeNDUd9uK6
Worth noting that ||
will also return true
if BOTH A
and B
are true
.
In JavaScript, if you're looking for A
or B
, but not both, you'll need to do something similar to:
if( (A && !B) || (B && !A) ) { ... }
Problem
The upstream server is timing out and I don't what is happening.
Where to Look first before increasing read or write timeout if your server is connecting to a database
Server is connecting to a database and that connection is working just fine and within sane response time, and its not the one causing this delay in server response time.
make sure that connection state is not causing a cascading failure on your upstream
Then you can move to look at the read and write timeout configurations of the server and proxy.
you can also check this link
SELECT * FROM master_question
WHERE 1 ORDER BY question_id
ASC LIMIT 20
In my case just run the command and worked like charm.
php artisan route:clear
Hi I found the easiest way to do this.
Done!
No.The image will be loaded as usual and will still use the user’s bandwidth if you are considering the mobile phone user bandwidth saving.What u can do is to use media query and filter the devices that you want your image to be loaded.Your image must be set as a background image of a div,etc and NOT an tag since the the image tag will load the image regardless if the screen size and the media query set.
This code will help you, and it's fairly self-explanatory:
#include <stdio.h> /* Standard Library of Input and Output */
#include <complex.h> /* Standard Library of Complex Numbers */
int main() {
double complex z1 = 1.0 + 3.0 * I;
double complex z2 = 1.0 - 4.0 * I;
printf("Working with complex numbers:\n\v");
printf("Starting values: Z1 = %.2f + %.2fi\tZ2 = %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2));
double complex sum = z1 + z2;
printf("The sum: Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum));
double complex difference = z1 - z2;
printf("The difference: Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference));
double complex product = z1 * z2;
printf("The product: Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product));
double complex quotient = z1 / z2;
printf("The quotient: Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient));
double complex conjugate = conj(z1);
printf("The conjugate of Z1 = %.2f %+.2fi\n", creal(conjugate), cimag(conjugate));
return 0;
}
with:
creal(z1)
: get the real part (for float crealf(z1)
, for long double creall(z1)
)
cimag(z1)
: get the imaginary part (for float cimagf(z1)
, for long double cimagl(z1)
)
Another important point to remember when working with complex numbers is that functions like cos()
, exp()
and sqrt()
must be replaced with their complex forms, e.g. ccos()
, cexp()
, csqrt()
.
I'd install Tortoise Hg (a free GUI for Mercurial) and use that. You can then just right-click on a revision you might want to return to - with all the commit messages there in front of your eyes - and 'Revert all files'. Makes it intuitive and easy to roll backwards and forwards between versions of a fileset, which can be really useful if you are looking to establish when a problem first appeared.
<form name="registrationForm">_x000D_
<input type="range" name="ageInputName" id="ageInputId" value="24" min="1" max="10" onchange="getvalor(this.value);" oninput="ageOutputId.value = ageInputId.value">_x000D_
<input type="text" name="ageOutputName" id="ageOutputId"></input>_x000D_
</form>
_x000D_
Main thing to worry about is how would you notify the elevator that it needs to move up or down. and also if you are going to have a centralized class to control this behavior and how could you distribute the control.
It seems like it can be very simple or very complicated. If we don't take concurrency or the time for an elevator to get to one place, then it seems like it will be simple since we just need to check the states of elevator, like is it moving up or down, or standing still. But if we make Elevator implement Runnable, and constantly check and synchronize a queue (linkedList). A Controller class will assign which floor to go in the queue. When the queue is empty, the run() method will wait (queue.wait() ), when a floor is assigned to this elevator, it will call queue.notify() to wake up the run() method, and run() method will call goToFloor(queue.pop()). This will make the problem too complicated. I tried to write it on paper, but dont think it works. It seems like we don't really need to take concurrency or timing issue into account here, but we do need to somehow use a queue to distribute the control.
Any suggestion?
You only have to edit your profile file like this:
sudo su
vim ~/.profile
and put this at the end of the file:
export ANDROID_HOME=/home/(user name)/Android/Sdk
export PATH=$PATH:/tools
export PATH=$PATH:/platform-tools
Save and close the file and do:
cd ~
source .profile
now if you do:
echo $ANDROID_HOME
it should show you something like this:
/home/(user name)/Android/Sdk
<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>
or
$sidemenus = mysql_fetch_array($results);
then
<?php echo $sidemenu['mname']."<br />";?>
There are two ways:
It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...
First create HashMap.
HashMap> mapList = new HashMap>();
Get value from HashMap against your input key.
ArrayList arrayList = mapList.get(key);
Add value to arraylist.
arrayList.add(addvalue);
Then again put arraylist against that key value. mapList.put(key,arrayList);
It will work.....
Take a look at this article; under the heading "Methods provided at runtime":
Some accessors are created dynamically at runtime, such as certain ones used in CoreData's NSManagedObject class. If you want to declare and use properties for these cases, but want to avoid warnings about methods missing at compile time, you can use the @dynamic directive instead of @synthesize.
...
Using the @dynamic directive essentially tells the compiler "don't worry about it, a method is on the way."
The @synthesize
directive, on the other hand, generates the accessor methods for you at compile time (although as noted in the "Mixing Synthesized and Custom Accessors" section it is flexible and does not generate methods for you if either are implemented).
Your error is also shown when trying to access the sizeof()
of an non-initialized extern array:
extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'
Note that you would get an array size missing
error without the extern
keyword.
I had to do this recently as well for both Mac and Linux OS's and after browsing through many posts and trying many things out, in my particular opinion I never got to where I wanted to which is: a simple enough to understand solution using well known and standard commands with simple patterns, one liner, portable, expandable to add in more constraints. Then I tried to looked at it with a different perspective, that's when I realized i could do without the "one liner" option if a "2-liner" met the rest of my criteria. At the end I came up with this solution I like that works in both Ubuntu and Mac which i wanted to share with everyone:
insertLine=$(( $(grep -n "foo" sample.txt | cut -f1 -d: | head -1) + 1 ))
sed -i -e "$insertLine"' i\'$'\n''bar'$'\n' sample.txt
In first command, grep looks for line numbers containing "foo", cut/head selects 1st occurrence, and the arithmetic op increments that first occurrence line number by 1 since I want to insert after the occurrence. In second command, it's an in-place file edit, "i" for inserting: an ansi-c quoting new line, "bar", then another new line. The result is adding a new line containing "bar" after the "foo" line. Each of these 2 commands can be expanded to more complex operations and matching.
you can done this way also.
if (dateFormat(first, "yyyy-mm-dd") > dateFormat(second, "yyyy-mm-dd")) {
console.log("done");
}
OR
if (dateFormat(first, "mm-dd-yyyy") > dateFormat(second, "mm-dd-yyyy")) {
console.log("done");
}
i use following plugin for dateFormat()
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
// Passing date through Date applies Date.parse, if necessary
date = date ? new Date(date) : new Date;
if (isNaN(date)) throw SyntaxError("invalid date");
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};
Pivot table Excel2007- average to exclude zeros
=sum(XX:XX)/count if(XX:XX, ">0")
Invoice USD
Qty Rate(count) Value (sum) 300 0.000 000.000 1000 0.385 385.000
Average Rate Count should Exclude 0.000 rate
Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.
Quick fix:
helloWorld
inside the src
folder.helloWorld.java
file in that package. Just drag and drop on
the package. Error should disappear.Explanation:
Latest version of Eclipse required java11 or above. The module
feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules
When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java
file. If you select don't create
then module-info.java
will not create and your project will free from this issue.
Best practice is while crating project, after giving project name. Click on next
button instead of finish
. On next page at the bottom it ask for creation of module-info.java
file. Select or deselect as per need.
If selected: (by default) click on finish
button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.
If deselect: No issue
Just to add that from SQL Server 2008, there is a TIME datatype so from then on you can do:
SELECT CONVERT(TIME, GETDATE())
Might be useful for those that use SQL 2008+ and find this question.
In your Eclipse editor screen, try Control + Shift + R buttons.
you can do it like this
$.when(funtion1()).then(function(){
funtion2();
})
I have try the code from first answer, it not working but I have play around and this work for me
$('#vip').change(function(){
if ($(this).is(':checked')) {
alert('checked');
} else {
alert('uncheck');
}
});
Alternatively, if you just want to convert one particular row to uppercase, use the code below:
df[[1]] <- toupper(df[[1]])
Check your package version: npm -v [package-name]
Update it: npm update [-g] [package-name]
using -g or --global installs it as a global package.
merged = map(names(first), ~c(first[[.x]], second[[.x]])
merged = set_names(merged, names(first))
Using purrr. Also solves the problem of your lists not being in order.
In below Order
extrac Guid values from database functions:
#region GUID
public static Guid GGuid(SqlDataReader reader, string field)
{
try
{
return reader[field] == DBNull.Value ? Guid.Empty : (Guid)reader[field];
}
catch { return Guid.Empty; }
}
public static Guid GGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
return reader[ordinal] == DBNull.Value ? Guid.Empty : (Guid)reader[ordinal];
}
catch { return Guid.Empty; }
}
public static Guid? NGuid(SqlDataReader reader, string field)
{
try
{
if (reader[field] == DBNull.Value) return (Guid?)null; else return (Guid)reader[field];
}
catch { return (Guid?)null; }
}
public static Guid? NGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
if (reader[ordinal] == DBNull.Value) return (Guid?)null; else return (Guid)reader[ordinal];
}
catch { return (Guid?)null; }
}
#endregion
On Windows, you can use WMI (home page, cheeseshop):
def memory():
import os
from wmi import WMI
w = WMI('.')
result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid())
return int(result[0].WorkingSet)
On Linux (from python cookbook http://code.activestate.com/recipes/286222/:
import os
_proc_status = '/proc/%d/status' % os.getpid()
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
'KB': 1024.0, 'MB': 1024.0*1024.0}
def _VmB(VmKey):
'''Private.
'''
global _proc_status, _scale
# get pseudo file /proc/<pid>/status
try:
t = open(_proc_status)
v = t.read()
t.close()
except:
return 0.0 # non-Linux?
# get VmKey line e.g. 'VmRSS: 9999 kB\n ...'
i = v.index(VmKey)
v = v[i:].split(None, 3) # whitespace
if len(v) < 3:
return 0.0 # invalid format?
# convert Vm value to bytes
return float(v[1]) * _scale[v[2]]
def memory(since=0.0):
'''Return memory usage in bytes.
'''
return _VmB('VmSize:') - since
def resident(since=0.0):
'''Return resident memory usage in bytes.
'''
return _VmB('VmRSS:') - since
def stacksize(since=0.0):
'''Return stack size in bytes.
'''
return _VmB('VmStk:') - since
If you have the generated SSH key for your project from GitLab you can add it to your keychain in OS X via terminal.
ssh-add -K <ssh_generated_key_file.txt>
Once executed you will be asked for the passphrase that you entered when creating the SSH key.
Once the SSH key is in the keychain you can paste the URL from GitLab into Sourcetree like you normally would to clone the project.
Although Apple recommends tel:
in their docs for Mobile Safari, currently (iOS 4.3) it accepts callto:
just the same. So I recommend using callto:
on a generic web site as it works with both Skype and iPhone and I expect it will work on Android phones, too.
This is still a matter of deciding what you want your web page to offer. On my websites I provide both tel:
and callto:
links (the latter labeled as being for Skype) since Desktop browsers on Mac don't do anything with tel:
links while mobile Android doesn't do anything with callto:
links. Even Google Chrome with the Google Talk plugin does not respond to tel:
links. Still, I prefer offering both links on the desktop in case someone has gone to the trouble of getting tel:
links to work on their computer.
If the site design dictated that I only provide one link, I'd use a tel:
link that I would try to change to callto:
on desktop browsers.
To set thousand separator, say 123,456.78
you have to use DecimalFormat:
DecimalFormat df = new DecimalFormat("#,###.00");
System.out.println(df.format(new BigDecimal(123456.75)));
System.out.println(df.format(new BigDecimal(123456.00)));
System.out.println(df.format(new BigDecimal(123456123456.78)));
Here is the result:
123,456.75
123,456.00
123,456,123,456.78
Although I set #,###.00
mask, it successfully formats the longer values too.
Note that the comma(,) separator in result depends on your locale. It may be just space( ) for Russian locale.
You can directly create your own style in this way:
input[type=button]
{
//Change the style as you like
}
I just had this issue. So there are a few approaches. The first is that new browsers support the
var formData = new FormData();
Follow this link to a blog with info about how support is limited to modern browsers but otherwise it totally solves this issue.
Otherwise you can post the form to an iframe using the target attribute. When you post the form be sure to set the target to an iframe with its display property set to none. The target is the name of the iframe. (Just so you know.)
I hope this helps
When the session expires the data is no longer present, so something like
if (!isset($_SESSION['id'])) {
header("Location: destination.php");
exit;
}
will redirect whenever the session is no longer active.
You can set how long the session cookie is alive using session.cookie_lifetime
ini_set("session.cookie_lifetime","3600"); //an hour
EDIT: If you are timing sessions out due to security concern (instead of convenience,) use the accepted answer, as the comments below show, this is controlled by the client and thus not secure. I never thought of this as a security measure.
Possible solution is described in this Code Project tip:
As folks mentioned IIS user network service user credentials while trying to log in sql server. So just change the Application pool settings in your IIS:
- Open Internet Information Service Manager
- Click on Application Pools in left navigation tree.
- Select your version Pool. In my case, I am using ASP .Net v4.0. If you dont have this version, select DefaultAppPool.
- Right click on step 3, and select advanced settings.
- Select Identity in properties window and click the button to change the value.
- Select Local System in Built-in accounts combo box and click ok. That's it. Now run your application. Everything works well.
a little example that works for me
.carousel-control-prev,
.carousel-control-next{
height: 50px;
width: 50px;
outline: $color-white;
background-size: 100%, 100%;
border-radius: 50%;
border: 1px solid $color-white;
background-color: $color-white;
}
.carousel-control-prev-icon {
background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23009be1' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E");
width: 30px;
height: 48px;
}
.carousel-control-next-icon {
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23009be1' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E");
width: 30px;
height: 48px;
}
Use the NSNumber method intValue
Here is Apple reference documentation
Padding
Padding is a CSS property that defines the space between an element content and its border (if it has a border). If an element has a border around it, padding will give space from that border to the element content which appears in that border. If an element does not have a border around it, then adding padding has no effect at all on that element, because there is no border to give space from.
Margin
Margin is a CSS property that defines the space of outside of an element to its next outside element.
Margin affects elements that both have or do not have borders. If an element has a border, margin defines the space from this border to the next outer element. If an element does not have a border, then margin defines the space from the element content to the next outer element.
Difference Between Padding and Margin
So the difference between margin and padding is that while padding deals with the inner space, margin deals with the outer space to the next outer element.
I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations:
In your case, I guess you have confused m
with n
. Here m
denotes the number of examples in your training set, not the number of features.
Let's have a look at my variation of your code:
import numpy as np
import random
# m denotes the number of examples here, not the number of features
def gradientDescent(x, y, theta, alpha, m, numIterations):
xTrans = x.transpose()
for i in range(0, numIterations):
hypothesis = np.dot(x, theta)
loss = hypothesis - y
# avg cost per example (the 2 in 2*m doesn't really matter here.
# But to be consistent with the gradient, I include it)
cost = np.sum(loss ** 2) / (2 * m)
print("Iteration %d | Cost: %f" % (i, cost))
# avg gradient per example
gradient = np.dot(xTrans, loss) / m
# update
theta = theta - alpha * gradient
return theta
def genData(numPoints, bias, variance):
x = np.zeros(shape=(numPoints, 2))
y = np.zeros(shape=numPoints)
# basically a straight line
for i in range(0, numPoints):
# bias feature
x[i][0] = 1
x[i][1] = i
# our target variable
y[i] = (i + bias) + random.uniform(0, 1) * variance
return x, y
# gen 100 points with a bias of 25 and 10 variance as a bit of noise
x, y = genData(100, 25, 10)
m, n = np.shape(x)
numIterations= 100000
alpha = 0.0005
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)
At first I create a small random dataset which should look like this:
As you can see I also added the generated regression line and formula that was calculated by excel.
You need to take care about the intuition of the regression using gradient descent. As you do a complete batch pass over your data X, you need to reduce the m-losses of every example to a single weight update. In this case, this is the average of the sum over the gradients, thus the division by m
.
The next thing you need to take care about is to track the convergence and adjust the learning rate. For that matter you should always track your cost every iteration, maybe even plot it.
If you run my example, the theta returned will look like this:
Iteration 99997 | Cost: 47883.706462
Iteration 99998 | Cost: 47883.706462
Iteration 99999 | Cost: 47883.706462
[ 29.25567368 1.01108458]
Which is actually quite close to the equation that was calculated by excel (y = x + 30). Note that as we passed the bias into the first column, the first theta value denotes the bias weight.
It is possible, as long as you know what instantiations you are going to need.
Add the following code at the end of stack.cpp and it'll work :
template class stack<int>;
All non-template methods of stack will be instantiated, and linking step will work fine.
Had a look about and I don't think theres a timezone in Java that is GMT + 13. So I think you have to use:
Calendar calendar = Calendar.getInstance();
//OR Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY)+13);
Date d = calendar.getTime();
(If there is then change "GMT" to that Timezone and remove the 2nd line of code)
OR
SimpleDateFormat df = new SimpleDateFormat();
df.setTimeZone(TimeZone.getTimeZone("GMT+13"));
System.out.println(df.format(c.getTime()));
If you want to set a specific time/date you can also use:
calendar.set(Calendar.DATE, 15);
calendar.set(Calendar.MONTH, 3);
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE, 45);
calendar.set(Calendar.SECOND, 00);
The following XML-to-Python-dict snippet parses entities as well as attributes following this XML-to-JSON "specification". It is the most general solution handling all cases of XML.
from collections import defaultdict
def etree_to_dict(t):
d = {t.tag: {} if t.attrib else None}
children = list(t)
if children:
dd = defaultdict(list)
for dc in map(etree_to_dict, children):
for k, v in dc.items():
dd[k].append(v)
d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.items()}}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
It is used:
from xml.etree import cElementTree as ET
e = ET.XML('''
<root>
<e />
<e>text</e>
<e name="value" />
<e name="value">text</e>
<e> <a>text</a> <b>text</b> </e>
<e> <a>text</a> <a>text</a> </e>
<e> text <a>text</a> </e>
</root>
''')
from pprint import pprint
pprint(etree_to_dict(e))
The output of this example (as per above-linked "specification") should be:
{'root': {'e': [None,
'text',
{'@name': 'value'},
{'#text': 'text', '@name': 'value'},
{'a': 'text', 'b': 'text'},
{'a': ['text', 'text']},
{'#text': 'text', 'a': 'text'}]}}
Not necessarily pretty, but it is unambiguous, and simpler XML inputs result in simpler JSON. :)
If you want to do the reverse, emit an XML string from a JSON/dict, you can use:
try:
basestring
except NameError: # python3
basestring = str
def dict_to_etree(d):
def _to_etree(d, root):
if not d:
pass
elif isinstance(d, basestring):
root.text = d
elif isinstance(d, dict):
for k,v in d.items():
assert isinstance(k, basestring)
if k.startswith('#'):
assert k == '#text' and isinstance(v, basestring)
root.text = v
elif k.startswith('@'):
assert isinstance(v, basestring)
root.set(k[1:], v)
elif isinstance(v, list):
for e in v:
_to_etree(e, ET.SubElement(root, k))
else:
_to_etree(v, ET.SubElement(root, k))
else:
raise TypeError('invalid type: ' + str(type(d)))
assert isinstance(d, dict) and len(d) == 1
tag, body = next(iter(d.items()))
node = ET.Element(tag)
_to_etree(body, node)
return ET.tostring(node)
pprint(dict_to_etree(d))
Make sure that your package is installed in your $GOPATH
directory or already inside your workspace/package.
For example: if your $GOPATH = "c:\go"
, make sure that the package inside C:\Go\src\pkgName
This work fine for all Linux environment.
#!/bin/sh
cat /etc/*-release
In Ubuntu:
$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=10.04
DISTRIB_CODENAME=lucid
DISTRIB_DESCRIPTION="Ubuntu 10.04.4 LTS"
or 12.04:
$ cat /etc/*-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=12.04
DISTRIB_CODENAME=precise
DISTRIB_DESCRIPTION="Ubuntu 12.04.4 LTS"
NAME="Ubuntu"
VERSION="12.04.4 LTS, Precise Pangolin"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu precise (12.04.4 LTS)"
VERSION_ID="12.04"
In RHEL:
$ cat /etc/*-release
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Or Use this Script:
#!/bin/sh
# Detects which OS and if it is Linux then it will detect which Linux
# Distribution.
OS=`uname -s`
REV=`uname -r`
MACH=`uname -m`
GetVersionFromFile()
{
VERSION=`cat $1 | tr "\n" ' ' | sed s/.*VERSION.*=\ // `
}
if [ "${OS}" = "SunOS" ] ; then
OS=Solaris
ARCH=`uname -p`
OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
elif [ "${OS}" = "AIX" ] ; then
OSSTR="${OS} `oslevel` (`oslevel -r`)"
elif [ "${OS}" = "Linux" ] ; then
KERNEL=`uname -r`
if [ -f /etc/redhat-release ] ; then
DIST='RedHat'
PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
elif [ -f /etc/SuSE-release ] ; then
DIST=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
elif [ -f /etc/mandrake-release ] ; then
DIST='Mandrake'
PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
elif [ -f /etc/debian_version ] ; then
DIST="Debian `cat /etc/debian_version`"
REV=""
fi
if [ -f /etc/UnitedLinux-release ] ; then
DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
fi
OSSTR="${OS} ${DIST} ${REV}(${PSUEDONAME} ${KERNEL} ${MACH})"
fi
echo ${OSSTR}
if not myList:
print "Nothing here"
This is a simple way.
<div class="row">
<div class="col-md-6 mx-auto">
<p>My text</p>
</div>
</div>
The number 6 controls the width of the column.
a reply to @DarinDimitrov for a case where i have used foreach in a razor view.
<li><label for="category">Category</label>
<select id="category">
<option value="0">All</option>
@foreach(Category c in Model.Categories)
{
<option title="@c.Description" value="@c.CategoryID">@c.Name</option>
}
</select>
</li>
Mysql isn't very clever. When you want to use the same timestamp in multiple update or insert queries, you need to declare a variable.
When you use the now()
function, the system will call the current timestamp every time you call it in another query.
this did it for me. you can vary the options for the output format to Base64.Default whatsoever.
// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:
<body onload="parent.alertsize(document.body.scrollHeight);">
In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
to that script just add:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
How you use the above script is easy:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
Complete iframe code: (this iframe named "theiframe.htm")
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.
Make a new column
alter table users add newusernum int;
Copy values over
update users set newusernum=usernum;
Drop the old column
alter table users drop column usernum;
Rename the new column to the old column name
EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';