Get the selected item with Kotlin:
spinner.selectedItem.toString()
If your AWK doesn't have strftime()
:
ping host | perl -nle 'print scalar(localtime), " ", $_'
To redirect it to a file, use standard shell redirection and turn off output buffering:
ping host | perl -nle 'BEGIN {$|++} print scalar(localtime), " ", $_' > outputfile
If you want ISO8601 format for the timestamp:
ping host | perl -nle 'use Time::Piece; BEGIN {$|++} print localtime->datetime, " ", $_' > outputfile
Try this maybe :
Bootply : http://www.bootply.com/106527
Js :
$('input').on('click', function(){
var valeur = 0;
$('input:checked').each(function(){
if ( $(this).attr('value') > valeur )
{
valeur = $(this).attr('value');
}
});
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);
});
HTML :
<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
<div class="row tasks">
<div class="col-md-6">
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
</div>
<div class="col-md-2">
<label>2014-01-29</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="10">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="20">
</div>
</div><!-- tasks -->
<div class="row tasks">
<div class="col-md-6">
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
</div>
<div class="col-md-2">
<label>2014-01-25</label>
</div>
<div class="col-md-2">
<input name="progress" class="progress" type="checkbox" value="30">
</div>
<div class="col-md-2">
<input name="done" class="done" type="checkbox" value="40">
</div>
</div><!-- tasks -->
Css
.tasks{
background-color: #F6F8F8;
padding: 10px;
border-radius: 5px;
margin-top: 10px;
}
.tasks span{
font-weight: bold;
}
.tasks input{
display: block;
margin: 0 auto;
margin-top: 10px;
}
.tasks a{
color: #000;
text-decoration: none;
border:none;
}
.tasks a:hover{
border-bottom: dashed 1px #0088cc;
}
.tasks label{
display: block;
text-align: center;
}
$(function(){_x000D_
$('input').on('click', function(){_x000D_
var valeur = 0;_x000D_
$('input:checked').each(function(){_x000D_
if ( $(this).attr('value') > valeur )_x000D_
{_x000D_
valeur = $(this).attr('value');_x000D_
}_x000D_
});_x000D_
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur); _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
background-color: #F6F8F8;_x000D_
padding: 10px;_x000D_
border-radius: 5px;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
display: block;_x000D_
margin: 0 auto;_x000D_
margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
color: #000;_x000D_
text-decoration: none;_x000D_
border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
display: block;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="progress progress-striped active">_x000D_
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
</div>_x000D_
</div>_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-29</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="10">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="20">_x000D_
</div>_x000D_
</div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
<div class="col-md-6">_x000D_
<p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<label>2014-01-25</label>_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="progress" class="progress" type="checkbox" value="30">_x000D_
</div>_x000D_
<div class="col-md-2">_x000D_
<input name="done" class="done" type="checkbox" value="40">_x000D_
</div>_x000D_
</div><!-- tasks -->
_x000D_
I use this combination of extension methods:
public static Stream Copy(this Stream source)
{
if (source == null)
return null;
long originalPosition = -1;
if (source.CanSeek)
originalPosition = source.Position;
MemoryStream ms = new MemoryStream();
try
{
Copy(source, ms);
if (originalPosition > -1)
ms.Seek(originalPosition, SeekOrigin.Begin);
else
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
catch
{
ms.Dispose();
throw;
}
}
public static void Copy(this Stream source, Stream target)
{
if (source == null)
throw new ArgumentNullException("source");
if (target == null)
throw new ArgumentNullException("target");
long originalSourcePosition = -1;
int count = 0;
byte[] buffer = new byte[0x1000];
if (source.CanSeek)
{
originalSourcePosition = source.Position;
source.Seek(0, SeekOrigin.Begin);
}
while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
target.Write(buffer, 0, count);
if (originalSourcePosition > -1)
{
source.Seek(originalSourcePosition, SeekOrigin.Begin);
}
}
You can use:
width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;
EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/
very simple DateTime.Now.ToString("hh:mm:ss tt")
I'm using the awesome_print gem
So you just have to type :
ap @var
I have tried a few fixes and none of them works. My version is simple: add a new unused parameter into query parameters
if (force) {
let key = 'time';
while (key in filter) {
key = '_' + key;
}
filter[key] = Date.now();
}
this.router.navigate(['.', { filter: JSON.stringify(filter) }]);
If you're on a Mac do brew install geckodriver
and off you go!
You want to use timeout. timeout 10 will sleep 10 seconds
I added
c:\users\[user]\appdata\roaming\python\python37\site-packages
to the path and it worked.
By using very simple method, we can follow this:
$http({
url : "submit_form_adv.php",
method : 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p)+' = '+encodeURIComponent(obj[p]));
return str.join('&');
},
data : {sample_id : 100, sample_name: 'Abin John'},
}).success(function(data, status, headers, config) {
}).error(function(ata, status, headers, config) {
});
you may want to see if your app can run under IronPython. If so, you can compile it to an exe http://www.codeplex.com/IronPython
try this code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<Script>
$(document).ready(function(){
$("#postcontent").click(function(e) {
$.ajax({type:"POST",url:"add_new_post.php",data:$("#postcontent").serialize(),beforeSend:function(){
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},success:function(response){
//alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
});
});
</script>
<form name="postcontent" id="postcontent">
<input name="postsubmit" type="button" id="postsubmit" value="POST"/>
<textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
Why not do it simply by picking eight different numbers from 0
to Horse.count
and use that to get your horses?
offsets = (0...Horse.count).to_a.sample(8)
@suggested_horses = offsets.map{|i| Horse.first(:offset => i) }
This has the added advantage that it won't cause an infinite loop if you happen to have less than 8 horses in your database.
Note: Array#sample
is new to 1.9 (and coming in 1.8.8), so either upgrade your Ruby, require 'backports'
or use something like shuffle.first(n)
.
Here's a setTimeout equivalent, mostly useful when trying to update the User Interface after a delay.
As you may know, updating the user interface can only by done from the UI thread. AsyncTask does that for you by calling its onPostExecute method from that thread.
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Update the User Interface
}
}.execute();
Here's my solution! Windows 10, Python 3.7.1
I'm not sure why this code works, but it completely erases the original line. I compiled it from the previous answers. The other answers would just return the line to the beginning, but if you had a shorter line afterwards, it would look messed up like hello
turns into byelo
.
import sys
#include ctypes if you're on Windows
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
#end ctypes
def clearline(msg):
CURSOR_UP_ONE = '\033[K'
ERASE_LINE = '\x1b[2K'
sys.stdout.write(CURSOR_UP_ONE)
sys.stdout.write(ERASE_LINE+'\r')
print(msg, end='\r')
#example
ig_usernames = ['beyonce','selenagomez']
for name in ig_usernames:
clearline("SCRAPING COMPLETE: "+ name)
Output - Each line will be rewritten without any old text showing:
SCRAPING COMPLETE: selenagomez
Next line (rewritten completely on same line):
SCRAPING COMPLETE: beyonce
As of May 2018, you can find the full list here: https://developers.facebook.com/docs/reference/opengraph#object-type
apps.saves
An action representing someone saving an app to try later.
article
This object represents an article on a website. It is the preferred type for blog posts and news stories.
book
This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines
books.author
This object type represents a single author of a book.
books.book
This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books
books.genre
This object type represents the genre of a book or publication.
books.quotes
Returns no data as of April 4, 2018.
An action representing someone quoting from a book.
books.rates
Returns no data as of April 4, 2018.
An action representing someone rating a book.
books.reads
Returns no data as of April 4, 2018.
An action representing someone reading a book.
books.wants_to_read
Returns no data as of April 4, 2018.
An action representing someone wanting to read a book.
business.business
This object type represents a place of business that has a location, operating hours and contact information.
fitness.bikes
Returns no data as of April 4, 2018.
An action representing someone cycling a course.
fitness.course
This object type represents the user's activity contributing to a particular run, walk, or bike course.
fitness.runs
Returns no data as of April 4, 2018.
An action representing someone running a course.
fitness.walks
Returns no data as of April 4, 2018.
An action representing someone walking a course.
game.achievement
This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has agame:points
value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.
games.achieves
An action representing someone reaching a game achievement.
games.celebrate
An action representing someone celebrating a victory in a game.
games.plays
An action representing someone playing a game. Stories for this action will only appear in the activity log.
games.saves
An action representing someone saving a game.
music.album
This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.
music.listens
Returns no data as of April 4, 2018.
An action representing someone listening to a song, album, radio station, playlist or musician
music.playlist
This object type represents a music playlist, an ordered collection of songs from a collection of artists.
music.playlists
Returns no data as of April 4, 2018.
An action representing someone creating a playlist.
music.radio_station
This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.
music.song
This object type represents a single song.
news.publishes
An action representing someone publishing a news article.
news.reads
Returns no data as of April 4, 2018.
An action representing someone reading a news article.
og.follows
An action representing someone following a Facebook user
og.likes
An action representing someone liking any object.
pages.saves
An action representing someone saving a place.
place
This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.
product
This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.
product.group
This object type represents a group of product items.
product.item
This object type represents a product item.
profile
This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. Thefb:profile_id
field associates the object with a Facebook user.
restaurant.menu
This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.
restaurant.menu_item
This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.
restaurant.menu_section
This object type represents a section in a restaurant's menu. A section contains multiple menu items.
restaurant.restaurant
This object type represents a restaurant at a specific location.
restaurant.visited
An action representing someone visiting a restaurant.
restaurant.wants_to_visit
An action representing someone wanting to visit a restaurant
sellers.rates
An action representing a commerce seller has been given a rating.
video.episode
This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.
video.movie
This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.
video.other
This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use thevideo.movie
orvideo.tv_show
object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)
video.rates
Returns no data as of April 4, 2018.
An action representing someone rating a movie, TV show, episode or another piece of video content.
video.tv_show
This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use thevideo.episode
object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)
video.wants_to_watch
Returns no data as of April 4, 2018.
An action representing someone wanting to watch video content.
video.watches
Returns no data as of April 4, 2018.
An action representing someone watching video content.
I have just encountered a similar need. In my case, slf4j is configured with the java logging adapter (the jdk14 one). Using the following code snippet I have managed to change the debug level at runtime:
Logger logger = LoggerFactory.getLogger("testing");
java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("testing");
julLogger.setLevel(java.util.logging.Level.FINE);
logger.debug("hello world");
My dad moved his office after 30 year and they need to update the address in the header of their Crystal Reports 7 (1997!) based billing system.
After buying old copies of Access 97 and Visual Studio 2003 Pro, I found out that both programs were too new - they could open the RPT files, but they saved them with an updated version that would not open in the billing system.
I ended up being able to make the changes using this life-saver program...
http://www.softwareforces.com/Products/rpt-inspector-professional-suite-for-crystal-reports
It was available with a 10 day free trial, and I only needed about 10 minutes to make my changes. That said, I would have happily paid whatever they asked for it. :)
Some hints:
for entry in "$search_dir"/*
do
echo "$entry"
done
getElementsByClassName
returns HTMLCollection in modern browsers.
which is
array-like object similar to arguments which is iteratable by for...of
loop see below what MDN doc is saying about it:
The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.
example
for (const element of document.getElementsByClassName("classname")){
element.style.display="none";
}
try this! syntax less lines and even more compact! don't forget to add the properties you want to add with this approach!
cmd.Parameters.Add(new SqlParameter{SqlValue=(object)username??DBNull.Value,ParameterName="user" } );
I'm assuming you want the standard system bell, and don't want to concern yourself with frequencies and durations etc., you just want the standard windows bell.
import winsound
winsound.MessageBeep()
I have recently written a blog about it for the Laravel5.6. Link to blog is https://www.samundra.com.np/integrating-font-awesome-with-laravel-5.x-using-webpack/1574
The steps are similar to above description. But in my case, I had to do extra steps like configuring the webfonts path to font-awesome in "public" directory. Setting the resource root in Laravel mix etc. You can find the details in the blog.
I am leaving the link here so it helps people for whom the mentioned solutions don't work.
If there is a failed merge, which is the most common reason for wanting to undo a git pull
, running git reset --merge
does exactly what one would expect: keep the fetched files, but undo the merge that git pull
attempted to merge. Then one can decide what to do without the clutter that git merge
sometimes generates. And it does not need one to find the exact commit ID which --hard
mentioned in every other answer requires.
@section
is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).
You might find Scott Gu's write up on this very interesting.
Edit: Based on additional question clarification
The @RenderSection
syntax goes into the Shared View, such as:
<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>
This would then be placed in your view with @Section
syntax:
@section Sidebar{
<!-- Content Here -->
}
In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.
Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.
@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.
function UniqueDateTime(format='',language='en-US'){
//returns a meaningful unique number based on current time, and milliseconds, making it virtually unique
//e.g : 20170428-115833-547
//allows personal formatting like more usual :YYYYMMDDHHmmSS, or YYYYMMDD_HH:mm:SS
var dt = new Date();
var modele="YYYYMMDD-HHmmSS-mss";
if (format!==''){
modele=format;
}
modele=modele.replace("YYYY",dt.getFullYear());
modele=modele.replace("MM",(dt.getMonth()+1).toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("DD",dt.getDate().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("HH",dt.getHours().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mm",dt.getMinutes().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("SS",dt.getSeconds().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mss",dt.getMilliseconds().toLocaleString(language, {minimumIntegerDigits: 3, useGrouping:false}));
return modele;
}
For MongoDB 3.6 and newer:
The $expr
operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP
operator to check the length of the string as follows:
db.usercollection.find({
"name": { "$exists": true },
"$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] }
})
For MongoDB 3.4 and newer:
You can also use the aggregation framework with the $redact
pipeline operator that allows you to proccess the logical condition with the $cond
operator and uses the special operations $$KEEP
to "keep" the document where the logical condition is true or $$PRUNE
to "remove" the document where the condition was false.
This operation is similar to having a $project
pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match
, except that $redact
uses a single pipeline stage which is more efficient.
As for the logical condition, there are String Aggregation Operators that you can use $strLenCP
operator to check the length of the string. If the length is $gt
a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.
Consider running the following aggregate operation which demonstrates the above concept:
db.usercollection.aggregate([
{ "$match": { "name": { "$exists": true } } },
{
"$redact": {
"$cond": [
{ "$gt": [ { "$strLenCP": "$name" }, 40] },
"$$KEEP",
"$$PRUNE"
]
}
},
{ "$limit": 2 }
])
If using $where
, try your query without the enclosing brackets:
db.usercollection.find({$where: "this.name.length > 40"}).limit(2);
A better query would be to to check for the field's existence and then check the length:
db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2);
or:
db.usercollection.find({name: {$exists: true}, $where: "this.name.length >
40"}).limit(2);
MongoDB evaluates non-$where
query operations before $where
expressions and non-$where
query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where
will be much slower compared to that. It's recommended to use JavaScript expressions and the $where
operator as a last resort when you can't structure the data in any other way, or when you are dealing with a
small subset of data.
A different and faster approach that avoids the use of the $where
operator is the $regex
operator. Consider the following pattern which searches for
db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2);
Note - From the docs:
If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.
A regular expression is a “prefix expression” if it starts with a caret
(^)
or a left anchor(\A)
, followed by a string of simple symbols. For example, the regex/^abc.*/
will be optimized by matching only against the values from the index that start withabc
.Additionally, while
/^a/, /^a.*/,
and/^a.*$/
match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however,/^a.*/
, and/^a.*$/
are slower./^a/
can stop scanning after matching the prefix.
I prefer using .env file for different environment.
env.dev
to .env into root folder env.prod
to .envand in code
use
require('dotenv').config();
const API = process.env.API ## which will store the value from .env file
Here is the typical structure of new Codeigniter project:
- application/
- system/
- user_guide/
- index.php <- this is the file you need to change
I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.
With this code you can deploy your site to your production server without changing index.php each time.
// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT')) {
switch (ENVIRONMENT) {
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
ini_set('display_errors', 0);
break;
default:
exit('The application environment is not set correctly.');
}
}
1)Go to configure build path . 2)Remove unbound JRE library . 3)Add library --> JRE System library .
Then project compile and done ..
Try to:
$requestData = $request->all();
$requestData['img'] = $img;
Another way to do it:
$request->merge(['img' => $img]);
Thanks to @JoelHinz for this.
If you want to add or overwrite nested data:
$data['some']['thing'] = 'value';
$request->merge($data);
If you do not inject Request $request
object, you can use the global request()
helper or \Request::
facade instead of $request
No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".
x = np.zeros((2,3,4))
Simply Means:
2 Sets, 3 Rows per Set, 4 Columns
Example:
Input
x = np.zeros((2,3,4))
Output
Set # 1 ---- [[[ 0., 0., 0., 0.], ---- Row 1
[ 0., 0., 0., 0.], ---- Row 2
[ 0., 0., 0., 0.]], ---- Row 3
Set # 2 ---- [[ 0., 0., 0., 0.], ---- Row 1
[ 0., 0., 0., 0.], ---- Row 2
[ 0., 0., 0., 0.]]] ---- Row 3
Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.
Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".
Please stick to the semantics of protocol. Use 2xx for successful responses and 4xx , 5xx for error responses - be it your business exceptions or other. Had using 2xx for any response been the intended use case in the protocol, they would not have other status codes in the first place.
You can define a template which will work not only just with doubles, but with other types as well.
template <typename T> string tostr(const T& t) {
ostringstream os;
os<<t;
return os.str();
}
Then you can use it for other types.
double x = 14.4;
int y = 21;
string sx = tostr(x);
string sy = tostr(y);
You want to set its 'Format' property to be time and add a spin button control to it:
yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;
Perhaps try:
var body = document.getElementsByTagName('body')[0];
body.setAttribute("data-body","");
DSM's and Tadeck's answers answer your question directly.
In my scripts I often use the convenient dict.pop()
to deal with optional, and additional arguments. Here's an example of a simple print()
wrapper:
def my_print(*args, **kwargs):
prefix = kwargs.pop('prefix', '')
print(prefix, *args, **kwargs)
Then:
>>> my_print('eggs')
eggs
>>> my_print('eggs', prefix='spam')
spam eggs
As you can see, if prefix
is not contained in kwargs
, then the default ''
(empty string) is being stored in the local prefix
variable. If it is given, then its value is being used.
This is generally a compact and readable recipe for writing wrappers for any kind of function: Always just pass-through arguments you don't understand, and don't even know if they exist. If you always pass through *args
and **kwargs
you make your code slower, and requires a bit more typing, but if interfaces of the called function (in this case print
) changes, you don't need to change your code. This approach reduces development time while supporting all interface changes.
Right now (August 2014) You could use RStudio for converting R Markdown to PDF. Basically, RStudio use pandoc to convert Rmd to PDF.
You could change metadata to:
For more details - http://rmarkdown.rstudio.com/pdf_document_format.html
This is an old question, and I know its asking specifically about adding a script tag into the head, however based on the OPs explanation they actually just intend to execute some JS code which has been obtained via some other JS function.
This is much simpler than adding a script tag into the page.
Simply:
eval(decoded);
Eval will execute a string of JS in-line, without any need to add it to the DOM at all.
I don't think there's ever really a need to add an in-line script tag to the DOM after page load.
More info here: http://www.w3schools.com/jsref/jsref_eval.asp
I had trouble with all of the other code examples above. In Chrome, this was the condition that worked for me:
typeof possiblyUndefinedVariable !== "undefined"
I will have to test that in other browsers and see how things go I suppose.
You can do this
@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem()
{
Text = "Newest to Oldest", Value = "0" }, new SelectListItem() { Text = "Oldest to Newest", Value = "1" } , new
{
onchange = @"form.submit();"
}
})
@echo off
title Professional Hacker
color 02
:matrix
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
goto matrix
Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.
If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.
If you prefer a result set return, then again is arguable better to use the OUTPUT clause:
INSERT INTO MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);
This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.
Overall, I can't see a single case when returning SCOPE_IDENTITY()
as a result set would be a good practice.
An alternative to assume-unchanged
is skip-worktree
. The latter has a different meaning, something like "Git should not track this file. Developers can, and are encouraged, to make local changes."
In your situation where you do not wish to track changes to (typically large) build files, assume-unchanged
is a good choice.
In the situation where the file should have default contents and the developer is free to modify the file locally, but should not check their local changes back to the remote repo, skip-worktree
is a better choice.
Another elegant option is to have a default file in the repo. Say the filename is BuildConfig.Default.cfg
. The developer is expected to rename this locally to BuildConfig.cfg
and they can make whatever local changes they need. Now add BuildConfig.cfg
to .gitignore
so the file is untracked.
See this question which has some nice background information in the accepted answer.
No need to store anything. No need for hashsets. (Extra memory), You can do it as you move through the array. However, The array has to be sorted. And we know the very most minimum value is 1
import java.util.Arrays;
class Solution {
public int solution(int[] A) {
Arrays.sort(A);
int min = 1;
int cap = A.length; //for efficiency — no need to calculate or access the array object’s length property per iteration
for (int i = 0; i < cap; i++){
if(A[i] == min){
min++;
}//can add else if A[i] > min, break; as suggested by punit
}
//min = ( min <= 0 ) ? 1:min; //this means: if (min <= 0 ){min =1}else{min = min} you can also do: if min <1 for better efficiency/less jumps
return min;
}
}
As of today, there is an official Android-hosted copy of Volley available on JCenter:
compile 'com.android.volley:volley:1.0.0'
This was compiled from the AOSP volley source code.
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
In Django 1.8, this is how I did mine.
from django.views.generic.base import RedirectView
url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))
Instead of using url
, you can use the pattern_name
, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.
Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered.
Take a look at the web.config
in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config
):
<configuration>
<system.web>
<httpHandlers>
<add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
<add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
<add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
<add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
<add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
</httpHandlers>
</system.web>
<configuration>
You can register your own handlers with a whatever.axd
name in your application's web.config
. While you can bind your handlers to whatever names you like, .axd
has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd
to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf
(or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
There is one rule that is set by font-awesome.css
, which you need to override.
You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline;
by default and which I've corrected here:
<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:
I've downsized the font-size of the icon above in this instance to 30px
, as it feels too big at 40px
for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:
This works across year and month changes.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay())));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
When using hashcodes with any jce provider you first try to get an instance of the algorithm, then update it with the data you want to be hashed and when you are finished you call digest to get the hash value.
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(in.getBytes());
byte[] digest = sha.digest();
you can use the digest to get a base64 or hex encoded version according to your needs
To get the number of element in any iterable object, your goto method in Python is len()
eg.
a = range(1000) # range
b = 'abcdefghijklmnopqrstuvwxyz' # string
c = [10, 20, 30] # List
d = (30, 40, 50, 60, 70) # tuple
e = {11, 21, 31, 41} # set
len()
method can work on all the above data types because they are iterable i.e You can iterate over them.
all_var = [a, b, c, d, e] # All variables are stored to a list
for var in all_var:
print(len(var))
Rough estimate of the len() method
def len(iterable, /):
total = 0
for i in iterable:
total += 1
return total
There are many methods :
CSS
<div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div>
2 . Center horizontally and vertically a single line of text
CSS
<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>
3 . Center horizontal and vertical align of an element with no specific measure
CSS
<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>
A function pointer to a class member is a problem that is really suited to using boost::function. Small example:
#include <boost/function.hpp>
#include <iostream>
class Dog
{
public:
Dog (int i) : tmp(i) {}
void bark ()
{
std::cout << "woof: " << tmp << std::endl;
}
private:
int tmp;
};
int main()
{
Dog* pDog1 = new Dog (1);
Dog* pDog2 = new Dog (2);
//BarkFunction pBark = &Dog::bark;
boost::function<void (Dog*)> f1 = &Dog::bark;
f1(pDog1);
f1(pDog2);
}
IMHO for Angular2 (v2.2.3) the best way is to add services that contain the global variable and inject them into components without the providers
tag inside the @Component
annotation. By this way you are able to share information between components.
A sample service that owns a global variable:
import { Injectable } from '@angular/core'
@Injectable()
export class SomeSharedService {
public globalVar = '';
}
A sample component that updates the value of your global variable:
import { SomeSharedService } from '../services/index';
@Component({
templateUrl: '...'
})
export class UpdatingComponent {
constructor(private someSharedService: SomeSharedService) { }
updateValue() {
this.someSharedService.globalVar = 'updated value';
}
}
A sample component that reads the value of your global variable:
import { SomeSharedService } from '../services/index';
@Component({
templateUrl: '...'
})
export class ReadingComponent {
constructor(private someSharedService: SomeSharedService) { }
readValue() {
let valueReadOut = this.someSharedService.globalVar;
// do something with the value read out
}
}
Note that
providers: [ SomeSharedService ]
should not be added to your@Component
annotation. By not adding this line injection will always give you the same instance ofSomeSharedService
. If you add the line a freshly created instance is injected.
With personal experience of using the following code within a Stored Procedure which Hashed a SP Variable I can confirm, although undocumented, this combination works 100% as per my example:
@var=SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA2_512', @SPvar)), 3, 128)
pip install opencv-python==3.4.2.17 numpy==1.14.5
done the job for me!
By using java 8 java.time.LocalDate
String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/dd/yyyy"))
.with(TemporalAdjusters.lastDayOfMonth());
try like this
if (!(a | b)) {
//blahblah
}
It's same with
if (a | b) {}
else {
// blahblah
}
I did a small experiment of running a method "1,000,000,000 (one billion)" times with "Parallel.For" and one with "Task" objects.
I measured the processor time and found Parallel more efficient. Parallel.For divides your task in to small work items and executes them on all the cores parallely in a optimal way. While creating lot of task objects ( FYI TPL will use thread pooling internally) will move every execution on each task creating more stress in the box which is evident from the experiment below.
I have also created a small video which explains basic TPL and also demonstrated how Parallel.For utilizes your core more efficiently http://www.youtube.com/watch?v=No7QqSc5cl8 as compared to normal tasks and threads.
Experiment 1
Parallel.For(0, 1000000000, x => Method1());
Experiment 2
for (int i = 0; i < 1000000000; i++)
{
Task o = new Task(Method1);
o.Start();
}
If you've enabled two factor authentication, then you'll need to generate a personal access token and use that instead of your regular password. More info here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/
For styles wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );
Then use: wp_enqueue_style('namespace');
wherever you want the css to load.
Scripts are as above but the quicker way for loading jquery is just to use enqueue loaded in an init for the page you want it to load on: wp_enqueue_script('jquery');
Unless of course you want to use the google repository for jquery.
You can also conditionally load the jquery library that your script is dependent on:
wp_enqueue_script('namespaceformyscript', 'http://locationofscript.com/myscript.js', array('jquery'));
Update Sept. 2017
I wrote this answer a while ago. I should clarify that the best place to enqueue your scripts and styles is within the wp_enqueue_scripts
hook. So for example:
add_action('wp_enqueue_scripts', 'callback_for_setting_up_scripts');
function callback_for_setting_up_scripts() {
wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );
wp_enqueue_style( 'namespace' );
wp_enqueue_script( 'namespaceformyscript', 'http://locationofscript.com/myscript.js', array( 'jquery' ) );
}
The wp_enqueue_scripts
action will set things up for the "frontend". You can use the admin_enqueue_scripts
action for the backend (anywhere within wp-admin) and the login_enqueue_scripts
action for the login page.
Most easiest way to do it as follow:
var elementPosition = $('#navigation').offset();
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('#navigation').css('position','fixed').css('top','0');
} else {
$('#navigation').css('position','static');
}
});
From within less (in Linux):
g and the line number to go forward
G and the line number to go backwards
Used alone, g and G will take you to the first and last line in a file respectively; used with a number they are both equivalent.
An example; you want to go to line 320123 of a file,
press 'g' and after the colon type in the number 320123
Additionally you can type '-N' inside less to activate / deactivate the line numbers. You can as a matter of fact pass any command line switches from inside the program, such as -j or -N.
NOTE: You can provide the line number in the command line to start less (less +number -N) which will be much faster than doing it from inside the program:
less +12345 -N /var/log/hugelogfile
This will open a file displaying the line numbers and starting at line 12345
Source: man 1 less and built-in help in less (less 418)
This tutorial details how to update a jar file
jar -uf jar-file <optional_folder_structure>/input-file(s)
where 'u' means update.
for center and auto zoom on display markers
// map: an instance of google.maps.Map object
// latlng_points_array: an array of google.maps.LatLng objects
var latlngbounds = new google.maps.LatLngBounds( );
for ( var i = 0; i < latlng_points_array.length; i++ ) {
latlngbounds.extend( latlng_points_array[i] );
}
map.fitBounds( latlngbounds );
You have a couple of questions here, so I'll address them separately:
My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).
You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:
Base table (what you have now):
| id primary_key sequence
| -- other columns here.
Items table:
| id primary_key sequence
| descript VARCHAR(30) UNIQUE
Map table:
| base_id bigint
| items_id bigint
Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.
And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.
If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.
Personally, I would use TEXT
. It does not sound like you'd gain much by making this a BLOB
, and TEXT
, in my experience, is easier to read if you're using some form of IDE.
You can disable caching globally using $.ajaxSetup()
, for example:
$.ajaxSetup({ cache: false });
This appends a timestamp to the querystring when making the request. To turn cache off for a particular $.ajax()
call, set cache: false
on it locally, like this:
$.ajax({
cache: false,
//other options...
});
You need to add style="overflow-y:scroll;"
to the div tag. (This will force a scrollbar on the vertical).
If you only want a scrollbar when needed, just do overflow-y:auto;
I think every process you make start executing the line you create so something like this...
pid=fork() at line 6. fork function returns 2 values
you have 2 pids, first pid=0 for child and pid>0 for parent
so you can use if to separate
.
/*
sleep(int time) to see clearly
<0 fail
=0 child
>0 parent
*/
int main(int argc, char** argv) {
pid_t childpid1, childpid2;
printf("pid = process identification\n");
printf("ppid = parent process identification\n");
childpid1 = fork();
if (childpid1 == -1) {
printf("Fork error !\n");
}
if (childpid1 == 0) {
sleep(1);
printf("child[1] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
childpid2 = fork();
if (childpid2 == 0) {
sleep(2);
printf("child[2] --> pid = %d and ppid = %d\n",
getpid(), getppid());
} else {
sleep(3);
printf("parent --> pid = %d\n", getpid());
}
}
return 0;
}
//pid = process identification
//ppid = parent process identification
//child[1] --> pid = 2399 and ppid = 2398
//child[2] --> pid = 2400 and ppid = 2398
//parent --> pid = 2398
You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html()
call will not serialize the event.
If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip
method.
" hello ".strip #=> "hello"
"\tgoodbye\r\n".strip #=> "goodbye"
as mentioned here.
edit The original title for this question was different. My answer is for the original question.
I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:
original Code block:
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
Changed Code block:
post: function (url, data, callback, failcallback, type) {
if (type === undefined || type === null) {
if (!jQuery.isFunction(failcallback)) {
type=failcallback
}
else if (!jQuery.isFunction(callback)) {
type = callback
}
}
if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
failcallback = callback;
}
// shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
error:failcallback,
dataType: type
});
},
This should help the one trying to catch error on $.Post in jquery.
Updated: Or there is another way to do this is :
$.post(url,{},function(res){
//To do write if call is successful
}).error(function(p1,p2,p3){
//To do Write if call is failed
});
Below gives me opposite of what you have. (Notice Group column)
SELECT
*
FROM
myTable
GROUP BY
Group_value,
ID
ORDER BY
count(Group_value)
Let me know if this is fine with you...
I am trying to get what you want too...
You can also hide spinner with following trick :
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
opacity:0;
pointer-events:none;
}
the difference is not between <span>
and <div>
specifically, but between inline
and block
elements. <span>
defaults to being display:inline;
whereas <div>
defaults to being display:block;
. But these can be overridden in CSS.
The difference in the way text-align:center
works between the two is down to the width.
A block
element defaults to being the width of its container. It can have its width set using CSS, but either way it is a fixed width.
An inline
element takes its width from the size of its content text.
text-align:center
tells the text to position itself centrally in the element. But in an inline
element, this is clearly not going to have any effect because the element is the same width as the text; aligning it one way or the other is meaningless.
In a block
element, because the element's width is independent of the content, the content can be positioned within the element using the text-align
style.
Finally, a solution for you:
There is an additional value for the display
property which provides a half-way house between block
and inline
. Conveniently enough, it's called inline-block
. If you specify a <span>
to be display:inline-block;
in the CSS, it will continue to work as an inline element but will take on some of the properties of a block as well, such as the ability to specify a width
. Once you specify a width for it, you will be able to center the text within that width using text-align:center;
Hope that helps.
In the HTML source provided, the element #tfl
has an inline style "display:block
". Inline style will always override stylesheets styles…
Then, you have some options (while as you said you can't modify the html code nor using javascript):
display:none
with !important
rule (not recommended)put the div offscreen with theses rules :
#tfl {
position: absolute;
left: -9999px;
}
Operations on integers are exact. double
is a floating point data type, and floating point operations are approximate whenever there's a fraction.
double
also takes up twice as much space as int
in many implementations (e.g. most 32-bit systems) .
Try:
sudo apt-get install php-curl
It worked on a fresh Ubuntu 16.04 (Xenial Xerus) LTS, with lamp-server and php7. I tried with php7-curl
- it didn't work and also didn't work with php5-curl
.
You may also use the stringr
package
library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))
You may not use '^'
(starts with) in this case, to obtain the results you need
Update: appears to have stopped working since Chrome 80
Drag & Drop the '.crx' file on to the 'Extensions' page
Settings - icon > Tools > Extensions
( the 'hamburger' icon in the top-right corner )Enable Developer Mode ( toggle button in top-right corner )
Drag and drop the '.crx' extension file onto the Extensions page from step 1
( crx file should likely be in your Downloads directory )Install
Source: Chrome YouTube Downloader - install instructions
Personnaly I encountered this issue while migrating a IIS6 website into IIS7, in order to fix this issue I used this command line :
%windir%\System32\inetsrv\appcmd migrate config "MyWebSite\"
Make sure to backup your web.config
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
The compiler warnings happen on stderr
, not stdout
, which is why you don't see them when you just redirect make
somewhere else. Instead, try this if you're using Bash:
$ make &> results.txt
The &
means "redirect stdout and stderr to this location". Other shells often have similar constructs.
Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.
print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:
print "Foo %10s bar" % baz,
Yes there is a difference between the functions but the way you are using them in this case will result in the same outcome.
path.join
returns a normalized path by merging two paths together. It can return an absolute path, but it doesn't necessarily always do so.
For instance:
path.join('app/libs/oauth', '/../ssl')
resolves to app/libs/ssl
path.resolve
, on the other hand, will resolve to an absolute path.
For instance, when you run:
path.resolve('bar', '/foo');
The path returned will be /foo
since that is the first absolute path that can be constructed.
However, if you run:
path.resolve('/bar/bae', '/foo', 'test');
The path returned will be /foo/test
again because that is the first absolute path that can be formed from right to left.
If you don't provide a path that specifies the root directory then the paths given to the resolve
function are appended to the current working directory. So if your working directory was /home/mark/project/
:
path.resolve('test', 'directory', '../back');
resolves to
/home/mark/project/test/back
Using __dirname
is the absolute path to the directory containing the source file. When you use path.resolve
or path.join
they will return the same result if you give the same path following __dirname
. In such cases it's really just a matter of preference.
Did you try to give the layout_width and layout_height like the following? Since you are setting with wrap_content, the image button expands to the size of source image's height and width.
<blink>
<ImageButton>
android:id="@+id/Button01"
android:scaleType="fitXY"
android:layout_width="80dip"
android:layout_height="80dip"
android:cropToPadding="false"
android:paddingLeft="10dp"
android:src="@drawable/eye">
</ImageButton>
</blink>
The default constructor has no arguments. You need to specify a constructor:
public Friends( String firstName, String age) { ... }
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.
Here is a small example for Action and Func without using Linq:
class Program
{
static void Main(string[] args)
{
Action<int> myAction = new Action<int>(DoSomething);
myAction(123); // Prints out "123"
// can be also called as myAction.Invoke(123);
Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
Console.WriteLine(myFunc(5)); // Prints out "2.5"
}
static void DoSomething(int i)
{
Console.WriteLine(i);
}
static double CalculateSomething(int i)
{
return (double)i/2;
}
}
Try to create lombok.config
file under project base directory and provide lombok.log.fieldName
value.
Example: lombok.log.fieldName = LOG
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
My solution is to add the ID field as the LAST field in the table, thus bulk insert ignores it and it gets automatic values. Clean and simple ...
For instance, if inserting into a temp table:
CREATE TABLE #TempTable
(field1 varchar(max), field2 varchar(max), ...
ROW_ID int IDENTITY(1,1) NOT NULL)
Note that the ROW_ID
field MUST always be specified as LAST field!
I am using Windows 10 and overcame this issue by running the pip install mysql-connector
command in Windows PowerShell rather than the Command Prompt.
There is another way to install the pip3: just reinstall 3.6.
Here is a link to VeriSign's SSL Certificate Installation Checker: https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR1130
Enter your URL, click "Test this Web Server" and it will tell you if there are issues with your intermediate certificate authority.
Usually, this problem resolve with using the modulo of a number in a loop or convert a number to a string. For convert a number to a string, you may can use the function itoa, so considering the variant with the modulo of a number in a loop.
Content of a file get_digits.c
$ cat get_digits.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// return a length of integer
unsigned long int get_number_count_digits(long int number);
// get digits from an integer number into an array
int number_get_digits(long int number, int **digits, unsigned int *len);
// for demo features
void demo_number_get_digits(long int number);
int
main()
{
demo_number_get_digits(-9999999999999);
demo_number_get_digits(-10000000000);
demo_number_get_digits(-1000);
demo_number_get_digits(-9);
demo_number_get_digits(0);
demo_number_get_digits(9);
demo_number_get_digits(1000);
demo_number_get_digits(10000000000);
demo_number_get_digits(9999999999999);
return EXIT_SUCCESS;
}
unsigned long int
get_number_count_digits(long int number)
{
if (number < 0)
number = llabs(number);
else if (number == 0)
return 1;
if (number < 999999999999997)
return floor(log10(number)) + 1;
unsigned long int count = 0;
while (number > 0) {
++count;
number /= 10;
}
return count;
}
int
number_get_digits(long int number, int **digits, unsigned int *len)
{
number = labs(number);
// termination count digits and size of a array as well as
*len = get_number_count_digits(number);
*digits = realloc(*digits, *len * sizeof(int));
// fill up the array
unsigned int index = 0;
while (number > 0) {
(*digits)[index] = (int)(number % 10);
number /= 10;
++index;
}
// reverse the array
unsigned long int i = 0, half_len = (*len / 2);
int swap;
while (i < half_len) {
swap = (*digits)[i];
(*digits)[i] = (*digits)[*len - i - 1];
(*digits)[*len - i - 1] = swap;
++i;
}
return 0;
}
void
demo_number_get_digits(long int number)
{
int *digits;
unsigned int len;
digits = malloc(sizeof(int));
number_get_digits(number, &digits, &len);
printf("%ld --> [", number);
for (unsigned int i = 0; i < len; ++i) {
if (i == len - 1)
printf("%d", digits[i]);
else
printf("%d, ", digits[i]);
}
printf("]\n");
free(digits);
}
Demo with the GNU GCC
$~/Downloads/temp$ cc -Wall -Wextra -std=c11 -o run get_digits.c -lm
$~/Downloads/temp$ ./run
-9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
-10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-1000 --> [1, 0, 0, 0]
-9 --> [9]
0 --> [0]
9 --> [9]
1000 --> [1, 0, 0, 0]
10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
Demo with the LLVM/Clang
$~/Downloads/temp$ rm run
$~/Downloads/temp$ clang -std=c11 -Wall -Wextra get_digits.c -o run -lm
setivolkylany$~/Downloads/temp$ ./run
-9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
-10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-1000 --> [1, 0, 0, 0]
-9 --> [9]
0 --> [0]
9 --> [9]
1000 --> [1, 0, 0, 0]
10000000000 --> [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9999999999999 --> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
Testing environment
$~/Downloads/temp$ cc --version | head -n 1
cc (Debian 4.9.2-10) 4.9.2
$~/Downloads/temp$ clang --version
Debian clang version 3.5.0-10 (tags/RELEASE_350/final) (based on LLVM 3.5.0)
Target: x86_64-pc-linux-gnu
Thread model: posix
As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.
What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.
Using printf is like using a machine gun to fire one bullet.
Further to the above excellent comments about trusted constraints:
select * from sys.foreign_keys where is_not_trusted = 1 ;
select * from sys.check_constraints where is_not_trusted = 1 ;
An untrusted constraint, much as its name suggests, cannot be trusted to accurately represent the state of the data in the table right now. It can, however, but can be trusted to check data added and modified in the future.
Additionally, untrusted constraints are disregarded by the query optimiser.
The code to enable check constraints and foreign key constraints is pretty bad, with three meanings of the word "check".
ALTER TABLE [Production].[ProductCostHistory]
WITH CHECK -- This means "Check the existing data in the table".
CHECK CONSTRAINT -- This means "enable the check or foreign key constraint".
[FK_ProductCostHistory_Product_ProductID] -- The name of the check or foreign key constraint, or "ALL".
If you already have a wheel file (.whl) on your pc, then just go with the following code:
cd ../user
pip install file.whl
If you want to download a file from web, and then install it, go with the following in command line:
pip install package_name
or, if you have the url:
pip install http//websiteurl.com/filename.whl
This will for sure install the required file.
Note: I had to type pip2 instead of pip while using Python 2.
You need to use a graphics library. Put this in your preamble:
\usepackage{graphicx}
You can then add images like this:
\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}
This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure
and \includegraphics
. You can then refer to the image in your text using the label you gave in the figure:
And here we see figure \ref{overflow}.
Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions
Use Prim's algorithm when you have a graph with lots of edges.
For a graph with V vertices E edges, Kruskal's algorithm runs in O(E log V) time and Prim's algorithm can run in O(E + V log V) amortized time, if you use a Fibonacci Heap.
Prim's algorithm is significantly faster in the limit when you've got a really dense graph with many more edges than vertices. Kruskal performs better in typical situations (sparse graphs) because it uses simpler data structures.
Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.
Geocoder call procedure, can be located in a Helper class
public static void getAddressFromLocation(
final Location location, final Context context, final Handler handler) {
Thread thread = new Thread() {
@Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
Here is the call to this Geocoder procedure in your UI Activity:
getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());
And the handler to show the results in your UI:
private class GeocoderHandler extends Handler {
@Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}
Don't forget to put the following permission in your Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
If you don't want to use html/dom, you could use regex. I haven't tested this; but something along the lines of:
function parseHtmlEntities(str) {
return str.replace(/&#([0-9]{1,3});/gi, function(match, numStr) {
var num = parseInt(numStr, 10); // read num as normal number
return String.fromCharCode(num);
});
}
Note: this would only work for numeric html-entities, and not stuff like &oring;.
Fixed the function (some typos), test here: http://jsfiddle.net/Be2Bd/1/
I want to be clear that the following code is not good practice. You can use GOTO Label:
For Each I As Item In Items
If I = x Then
'Move to next item
GOTO Label1
End If
' Do something
Label1:
Next
Use Pypdf or its successor PyPDF2:
A Pure-Python library built as a PDF toolkit. It is capable of:
* splitting documents page by page,
* merging documents page by page,
(and much more)
Here's a sample program that works with both versions.
#!/usr/bin/env python
import sys
try:
from PyPDF2 import PdfFileReader, PdfFileWriter
except ImportError:
from pyPdf import PdfFileReader, PdfFileWriter
def pdf_cat(input_files, output_stream):
input_streams = []
try:
# First open all the files, then produce the output file, and
# finally close the input files. This is necessary because
# the data isn't read from the input files until the write
# operation. Thanks to
# https://stackoverflow.com/questions/6773631/problem-with-closing-python-pypdf-writing-getting-a-valueerror-i-o-operation/6773733#6773733
for input_file in input_files:
input_streams.append(open(input_file, 'rb'))
writer = PdfFileWriter()
for reader in map(PdfFileReader, input_streams):
for n in range(reader.getNumPages()):
writer.addPage(reader.getPage(n))
writer.write(output_stream)
finally:
for f in input_streams:
f.close()
if __name__ == '__main__':
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
pdf_cat(sys.argv[1:], sys.stdout)
For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations
key, so add CoursesComponent
in your main module declarations
as below and remove directives
from AppComponent
metadata.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, CoursesComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Edit: After Docker 1.9, the docker network
command (see below https://stackoverflow.com/a/35184695/977939) is the recommended way to achieve this.
My solution is to set up a dnsmasq on the host to have DNS record automatically updated: "A" records have the names of containers and point to the IP addresses of the containers automatically (every 10 sec). The automatic updating script is pasted here:
#!/bin/bash
# 10 seconds interval time by default
INTERVAL=${INTERVAL:-10}
# dnsmasq config directory
DNSMASQ_CONFIG=${DNSMASQ_CONFIG:-.}
# commands used in this script
DOCKER=${DOCKER:-docker}
SLEEP=${SLEEP:-sleep}
TAIL=${TAIL:-tail}
declare -A service_map
while true
do
changed=false
while read line
do
name=${line##* }
ip=$(${DOCKER} inspect --format '{{.NetworkSettings.IPAddress}}' $name)
if [ -z ${service_map[$name]} ] || [ ${service_map[$name]} != $ip ] # IP addr changed
then
service_map[$name]=$ip
# write to file
echo $name has a new IP Address $ip >&2
echo "host-record=$name,$ip" > "${DNSMASQ_CONFIG}/docker-$name"
changed=true
fi
done < <(${DOCKER} ps | ${TAIL} -n +2)
# a change of IP address occured, restart dnsmasq
if [ $changed = true ]
then
systemctl restart dnsmasq
fi
${SLEEP} $INTERVAL
done
Make sure your dnsmasq service is available on docker0
. Then, start your container with --dns HOST_ADDRESS
to use this mini dns service.
When root (sudo) permissions are required, which is usually 90%+ when using scripts, the methods in previous answers always give you root
as the answer.
To get the current "logged in" user is just as simple, but it requires accessing different variables: $SUDO_UID
and $SUDO_USER
.
They can be echoed:
echo $SUDO_UID
echo $SUDO_USER
Or assigned, for example:
myuid=$SUDO_UID
myuname=$SUDO_USER
Here is my example of how to change the arrows for Slick Carousel in React to anything you would like. First you need to set the nextArrow and prevArrow in settings to a function then return a div in that function with whatever icon you would like to use. For mine I used Font Awesome. Then you will need to add a className in your icon, you will see that in the NextArrow and PrevArrow functions. Then add the scss code to customize whatever you would like.
JSX Code:
function NextArrow(props) {
const { style, onClick } = props;
return (
<div style={{ ...style, display: "block" }} onClick={onClick}>
<FontAwesomeIcon icon={faChevronRight} size="3x" className="slick-arrow-icon-right" />
</div>
);
}
function PrevArrow(props) {
const { style, onClick } = props;
return (
<div style={{ ...style, display: "block" }} onClick={onClick}>
<FontAwesomeIcon icon={faChevronLeft} size="3x" className="slick-arrow-icon-left" />
</div>
);
}
function SlickCarouselArrowChange(props) {
var settings = {
className: "slider variable-width",
dots: true,
infinite: true,
centerMode: true,
slidesToShow: 1,
slidesToScroll: 1,
variableWidth: true,
autoplay: true,
autoplaySpeed: 2000,
nextArrow: <NextArrow />,
prevArrow: <PrevArrow />,
};
return (
<div className="slick-slider">
<Slider {...settings}>
{props.searchResults.map((image, index) => (
<div key={index}>
<img src={image.urls.small} />{" "}
</div>
))}
</Slider>
</div>
);
}
SCSS Code:
.slick-arrow-icon-left,
.slick-arrow-icon-right {
position: absolute;
display: block;
cursor: pointer;
background: transparent;
color: black;
top: 50%;
-webkit-transform: translate(0, -50%);
-ms-transform: translate(0, -50%);
transform: translate(0, -50%);
padding: 0;
border: none;
outline: none;
transition: 0.5s ease-in-out;
&:hover,
&:focus {
outline: none;
background: transparent;
color: black;
font-size: 40px;
&::before {
opacity: 1;
}
}
}
.slick-arrow-icon-left {
left: -50px;
[dir="rtl"] & {
left: auto;
right: -50px;
}
}
.slick-arrow-icon-right {
right: -50px;
[dir="rtl"] & {
left: -50px;
right: auto;
}
}
Example Link:
https://slick-carousel-arrow-change.herokuapp.com/
Source Code:
Store the names in a array and look up by the index of the month.
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
document.write("The current month is " + month[d.getMonth()]);
OP wanted two specific maps, but if you'd like to have a dynamic number of maps on one page (for instance a list of retailer locations) you need to go another route. The standard implementation of Google maps API defines the map as a global variable, this won't work with a dynamic number of maps. Here's my code to solve this without global variables:
function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 14,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Just pass the ID and address of each map to the function to plot the map and mark the address.
This code will show an error like
Table[0] can not be found!
because there will not be any table in position 0.
if (ds.Tables[0].Rows.Count == 0)
{
//
}
The best way to do this is:
input.heighttext{
padding: 20px 10px;
line-height: 28px;
}
Public Function getLoginresponce(ByVal email As String, ByVal password As String) As String
Dim requestUrl As String = "your api"
Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl), HttpWebRequest)
Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
Dim result = responseFromServer
reader.Close()
response.Close()
Return result
End Function
You have to wrap your Javascript-Code with $(document).ready(function(){});
Look this JSfiddle.
JS Code:
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
Try this! And never use trigger twice on div!
You can define function to call before the div tag.
$(function(){
$('div[onload]').trigger('onload');
});
DEMO: jsfiddle
One of the reasons why the global variable needs a prefix (called a "sigil") is because in Ruby, unlike in C, you don't have to declare your variables before assigning to them. The sigil is used as a way to be explicit about the scope of the variable.
Without a specific prefix for globals, given a statement pointNew = offset + point
inside your draw
method then offset
refers to a local variable inside the method (and results in a NameError
in this case). The same for @
used to refer to instance variables and @@
for class variables.
In other languages that use explicit declarations such as C
, Java
etc. the placement of the declaration is used to control the scope.
Though you can use First()
, Dictionaries do not have order per se. Please use OrderedDictionary instead. And then you can do FirstOrDefault
. This way it will be meaningful.
I needed the same thing and found the following working for me:
git log -n1 --pretty='format:%cd' --date=format:'%Y-%m-%d %H:%M:%S'
The --date=format
formats the date output where the --pretty
tells what to print.
I did a project on this. You can look at my github repo:
https://github.com/nishant-boro/django-rest-framework-download-expert
This module provides a simple way to serve files for download in django rest framework using Apache module Xsendfile. It also has an additional feature of serving downloads only to users belonging to a particular group
In case anyone's reading this and wanting to protect master
with client-side branch protection,
git branch -vv | grep "^\*" |grep -E '\* master |origin\/master'
will return 0
if either the local checked-out branch or its upstream remote branch is master
.
Just put this in your .git/hooks
directory's pre-commit
and update
files accordingly and Bob is your father's brother.
I wrote a little bash onliner that you can write to a script to get a friendly output:
mysql_references_to:
mysql -uUSER -pPASS -A DB_NAME -se "USE information_schema; SELECT * FROM KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = '$1' AND REFERENCED_COLUMN_NAME = 'id'\G" | sed 's/^[ \t]*//;s/[ \t]*$//' |egrep "\<TABLE_NAME|\<COLUMN_NAME" |sed 's/TABLE_NAME: /./g' |sed 's/COLUMN_NAME: //g' | paste -sd "," -| tr '.' '\n' |sed 's/,$//' |sed 's/,/./'
So the execution: mysql_references_to transaccion
(where transaccion is a random table name) gives an output like this:
carrito_transaccion.transaccion_id
comanda_detalle.transaccion_id
comanda_detalle_devolucion.transaccion_positiva_id
comanda_detalle_devolucion.transaccion_negativa_id
comanda_transaccion.transaccion_id
cuenta_operacion.transaccion_id
...
I'm not sure what vim
is doing, but it is an interesting effect. The way you're describing what you want sounds more like how macros work (:help macro
). Something like this would do what you want with macros (starting in normal-mode):
qa
: Record macro to a
register.0w
: 0
goto start of line, w
jump one word.i"<Esc>
: Enter insert-mode, insert a "
and return to normal-mode.2e
: Jump to end of second word.a"<Esc>
: Append a "
.jq
Move to next line and end macro recording.Taken together: qa0wi"<Esc>2ea"<Esc>
Now you can execute the macro with @a
, repeat last macro with @@
. To apply to the rest of the file, do something like 99@a
which assumes you do not have more than 99 lines, macro execution will end when it reaches end of file.
Here is how to achieve what you want with visual-block-mode
(starting in normal mode):
visual-block-mode
, select the lines you want to affect, G
to go to the bottom of the file.I"<Esc>
."
..
will suffice.My backtracking solution :- Sort the array , then apply the backtracking.
void _find(int arr[],int end,vector<int> &v,int start,int target){
if(target==0){
for(int i = 0;i<v.size();i++){
cout<<v[i]<<" ";
}
cout<<endl;
}
else{
for(int i = start;i<=end && target >= arr[i];i++){
v.push_back(arr[i]);
_find(arr,end,v,i+1,target-arr[i]);
v.pop_back();
}
}
}
You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php
Then in your ajax call change the success function to this:
$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');
Don't use spaces...
(Incorrect)
SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'
(Correct)
SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'
You can't use a switch statement for this as the case values cannot be evaluated expressions. For this you have to use an an if/else ...
public static void Output<T>(IEnumerable<T> dataSource) where T : class
{
dataSourceName = (typeof(T).Name);
if(string.Compare(dataSourceName, typeof(CustomerDetails).Name.ToString(), true)==0)
{
var t = 123;
}
else if (/*case 2 conditional*/)
{
//blah
}
else
{
//default case
Console.WriteLine("Test");
}
}
I also took the liberty of tidying up your conditional statement. There is no need to cast to string after calling ToString()
. This will always return a string anyway. When comparing strings for equality, bare in mind that using the == operator will result in a case sensitive comparison. Better to use string compare = 0 with the last argument to set case sensitive on/off.
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
I was able to find a simple way to achieve both scrolling behaviors.
Here is the xml for it:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:scrollbars="vertical">
<HorizontalScrollView
android:layout_width="320px" android:layout_height="fill_parent">
<TableLayout
android:id="@+id/linlay" android:layout_width="320px"
android:layout_height="fill_parent" android:stretchColumns="1"
android:background="#000000"/>
</HorizontalScrollView>
</ScrollView>
I think it's better to round the time to milliseconds before the division.
func makeTimestamp() int64 {
return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}
Here is an example program:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(unixMilli(time.Unix(0, 123400000)))
fmt.Println(unixMilli(time.Unix(0, 123500000)))
m := makeTimestampMilli()
fmt.Println(m)
fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}
func unixMilli(t time.Time) int64 {
return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}
func makeTimestampMilli() int64 {
return unixMilli(time.Now())
}
The above program printed the result below on my machine:
123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST
There are many links that lets you know how to handle post values from checkboxes in php. Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Single check box
HTML code:
<form action="checkbox-form.php" method="post">
Do you need wheelchair access?
<input type="checkbox" name="formWheelchair" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
PHP Code:
<?php
if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes')
{
echo "Need wheelchair access.";
}
else
{
echo "Do not Need wheelchair access.";
}
?>
Check box group
<form action="checkbox-form.php" method="post">
Which buildings do you want access to?<br />
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
<input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
<input type="checkbox" name="formDoor[]" value="E" />Elliot House
<input type="submit" name="formSubmit" value="Submit" />
/form>
<?php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
}
?>
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
It is possible to save a "list" of labels in keras model directly. This way the user who uses the model for predictions and does not have any other sources of information can perform the lookup himself. Here is a dummy example of how one can perform an "injection" of labels
# assume we get labels as list
labels = ["cat","dog","horse","tomato"]
# here we start building our model with input image 299x299 and one output layer
xx = Input(shape=(299,299,3))
flat = Flatten()(xx)
output = Dense(shape=(4))(flat)
# here we perform injection of labels
tf_labels = tf.constant([labels],dtype="string")
tf_labels = tf.tile(labels,[tf.shape(xx)[0],1])
output_labels = Lambda(lambda x: tf_labels,name="label_injection")(xx)
#and finaly creating a model
model=tf.keras.Model(xx,[output,output_labels])
When used for prediction, this model returns tensor of scores and tensot of string labels. Model like this can be saved to h5. In this case the file contains the labels. This model can also be exported to saved_model and used for serving in the cloud.
If you are using pandas:
df['decimals'] = df['original_number'].mod(1)
You functionally want this:
#include <sys/time.h>
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
Note that this measures in microseconds, not just seconds.
Yes, it is a bit puzzling at first.
In Ruby, methods may receive a code block in order to perform arbitrary segments of code.
When a method expects a block, it invokes it by calling the yield
function.
This is very handy, for instance, to iterate over a list or to provide a custom algorithm.
Take the following example:
I'm going to define a Person
class initialized with a name, and provide a do_with_name
method that when invoked, would just pass the name
attribute, to the block received.
class Person
def initialize( name )
@name = name
end
def do_with_name
yield( @name )
end
end
This would allow us to call that method and pass an arbitrary code block.
For instance, to print the name we would do:
person = Person.new("Oscar")
#invoking the method passing a block
person.do_with_name do |name|
puts "Hey, his name is #{name}"
end
Would print:
Hey, his name is Oscar
Notice, the block receives, as a parameter, a variable called name
(N.B. you can call this variable anything you like, but it makes sense to call it name
). When the code invokes yield
it fills this parameter with the value of @name
.
yield( @name )
We could provide another block to perform a different action. For example, reverse the name:
#variable to hold the name reversed
reversed_name = ""
#invoke the method passing a different block
person.do_with_name do |name|
reversed_name = name.reverse
end
puts reversed_name
=> "racsO"
We used exactly the same method (do_with_name
) - it is just a different block.
This example is trivial. More interesting usages are to filter all the elements in an array:
days = ["monday", "tuesday", "wednesday", "thursday", "friday"]
# select those which start with 't'
days.select do | item |
item.match /^t/
end
=> ["tuesday", "thursday"]
Or, we can also provide a custom sort algorithm, for instance based on the string size:
days.sort do |x,y|
x.size <=> y.size
end
=> ["monday", "friday", "tuesday", "thursday", "wednesday"]
I hope this helps you to understand it better.
BTW, if the block is optional you should call it like:
yield(value) if block_given?
If is not optional, just invoke it.
EDIT
@hmak created a repl.it for these examples: https://repl.it/@makstaks/blocksandyieldsrubyexample
U can also play around the tintcolor and button image to indirectly change the color.
I get consistent behaviour for both instances:
>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]
Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.
In other words, [0:10]
doesn't go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
So you want to generate date in format YYYYMMDD_hhmmss
.
As %date%
and %time%
formats are locale dependant you might need more robust ways to get a formatted date.
Here's one option:
@if (@X)==(@Y) @end /*
@cscript //E:JScript //nologo "%~f0"
@exit /b %errorlevel%
@end*/
var todayDate = new Date();
todayDate = "" +
todayDate.getFullYear() +
("0" + (todayDate.getMonth() + 1)).slice(-2) +
("0" + todayDate.getDate()).slice(-2) +
"_" +
("0" + todayDate.getHours()).slice(-2) +
("0" + todayDate.getMinutes()).slice(-2) +
("0" + todayDate.getSeconds()).slice(-2) ;
WScript.Echo(todayDate);
and if you save the script as jsdate.bat
you can assign it as a value :
for /f %%a in ('jsdate.bat') do @set "fdate=%%a"
echo %fdate%
or directly from command prompt:
for /f %a in ('jsdate.bat') do @set "fdate=%a"
Or you can use powershell which probably is the way that requires the less code:
for /f %%# in ('powershell Get-Date -Format "yyyyMMdd_HHmmss"') do set "fdate=%%#"
<script>
var today = new Date;
document.getElementById('date').innerHTML= today.toDateString();
</script>
Right click on the stored procedure and select Script Stored Procedure as | CREATE To | New Query Editor Window / Clipboard / File.
You can also do Modify when you right click on the stored procedure.
For multiple procedures at once, click on the Stored Procedures folder, hit F7 to open the Object Explorer Details pane, hold Ctrl and click to select all the ones that you want, and then right click and select Script Stored Procedure as | CREATE To.
$.fn.extend({
hasClasses: function (selectors) {
var self = this;
for (var i in selectors) {
if ($(self).hasClass(selectors[i]))
return true;
}
return false;
}
});
$('#element').hasClasses(['class1', 'class2', 'class3']);
This should do it, simple and easy.
Both would return true on Unix systems - in Unix everything is a file, including directories. But to test if that name is taken, you should check both. There might be a regular file named 'foo', which would prevent you from creating a directory name 'foo'.
Any reason they can't just click on the tab for your sheet when they want it?
Try this:
Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
On Error GoTo the_dark
Dim wsSheet As Worksheet
Dim bFoundWS As Boolean
bFoundWS = False
If inNamePrefix <> "" Then
Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
End If
If inBeforeOrAfter = iAfter Then
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
Else
Worksheets.Add(After:=wsSheet).Name = inName
End If
Else
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(Before:=Worksheets(1)).Name = inName
Else
Worksheets.Add(Before:=wsSheet).Name = inName
End If
End If
Set addSheet = findWS(inWB, inName, bFoundWS) ' just to confirm it exists and gets it handle
the_light:
Exit Function
the_dark:
MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
Err.Clear
GoTo the_light
End Function
If your problem is still there it's certainly because you are trying to compile a different version from your current settings.
For example if you set your Additional Include Directories
in Debug x64, be sure that you are compiling with the same configuration.
Check this: Build > Configuration Manager... >
There is problably something like this in your active solution configuration: Debug x86 (Win32) platform
.
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
It's almost become a trend now to have a Conv2D
followed by a ReLu
followed by a BatchNormalization
layer. So I made up a small function to call all of them at once. Makes the model definition look a whole lot cleaner and easier to read.
def Conv2DReluBatchNorm(n_filter, w_filter, h_filter, inputs):
return BatchNormalization()(Activation(activation='relu')(Convolution2D(n_filter, w_filter, h_filter, border_mode='same')(inputs)))
As asked for by @??s???? an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.
package main
import "fmt"
func main() {
var data interface{} = 2
str := fmt.Sprint(data)
fmt.Println(str)
}
Here is a simple explanation about how to create a temp dir using templates.
PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR
TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}
# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH
# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH
# create a tempdir in your systems default tmp path e.g. /tmp
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH
# Do whatever you want with your generated temp dir and var holding its path
In your onHandleSubmit
function, set your state to {city: ''}
again like this :
this.setState({ city: '' });
This is slightly modified version of @aandis answer. When it comes to raw string, prefix 'r' character before the string. For example:
sql = r"""
SELECT field1, field2, field3, field4
FROM table
WHERE condition1 = 1
AND condition2 = 2;
"""
This is recommended when your query has any special character like '\' which requires escaping and lint tools like flake8 reports it as error.
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
if (capital.touched && capital != undefined && capital.length < 1 ) {
//capital does exists
}
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
You don't need to use arrays.
JSON values can be arrays, objects, or primitives (numbers or strings).
You can write JSON like this:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}
You can use it like this:
obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix.
//I'm not sure whether you intended to do that.
In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below,
Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java
In your case the jsp name is error.jsp so the path should be something like below
Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java
in line no 124 you are trying to access a null object which results in null pointer exception.
Old Version before V6: here's the documentation
const fs = require('fs');
fs.exists('/etc/passwd', (exists) => {
console.log(exists ? 'it\'s there' : 'no passwd!');
});
// or Sync
if (fs.existsSync('/etc/passwd')) {
console.log('it\'s there');
}
UPDATE
New versions from V6: documentation for fs.stat
fs.stat('/etc/passwd', function(err, stat) {
if(err == null) {
//Exist
} else if(err.code == 'ENOENT') {
// NO exist
}
});
An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.
WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.
The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.
from datetime import datetime
a = datetime.strptime(f, "%Y-%m-%d")
If you are working with Swift 5+ you have to use UserDefaults.standard.setValue(value, forKey: key)
and to get saved data you have to use UserDefaults.standard.dictionary(forKey: key)
.
String is immutable, which means that when you create a string you can never change it. Rather it will create a new string to store the new value, and this can be inefficient if you need to change the value of a string variable a lot.
StringBuilder can be used to simulate a mutable string, so it is good for when you need to change a string a lot.
Spring exposes the current HttpServletRequest
object (as well as the current HttpSession
object) through a wrapper object of type ServletRequestAttributes
. This wrapper object is bound to ThreadLocal and is obtained by calling the static
method RequestContextHolder.currentRequestAttributes()
.
ServletRequestAttributes
provides the method getRequest()
to get the current request, getSession()
to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:
HttpServletRequest curRequest =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Note that the RequestContextHolder.currentRequestAttributes()
method returns an interface and needs to be typecasted to ServletRequestAttributes
that implements the interface.
Spring Javadoc: RequestContextHolder | ServletRequestAttributes
There is a single line solution for those who use jQuery:
$("link[rel*='icon']").prop("href",'https://www.stackoverflow.com/favicon.ico');
I think the point is that there is no need to quit the app unless you have buggy software. Android quits the app when the user is not using it and the device needs more memory. If you have an app that needs to run a service in the background, you will likely want a way to turn the service off.
For example, Google Listen continues to play podcast when the app is not visible. But there is always the pause button to turn the podcast off when the user is done with it. If I remember correctly, Listen, even puts a shortcut in the notification bar so you can always get to the pause button quickly. Another example is an app like a twitter app for instance which constantly polls a service on the internet. These types of apps should really allow the user to choose how often to poll the server, or whether even to poll in a background thread.
If you need to have code that runs on exit, you can override onPause(), onStop(), or onDestroy() as appropriate. http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
IEnumerable is refering to a collection but IQueryable is just a query and it will be generated inside a Expression Tree.we will run this query to get data from database.
I think here "inflating a view" means fetching the layout.xml file drawing a view specified in that xml file and POPULATING ( = inflating ) the parent viewGroup with the created View.
If you're happy to use Apache classes, you could use org.apache.commons.text.RandomStringGenerator
(Apache Commons Text).
Example:
RandomStringGenerator randomStringGenerator =
new RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
.build();
randomStringGenerator.generate(12); // toUpperCase() if you want
Since Apache Commons Lang 3.6, RandomStringUtils
is deprecated.
hmm, I don't know if I would say that online materials are useless, but I do agree that there is something about books. Maybe they are better written, or maybe it is the act of forking over $50 that makes you more inclined to study the material.
Either way, I agree that books should be part of this question. If anyone has any suggestions for books for languages I will edit the post with the best suggestions.
By Using like
use css and font same location
@font-face {
font-family: 'Material-Design-Icons';
src: url('Material-Design-Icons.eot');
src: url('Material-Design-Icons.eot?#iefix') format('embedded-opentype'),
url('Material-Design-Icons.woff2') format('woff2'),
url('Material-Design-Icons.woff') format('woff'),
url('Material-Design-Icons.ttf') format('truetype'),
url('Material-Design-Icons.svg#ge_dinar_oneregular') format('svg');
font-weight: normal;
font-style: normal;
}
You need the table name/alias in the SELECT
part (maybe (vg.id, name)
) :
SELECT (vg.id, name) FROM v_groups vg
inner join people2v_groups p2vg on vg.id = p2vg.v_group_id
where p2vg.people_id =0;
The following are totally acceptable in python:
int
float
float
int
float
But you get a ValueError
if you pass a string representation of a float into int
, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int
, as @katyhuff points out above, you can convert to a float first, then to an integer:
>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
5
I just tested benmajor's GitHub jQuery Touch Events plugin for both 1.4 and 1.7+ versions of jQuery. It is lightweight and works perfectly with both on
and bind
while providing support for an exhaustive set of touch events.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
sed is a stream editor. I would say try man sed.If you didn't find this man page in your system refer this URL:
I know this is old question but...
As Raymond Hettinger said, it should be called while/no_break
instead of while/else
.
I find it easy to understeand if you look at this snippet.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
if n == 0:
print n
Now instead of checking condition after while loop we can swap it with else
and get rid of that check.
n = 5
while n > 0:
print n
n -= 1
if n == 2:
break
else: # read it as "no_break"
print n
I always read it as while/no_break
to understand the code and that syntax makes much more sense to me.
This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.
Code below serves as an explanation:
//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
setTimeout (function(){
console.log ('using callback:');
let mockResponseData = '{"data": "something for callback"}';
if (callback){
callback (mockResponseData);
}
}, 2000);
}
function b (dataJson) {
let dataObject = JSON.parse (dataJson);
console.log (dataObject.data);
}
a (b);
//rewriting above code using Promise
//function c is asynchronous function
function c () {
return new Promise(function (resolve, reject) {
setTimeout (function(){
console.log ('using promise:');
let mockResponseData = '{"data": "something for promise"}';
resolve(mockResponseData);
}, 2000);
});
}
c().then (b);
Contributing my solution to the noise. trim
defaults to creating a new string and returning the modified one while trim_in_place
modifies the string passed to it. The trim
function supports c++11 move semantics.
#include <string>
// modifies input string, returns input
std::string& trim_left_in_place(std::string& str) {
size_t i = 0;
while(i < str.size() && isspace(str[i])) { ++i; };
return str.erase(0, i);
}
std::string& trim_right_in_place(std::string& str) {
size_t i = str.size();
while(i > 0 && isspace(str[i - 1])) { --i; };
return str.erase(i, str.size());
}
std::string& trim_in_place(std::string& str) {
return trim_left_in_place(trim_right_in_place(str));
}
// returns newly created strings
std::string trim_right(std::string str) {
return trim_right_in_place(str);
}
std::string trim_left(std::string str) {
return trim_left_in_place(str);
}
std::string trim(std::string str) {
return trim_left_in_place(trim_right_in_place(str));
}
#include <cassert>
int main() {
std::string s1(" \t\r\n ");
std::string s2(" \r\nc");
std::string s3("c \t");
std::string s4(" \rc ");
assert(trim(s1) == "");
assert(trim(s2) == "c");
assert(trim(s3) == "c");
assert(trim(s4) == "c");
assert(s1 == " \t\r\n ");
assert(s2 == " \r\nc");
assert(s3 == "c \t");
assert(s4 == " \rc ");
assert(trim_in_place(s1) == "");
assert(trim_in_place(s2) == "c");
assert(trim_in_place(s3) == "c");
assert(trim_in_place(s4) == "c");
assert(s1 == "");
assert(s2 == "c");
assert(s3 == "c");
assert(s4 == "c");
}
Just got this problem on a development machine (production works just fine). I modify my config in IIS to allow anonymous access and put my name and password as credential.
Not the best way I am sure but it works for testing purposes.
Syntax:
$(selector).text()
content
: $(selector).text(content)
$(selector).text(function(index, curContent))
If you should remove all values from list a, which are present in list b.
def list_diff(a, b):
r = []
for i in a:
if i not in b:
r.append(i)
return r
list_diff([1,2,2], [1])
Result: [2,2]
or
def list_diff(a, b):
return [x for x in a if x not in b]
That's just the way TD's are. I believe It may be because the TD element's 'display' property is inherently set to 'table-cell' rather than 'block'.
In your case, the alternative may be to wrap the contents of the TD in a DIV and apply width and overflow to the DIV.
<td style="border: solid green 1px; width:200px;">
<div style="width:200px; overflow:hidden;">
This_is_a_terrible_example_of_thinking_outside_the_box.
</div>
</td>
There may be some padding or cellpadding issues to deal with, and you're better off removing the inline styles and using external css instead, but this should be a start.
The first step you create Filter using @Pipe
in your component.ts file:
your.component.ts
import { Component, Pipe, PipeTransform, Injectable } from '@angular/core';
import { Person} from "yourPath";
@Pipe({
name: 'searchfilter'
})
@Injectable()
export class SearchFilterPipe implements PipeTransform {
transform(items: Person[], value: string): any[] {
if (!items || !value) {
return items;
}
console.log("your search token = "+value);
return items.filter(e => e.firstName.toLowerCase().includes(value.toLocaleLowerCase()));
}
}
@Component({
....
persons;
ngOnInit() {
//inicial persons arrays
}
})
And data structure of Person object:
person.ts
export class Person{
constructor(
public firstName: string,
public lastName: string
) { }
}
In your view in html file:
your.component.html
<input class="form-control" placeholder="Search" id="search" type="text" [(ngModel)]="searchText"/>
<table class="table table-striped table-hover">
<colgroup>
<col span="1" style="width: 50%;">
<col span="1" style="width: 50%;">
</colgroup>
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of persons | searchfilter:searchText">
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</tbody>
</table>
D = {}
is a dictionary not set.
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
To answer your second query re. how encoding works, Joel Spolsky wrote a great introductory article on this. Strongly recommended.
You can achieve with following way
this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
Standing on the shoulders of the other poor creatures trodding through this muck, I was able to follow these steps to get back up and running after an upgrade to Yosemite:
Assuming you've used home-brew to install and upgrade Postgres, you can perform the following steps.
Stop current Postgres server:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
Initialize a new 9.4 database:
initdb /usr/local/var/postgres9.4 -E utf8
Install postgres 9.3 (as it was no longer present on my machine):
brew install homebrew/versions/postgresql93
Add directories removed during Yosemite upgrade:
mkdir -p /usr/local/var/postgres/{pg_tblspc,pg_twophase,pg_stat_tmp}/touch /usr/local/var/postgres/{pg_tblspc,pg_twophase,pg_stat_tmp}/.keep
run pg_upgrade
:
pg_upgrade -v -d /usr/local/var/postgres -D /usr/local/var/postgres9.4 -b /usr/local/Cellar/postgresql93/9.3.5/bin/ -B /usr/local/Cellar/postgresql/9.4.0/bin/
Move new data into place:
cd /usr/local/var
mv postgres postgres9.3
mv postgres9.4 postgres
Restart Postgres:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
Check /usr/local/var/postgres/server.log
for details and to make sure the new server started properly.
Finally, re-install related libraries?
pip install --upgrade psycopg2
gem uninstall pg
gem install pg
I am not aware of any libraries to do this (but I am sure there are many that can) but if you can already create HTML from the crystal report why not use XSLT to clean up the markup?
Its better to always encode spaces as %20, not as "+".
It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.
Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".
I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
You can also use the drop_duplicates() instead of unique()
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a
I don´t think you can have two Id´s but it should be possible. Using the same id twice is a different case... like two people using the same passport. However one person could have multiple passports... Came looking for this since I have a situation where a single employee can have several functions. Say "sysadm" and "team coordinator" having the id="sysadm teamcoordinator" would let me reference them from other pages so that employees.html#sysadm and employees.html#teamcoordinator would lead to the same place... One day somebody else might take over the team coordinator function while the sysadm remains the sysadm... then I only have to change the ids on the employees.html page ... but like I said - it doesn´t work :(
Another idea: Compensate for your margin on the opposite side of the div.
For the side with the spacing you are looking to achieve as an example: 10px, and for the opposing side, compensate with a -10px. It works for me. This likely won't work in all scenarios, but depending on your layout and spacing of other elements, it might work great.