in my case, The error message was
Module not found: Error: Can't resolve '/components/body
While everything was in the correct directory.
I found that renaming body.jsx
to body.js
resolve the issue!
So I added this code in webpack.config.js
to resolve jsx
as js
module.exports = {
//...
resolve: {
extensions: ['.js', '.jsx']
}
};
And then build error gone!
In launchSettings.json, under iisSettings, set anonymousAuthentication to true:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:4200/",
"sslPort": 0
}
}
Then, in Startup.cs, under ConfigureServices, before services.AddMvc, add:
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
builder
.AllowAnyOrigin()
.WithHeaders(HeaderNames.AccessControlAllowHeaders, "Content-Type")
.AllowAnyMethod()
.AllowCredentials();
}));
and then, in configure method, before app.UseMvc() add:
app.UseCors("ApiCorsPolicy");
I am using the Asp.Net Core angular template project with an Angular 4 front end and webpack. I had to use '/dist/assets/images/' in front of the image name, and store the image in the assets/images directory in the dist directory. eg:
<img class="img-responsive" src="/dist/assets/images/UnitBadge.jpg">
I had to figure it out myself but some svgs your need to match the viewBox & width+height in.
E.g. if it already has width="x"
height="y"
then =>
add <svg ... viewBox="0 0 [width] [height]">
and the opposite.
After that it will scale with <svg ... style="width: xxx; height: yyy;">
If you want to bind a string to the src
attribute, you should wrap it on single quotes:
<img v-bind:src="'/static/img/clear.gif'">
<!-- or shorthand -->
<img :src="'/static/img/clear.gif'">
IMO you do not need to bind a string, you could use the simple way:
<img src="/static/img/clear.gif">
Check an example about the image preload here: http://codepen.io/pespantelis/pen/RWVZxL
You can get a view for a particular position on a recyclerview using the following
int position = 2;
RecyclerView.ViewHolder viewHolder = recyclerview.findViewHolderForItemId(position);
View view = viewHolder.itemView;
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
CSS only (no icon sets) Codepen
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
<!-- <a class="navbar-brand" href="#">_x000D_
<img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
Bootstrap_x000D_
</a> -->_x000D_
<!-- https://stackoverflow.com/questions/26317679 -->_x000D_
<a class="nav-link" href="#">_x000D_
<div id="navBars">_x000D_
<input type="checkbox" /><span></span>_x000D_
<span></span>_x000D_
<span></span>_x000D_
</div>_x000D_
</a>_x000D_
<!-- /26317679 -->_x000D_
<div class="collapse navbar-collapse" id="navbarNav">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
<li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
In the latest R (3.2.3) there is a bug, preventing it some times from finding correct package. The workaround is to set repository manually:
install.packages("lubridate", dependencies=TRUE, repos='http://cran.rstudio.com/')
Found solution in other question
this code will work ,
.navbar .navbar-nav > li .navbar-item ,
.navbar .navbar-brand{
color: red;
}
paste in your css and run if you have a element below
eg .
<li>@Html.ActionLink("Login", "Login", "Home", new { area = "" },
new { @class = "navbar-item" })</li>
OR
<li> <button class="navbar-item">hi</button></li>
use now() in any cell. then use that cell as a "dummy" parameter in a function. when now() changes every minute the formula recalculates. example: someFunction(a1,b1,c1) * (cell with now() / cell with now())
Instead your both functions use toggle
function with following body
this[target].parentNode.style.display = 'none'
this[source].parentNode.style.display = 'block'
function toggle(target, source) {
this[target].parentNode.style.display = 'none'
this[source].parentNode.style.display = 'block'
}
_x000D_
<button onClick="toggle('target', 'replace_target')">View Portfolio</button>
<button onClick="toggle('replace_target', 'target')">View Results</button>
<div>
<span id="target">div1</span>
</div>
<div style="display:none">
<span id="replace_target">div2</span>
</div>
_x000D_
Yes, you have to get all records, update them and then call SaveChanges
.
Just remember that modifying the padding or margins on any bootstrap grid elements is likely to create overflowing elements at some point at lower screen-widths.
If that happens just remember to use CSS media queries and only include the margins at screen-widths that can handle it.
In keeping with the mobile-first approach of the framework you are working within (bootstrap) it is better to add the padding at widths which can handle it, rather than excluding it at widths which can't.
@media (min-width: 992px){
.navbar li {
margin-left : 1em;
margin-right : 1em;
}
}
I suspect looking at the excerpt that the function trustSrc
from trustSrc(currentProject.url)
is not defined in the controller.
You need to inject the $sce
service in the controller and trustAsResourceUrl
the url
there.
In the controller:
function AppCtrl($scope, $sce) {
// ...
$scope.setProject = function (id) {
$scope.currentProject = $scope.projects[id];
$scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
}
}
In the Template:
<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>
You need also to set .min-height: 0px;
please see bellow:
.navbar-inner {
min-height: 0px;
}
.navbar-brand,
.navbar-nav li a {
line-height: 150px;
height: 150px;
padding-top: 0;
}
If you set .min-height: 0px;
then you can choose any height you want!
Good Luck!
You can use np.c_
np.c_[[1,2,3], [4,5,6]]
It will give you:
np.array([[1,4], [2,5], [3,6]])
I could remove the error (Run-time error '1004'. Application-defined or operation-defined error) by defining the counters as Single
Better to use default collapse.js methods (V3 docs, V4 docs):
$('.nav a').click(function(){
$('.nav-collapse').collapse('hide');
});
FileReaderJS can read the files for you. You get the file content inside onLoad(e)
event handler as e.target.result
.
This can not be done easily. There's no way to make an NVARCHAR
parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.
Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:
CREATE TABLE #TempTable (ID INT)
WHILE LEN(@PortfolioID) > 0
BEGIN
IF NOT <@PortfolioID contains Comma>
BEGIN
INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
SET @PortfolioID = ''
END ELSE
BEGIN
INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
SET @PortfolioID = <Everything after the next comma>
END
END
Then, change your condition to
WHERE PortfolioId IN (SELECT ID FROM #TempTable)
EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:
You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:
The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.
The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.
The query must use an IN clause to specify the parameter.
This will do the trick
.gallery-item
{
opacity:1;
}
.gallery-item:hover
{
opacity:0;
transition: opacity .2s ease-out;
-moz-transition: opacity .2s ease-out;
-webkit-transition: opacity .2s ease-out;
-o-transition: opacity .2s ease-out;
}
Add ID current
for active/current page:
<div class="menuBar">
<ul>
<li id="current"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
#current a { color: #ff0000; }
Vohuman's answer lead me to my own implementation:
$(document).on("vclick", ".className", function() {
// Whatever you want to do
});
Instead of:
$(document).ready(function($) {
$('.className').click(function(){
// Whatever you want to do
});
});
I hope this helps!
zIndex
is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index
.
you forgot .css("attr","value"). use ' or " in both, attr and val. so,
.css("z-index","3000");
Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes
https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task
Yes, window.onfocus
and window.onblur
should work for your scenario:
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
if you want to scroll just only some div, can use the div id instead of 'html, body'
$('html, body').animate(...
use
$('#mydivid').animate(...
An <iframe>
gives you a complete window to work with. The most direct way to do what you want is to have your server give you a complete page that only contains the fragment you want to show.
As an alternative, you could just use a simple <div>
and use the jQuery "load" function to load the whole page and pluck out just the section you want:
$('#target-div').load('http://www.mywebsite.com/portfolio.php #portfolio-sports');
There may be other things you need to do, and a significant difference is that the content will become part of the main page instead of being segregated into a separate window.
Here is one simple PHP Script which gets exchange rate between GBP and USD
<?php
$amount = urlencode("1");
$from_GBP0 = urlencode("GBP");
$to_usd= urlencode("USD");
$Dallor = "hl=en&q=$amount$from_GBP0%3D%3F$to_usd";
$US_Rate = file_get_contents("http://google.com/ig/calculator?".$Dallor);
$US_data = explode('"', $US_Rate);
$US_data = explode(' ', $US_data['3']);
$var_USD = $US_data['0'];
echo $to_usd;
echo $var_USD;
echo '<br/>';
?>
Google currency rates are not accurate google itself says ==> Google cannot guarantee the accuracy of the exchange rates used by the calculator. You should confirm current rates before making any transactions that could be affected by changes in the exchange rates. Foreign currency rates provided by Citibank N.A. are displayed under licence. Rates are for information purposes only and are subject to change without notice. Rates for actual transactions may vary and Citibank is not offering to enter into any transaction at any rate displayed.
Using Concat on the group by will work
SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30
Had same problem, i fix it like that :
reset permission on id_rsa* only for current user no group no other
chmod o-rwx ~/.ssh/id*
chmod G-rwx ~/.ssh/id*
ls -lart ~/.ssh/
-rw------- 1 jenkins nogroup 398 avril 3 09:34 id_rsa.pub
-rw------- 1 jenkins nogroup 1675 avril 3 09:34 id_rsa
And clear ~/.ssh/know_hosts
Now Connect as jenkins
sudo su jenkins
Try the jenkins commands
git ls-remote -h [email protected]:user/project.git HEAD
If no problem appears, now jenkins will be able to connect the repo (for me ^^ at least)
Have you tried overflow-y:auto
? It is not exactly what you want, as the scrollbar will appear only when needed.
Use the following code:
$(document).ready(function() {
$('.date-pick').datepicker( {
onSelect: function(date) {
alert(date)
},
selectWeek: true,
inline: true,
startDate: '01/01/2000',
firstDay: 1,
});
});
You can adjust the parameters yourself :-)
As stated in 1.7.12 Release Notes, you may use
$ git rebase -i --root
These two need to go together for it to work. Been scratching my head for a while.
numberView.textAlignment = View.TEXT_ALIGNMENT_CENTER
numberView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
Oh, the fun of a snippet!
if (!function_exists('base_url')) {
function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
if (isset($_SERVER['HTTP_HOST'])) {
$http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
$hostname = $_SERVER['HTTP_HOST'];
$dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
$core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
$core = $core[0];
$tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
$end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
$base_url = sprintf( $tmplt, $http, $hostname, $end );
}
else $base_url = 'http://localhost/';
if ($parse) {
$base_url = parse_url($base_url);
if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
}
return $base_url;
}
}
It has beautiful returns like:
// A URL like http://stackoverflow.com/questions/189113/how-do-i-get-current-page-full-url-in-php-on-a-windows-iis-server:
echo base_url(); // Will produce something like: http://stackoverflow.com/questions/189113/
echo base_url(TRUE); // Will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); //Will produce something like: http://stackoverflow.com/questions/
// And finally:
echo base_url(NULL, NULL, TRUE);
// Will produce something like:
// array(3) {
// ["scheme"]=>
// string(4) "http"
// ["host"]=>
// string(12) "stackoverflow.com"
// ["path"]=>
// string(35) "/questions/189113/"
// }
For those using asyncio, an easy way is to use asyncio.wait_for()
:
async def my_loop():
res = False
while not res:
res = await do_something()
await asyncio.wait_for(my_loop(), 10)
A PIVOT
used to rotate the data from one column into multiple columns.
For your example here is a STATIC Pivot meaning you hard code the columns that you want to rotate:
create table temp
(
id int,
teamid int,
userid int,
elementid int,
phaseid int,
effort decimal(10, 5)
)
insert into temp values (1,1,1,3,5,6.74)
insert into temp values (2,1,1,3,6,8.25)
insert into temp values (3,1,1,4,1,2.23)
insert into temp values (4,1,1,4,5,6.8)
insert into temp values (5,1,1,4,6,1.5)
select elementid
, [1] as phaseid1
, [5] as phaseid5
, [6] as phaseid6
from
(
select elementid, phaseid, effort
from temp
) x
pivot
(
max(effort)
for phaseid in([1], [5], [6])
)p
Here is a SQL Demo with a working version.
This can also be done through a dynamic PIVOT where you create the list of columns dynamically and perform the PIVOT.
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.phaseid)
FROM temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT elementid, ' + @cols + ' from
(
select elementid, phaseid, effort
from temp
) x
pivot
(
max(effort)
for phaseid in (' + @cols + ')
) p '
execute(@query)
The results for both:
ELEMENTID PHASEID1 PHASEID5 PHASEID6
3 Null 6.74 8.25
4 2.23 6.8 1.5
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
Surround what you want to be bold with:
<span style="font-weight:bold">Your bold text</span>
This would go inside your <td>
tag.
In Swift (version 2.0):
class func jsonStringWithJSONObject(jsonObject: AnyObject) throws -> String? {
let data: NSData? = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)
var jsonStr: String?
if data != nil {
jsonStr = String(data: data!, encoding: NSUTF8StringEncoding)
}
return jsonStr
}
You can use readfile and output the image headers which you can get from getimagesize like this:
$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: {$imginfo['mime']}");
readfile($remoteImage);
The reason you should use readfile here is that it outputs the file directly to the output buffer where as file_get_contents will read the file into memory which is unnecessary in this content and potentially intensive for large files.
You might want to try this.
for name in /home/ken/foo/bar/*
do
echo $name
done
You can get abs path using for
loop and echo
simply without find
.
Try this approach using the newer str.format
syntax:
line_new = '{:>12} {:>12} {:>12}'.format(word[0], word[1], word[2])
And here's how to do it using the old %
syntax (useful for older versions of Python that don't support str.format
):
line_new = '%12s %12s %12s' % (word[0], word[1], word[2])
select * from tableName where columnName is null
From a comment:
I want to sort each set.
That's easy. For any set s
(or anything else iterable), sorted(s)
returns a list of the elements of s
in sorted order:
>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']
Note that sorted
is giving you a list
, not a set
. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2}
and {2, 1}
are the same set.
You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).
The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key
function:
>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']
For more information, see the Sorting HOWTO in the official docs.
* See the comments for exceptions.
I think this is the best way to do it !
<html>
<body onload="document.getElementById('redirectForm').submit()">
<form id='redirectForm' method='POST' action='/done.html'>
<input type='hidden' name='status' value='complete'/>
<input type='hidden' name='id' value='0u812'/>
<input type='submit' value='Please Click Here To Continue'/>
</form>
</body>
</html>
This will be almost instantaneous and user won't see anything !
Error shows that script does not exists
The file does not exists. check your full path
C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified
Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path
Confirm that script exists.
Into jenkins script, do the following to confirm that you do have the file
cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh
try:
r = requests.post(url, data=data, verify='/path/to/public_key.pem')
Tried everything but on Visual Studio 2015 Community edition I got it working when I installed MySQL for Visual Studio 1.2.4+ from http://dev.mysql.com/downloads/windows/visualstudio/ At time of writing I could download 1.2.6 which worked for me.
Release notes of 1.2.4 which adds support for VS2015 can be found at http://forums.mysql.com/read.php?3,633391
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
I notice this question gets quite a lot of views so I'll first address a question you didn't ask!
Regarding the title. To achieve a "Sql Union All with “distinct”" then simply replace UNION ALL
with UNION
. This has the effect of removing duplicates.
For your specific question, given the clarification "The first query should have "priority", so duplicates should be removed from bottom" you can use
SELECT col1,
col2,
MIN(grp) AS source_group
FROM (SELECT 1 AS grp,
col1,
col2
FROM t1
UNION ALL
SELECT 2 AS grp,
col1,
col2
FROM t2) AS t
GROUP BY col1,
col2
ORDER BY MIN(grp),
col1
The solution is to add height:100%;
to all the parent elements of your .wrapper-div
as well. So:
html{
height: 100%;
}
body{
margin:0;
padding:0;
overflow:hidden;
height:100%;
}
#container{
width:1000px;
margin:0 auto;
height:100%;
}
Counting number of letters in a string using regex.
import re
s = 'The grey old fox is an idiot'
count = len(re.findall('[a-zA-Z]',s))
On CodeProject, there is an article that briefly discusses pros and cons of testing private methods. It then provides some reflection code to access private methods (similar to the code Marcus provides above.) The only issue I've found with the sample is that the code doesn't take into account overloaded methods.
You can find the article here:
This solution doesn't require you to put a scrollable class on all your scrollable divs so is more general. Scrolling is allowed on all elements which are, or are children of, INPUT elements contenteditables and overflow scroll or autos.
I use a custom selector and I also cache the result of the check in the element to improve performance. No need to check the same element every time. This may have a few issues as only just written but thought I'd share.
$.expr[':'].scrollable = function(obj) {
var $el = $(obj);
var tagName = $el.prop("tagName");
return (tagName !== 'BODY' && tagName !== 'HTML') && (tagName === 'INPUT' || $el.is("[contentEditable='true']") || $el.css("overflow").match(/auto|scroll/));
};
function preventBodyScroll() {
function isScrollAllowed($target) {
if ($target.data("isScrollAllowed") !== undefined) {
return $target.data("isScrollAllowed");
}
var scrollAllowed = $target.closest(":scrollable").length > 0;
$target.data("isScrollAllowed",scrollAllowed);
return scrollAllowed;
}
$('body').bind('touchmove', function (ev) {
if (!isScrollAllowed($(ev.target))) {
ev.preventDefault();
}
});
}
Work with libraries. Make a library called nib, install it using setup.py, let it reside in site-packages and your problems are solved. You don't have to stuff everything you make in a single package. Break it up to pieces.
to creating some thing that is running like service you can use this thing :
The first thing that you must do is installing the Cement framework: Cement frame work is a CLI frame work that you can deploy your application on it.
command line interface of the app :
interface.py
from cement.core.foundation import CementApp
from cement.core.controller import CementBaseController, expose
from YourApp import yourApp
class Meta:
label = 'base'
description = "your application description"
arguments = [
(['-r' , '--run'],
dict(action='store_true', help='Run your application')),
(['-v', '--version'],
dict(action='version', version="Your app version")),
]
(['-s', '--stop'],
dict(action='store_true', help="Stop your application")),
]
@expose(hide=True)
def default(self):
if self.app.pargs.run:
#Start to running the your app from there !
YourApp.yourApp()
if self.app.pargs.stop:
#Stop your application
YourApp.yourApp.stop()
class App(CementApp):
class Meta:
label = 'Uptime'
base_controller = 'base'
handlers = [MyBaseController]
with App() as app:
app.run()
YourApp.py class:
import threading
class yourApp:
def __init__:
self.loger = log_exception.exception_loger()
thread = threading.Thread(target=self.start, args=())
thread.daemon = True
thread.start()
def start(self):
#Do every thing you want
pass
def stop(self):
#Do some things to stop your application
Keep in mind that your app must run on a thread to be daemon
To run the app just do this in command line
python interface.py --help
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
According to this site, this is supported in the playbackRate
and defaultPlaybackRate
attributes, accessible via the DOM. Example:
/* play video twice as fast */
document.querySelector('video').defaultPlaybackRate = 2.0;
document.querySelector('video').play();
/* now play three times as fast just for the heck of it */
document.querySelector('video').playbackRate = 3.0;
The above works on Chrome 43+, Firefox 20+, IE 9+, Edge 12+.
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause
:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
2019 modern browsers update
This is the approach I'd now recommend with a few caveats:
fetch('https://jsonplaceholder.typicode.com/todos/1')_x000D_
.then(resp => resp.blob())_x000D_
.then(blob => {_x000D_
const url = window.URL.createObjectURL(blob);_x000D_
const a = document.createElement('a');_x000D_
a.style.display = 'none';_x000D_
a.href = url;_x000D_
// the filename you want_x000D_
a.download = 'todo-1.json';_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
window.URL.revokeObjectURL(url);_x000D_
alert('your file has downloaded!'); // or you know, something with better UX..._x000D_
})_x000D_
.catch(() => alert('oh no!'));
_x000D_
2012 original jQuery/iframe/cookie based approach
I have created the jQuery File Download plugin (Demo) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:
Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too
User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications
successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation
In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this. Hope this helps someone!
Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.
$.fileDownload('some/file.pdf')
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });
If you want to display an icon and are using a dark theme. Which means the icon provided above doesn't look that great. Then you can find the icon here
C:\Program Files\Git\mingw64\share\git\git-for-windows
I copied it into.
%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState
and named it git-bash_32px
as suggested above.
Control the opacity with CTRL + SHIFT + scrolling.
{
"acrylicOpacity" : 0.75,
"closeOnExit" : true,
"colorScheme" : "Campbell",
"commandline" : "\"%PROGRAMFILES%\\git\\usr\\bin\\bash.exe\" -i -l",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 10,
"guid" : "{73225108-7633-47ae-80c1-5d00111ef646}",
"historySize" : 9001,
"icon" : "ms-appdata:///roaming/git-bash_32px.ico",
"name" : "Bash",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"startingDirectory" : "%USERPROFILE%",
"useAcrylic" : true
},
My fix for this issue was to separate the primary key with the foreign key. If you are using eclipse and made the above changes please remember to refresh the database explorer. Then recreate the entities from the tables.
You can use BETWEEN
:
DELETE FROM table
where id between 163 and 265
I'm new to git but it seems that if I do git checkout for each directory then it works. Also, the sparse-checkout file needs to have a trailing slash after every directory as indicated. Someone more experience please confirm that this will work.
Interestingly, if you checkout a directory not in the sparse-checkout file it seems to make no difference. They don't show up in git status and git read-tree -m -u HEAD doesn't cause it to be removed. git reset --hard doesn't cause the directory to be removed either. Anyone more experienced care to comment on what git thinks of directories that are checked out but which are not in the sparse checkout file?
This worked for me:
chmod 700 .ssh
chmod 600 .ssh/id_rsa
chmod 644 .ssh/id_rsa.pub
Then, type this:
ssh-add ~/.ssh/id_rsa
To add to the answers here, I think it's worth considering the opposite question in conjunction with this, viz. why did C allow fall-through in the first place?
Any programming language of course serves two goals:
The creation of any programming language is therefore a balance between how to best serve these two goals. On the one hand, the easier it is to turn into computer instructions (whether those are machine code, bytecode like IL, or the instructions are interpreted on execution) then more able that process of compilation or interpretation will be to be efficient, reliable and compact in output. Taken to its extreme, this goal results in our just writing in assembly, IL, or even raw op-codes, because the easiest compilation is where there is no compilation at all.
Conversely, the more the language expresses the intention of the programmer, rather than the means taken to that end, the more understandable the program both when writing and during maintenance.
Now, switch
could always have been compiled by converting it into the equivalent chain of if-else
blocks or similar, but it was designed as allowing compilation into a particular common assembly pattern where one takes a value, computes an offset from it (whether by looking up a table indexed by a perfect hash of the value, or by actual arithmetic on the value*). It's worth noting at this point that today, C# compilation will sometimes turn switch
into the equivalent if-else
, and sometimes use a hash-based jump approach (and likewise with C, C++, and other languages with comparable syntax).
In this case there are two good reasons for allowing fall-through:
It just happens naturally anyway: if you build a jump table into a set of instructions, and one of the earlier batches of instructions doesn't contain some sort of jump or return, then execution will just naturally progress into the next batch. Allowing fall-through was what would "just happen" if you turned the switch
-using C into jump-table–using machine code.
Coders who wrote in assembly were already used to the equivalent: when writing a jump table by hand in assembly, they would have to consider whether a given block of code would end with a return, a jump outside of the table, or just continue on to the next block. As such, having the coder add an explicit break
when necessary was "natural" for the coder too.
At the time therefore, it was a reasonable attempt to balance the two goals of a computer language as it relates to both the produced machine code, and the expressiveness of the source code.
Four decades later though, things are not quite the same, for a few reasons:
switch
either being turned into if-else
because it was deemed the approach likely to be most efficient, or else turned into a particularly esoteric variant of the jump-table approach are higher. The mapping between the higher- and lower-level approaches is not as strong as it once was.switch
blocks used a fall-through other than multiple labels on the same block, and it was thought that the use-case here meant that this 3% was in fact much higher than normal). So the language as studied make the unusual more readily catered-to than the common.Related to those last two points, consider the following quote from the current edition of K&R:
Falling through from one case to another is not robust, being prone to disintegration when the program is modified. With the exception of multiple labels for a single computation, fall-throughs should be used sparingly, and commented.
As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.
So, from the horse's mouth, fall-through in C is problematic. It's considered good practice to always document fall-throughs with comments, which is an application of the general principle that one should document where one does something unusual, because that's what will trip later examination of the code and/or make your code look like it has a novice's bug in it when it is in fact correct.
And when you think about it, code like this:
switch(x)
{
case 1:
foo();
/* FALLTHRU */
case 2:
bar();
break;
}
Is adding something to make the fall-through explicit in the code, it's just not something that can be detected (or whose absence can be detected) by the compiler.
As such, the fact that on has to be explicit with fall-through in C# doesn't add any penalty to people who wrote well in other C-style languages anyway, since they would already be explicit in their fall-throughs.†
Finally, the use of goto
here is already a norm from C and other such languages:
switch(x)
{
case 0:
case 1:
case 2:
foo();
goto below_six;
case 3:
bar();
goto below_six;
case 4:
baz();
/* FALLTHRU */
case 5:
below_six:
qux();
break;
default:
quux();
}
In this sort of case where we want a block to be included in the code executed for a value other than just that which brings one to the preceding block, then we're already having to use goto
. (Of course, there are means and ways of avoiding this with different conditionals but that's true of just about everything relating to this question). As such C# built on the already normal way to deal with one situation where we want to hit more than one block of code in a switch
, and just generalised it to cover fall-through as well. It also made both cases more convenient and self-documenting, since we have to add a new label in C but can use the case
as a label in C#. In C# we can get rid of the below_six
label and use goto case 5
which is clearer as to what we are doing. (We'd also have to add break
for the default
, which I left out just to make the above C code clearly not C# code).
In summary therefore:
break
, for easier learning of the language by those familiar with similar languages, and easier porting.goto
-based approach for hitting the same block from different case
labels as is used in C. It just generalises it to some other cases.goto
-based approach more convenient, and clearer, than it is in C, by allowing case
statements to act as labels.All in all, a pretty reasonable design decision
*Some forms of BASIC would allow one to do the likes of GOTO (x AND 7) * 50 + 240
which while brittle and hence a particularly persuasive case for banning goto
, does serve to show a higher-language equivalent of the sort of way that lower-level code can make a jump based on arithmetic upon a value, which is much more reasonable when it's the result of compilation rather than something that has to be maintained manually. Implementations of Duff's Device in particular lend themselves well to the equivalent machine code or IL because each block of instructions will often be the same length without needing the addition of nop
fillers.
†Duff's Device comes up here again, as a reasonable exception. The fact that with that and similar patterns there's a repetition of operations serves to make the use of fall-through relatively clear even without an explicit comment to that effect.
The point is semantics. In assertTrue, you are asserting that the expression is true. If it is not, then it will display the message and the assertion will fail. In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails.
assertTrue (message, value == false) == assertFalse (message, value);
These are functionally the same, but if you are expecting a value to be false then use assertFalse
. If you are expecting a value to be true, then use assertTrue
.
Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..
In my case it helped to remove node_modules
and package-lock.json
.
After that just reinstall everything with npm install
.
Have you tried this?
>>> l=[('A',1), ('B',2), ('C',3)]
>>> d=dict(l)
>>> d
{'A': 1, 'C': 3, 'B': 2}
In my case I used below configuration at VM options in IntelliJ
, it was not picking the local configurations but after a restart of IntelliJ
it picked configuration details from IntelliJ
and service started running.
-Dspring.profiles.active=local
If you have a large array and only want to see a subsection of the array you can type this into the watch window;
ptr+100,10
to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.
foreach (new SplFileObject(__FILE__) as $line) {
echo $line;
}
On ubuntu (version 18), some application support java 8 and do not support java 11. If this is the case , you can switch to java 8 by following instruction on below topic : https://askubuntu.com/questions/1133216/downgrading-java-11-to-java-8
You are missing setter for salt
property as indicated by the exception
Please add the setter as
public void setSalt(long salt) {
this.salt=salt;
}
Are there situations in which sys.stdout.write() is preferable to print?
I have found that stdout works better than print in a multithreading situation. I use a queue (FIFO) to store the lines to print and I hold all threads before the print line until my print queue is empty. Even so, using print I sometimes lose the final \n on the debug I/O (using the Wing Pro IDE).
When I use std.out with \n in the string, the debug I/O formats correctly and the \n's are accurately displayed.
For saving the graph:
matplotlib.rcParams['savefig.dpi'] = 300
For displaying the graph when you use plt.show()
:
matplotlib.rcParams["figure.dpi"] = 100
Just add them at the top
I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array
To access the attributes of an object is pretty easy:
alert(data.second);
But, if this does not completely answer your question, please clarify it and post back.
Thanks !
From a background script you can listen to the chrome.tabs.onUpdated
event and check the property changeInfo.status
on the callback. It can be loading or complete. If it is complete, do the action.
Example:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
// do your things
}
})
Because this will probably trigger on every tab completion, you can also check if the tab is active
on its homonymous attribute, like this:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
// do your things
}
})
If you really want to retrieve classes you make with a string, you should store (or properly worded, reference) them in a dictionary. After all, that'll also allow to name your classes in a higher level and avoid exposing unwanted classes.
Example, from a game where actor classes are defined in Python and you want to avoid other general classes to be reached by user input.
Another approach (like in the example below) would to make an entire new class, that holds the dict
above. This would:
Example:
class ClassHolder:
def __init__(self):
self.classes = {}
def add_class(self, c):
self.classes[c.__name__] = c
def __getitem__(self, n):
return self.classes[n]
class Foo:
def __init__(self):
self.a = 0
def bar(self):
return self.a + 1
class Spam(Foo):
def __init__(self):
self.a = 2
def bar(self):
return self.a + 4
class SomethingDifferent:
def __init__(self):
self.a = "Hello"
def add_world(self):
self.a += " World"
def add_word(self, w):
self.a += " " + w
def finish(self):
self.a += "!"
return self.a
aclasses = ClassHolder()
dclasses = ClassHolder()
aclasses.add_class(Foo)
aclasses.add_class(Spam)
dclasses.add_class(SomethingDifferent)
print aclasses
print dclasses
print "======="
print "o"
print aclasses["Foo"]
print aclasses["Spam"]
print "o"
print dclasses["SomethingDifferent"]
print "======="
g = dclasses["SomethingDifferent"]()
g.add_world()
print g.finish()
print "======="
s = []
s.append(aclasses["Foo"]())
s.append(aclasses["Spam"]())
for a in s:
print a.a
print a.bar()
print "--"
print "Done experiment!"
This returns me:
<__main__.ClassHolder object at 0x02D9EEF0>
<__main__.ClassHolder object at 0x02D9EF30>
=======
o
<class '__main__.Foo'>
<class '__main__.Spam'>
o
<class '__main__.SomethingDifferent'>
=======
Hello World!
=======
0
1
--
2
6
--
Done experiment!
Another fun experiment to do with those is to add a method that pickles the ClassHolder
so you never lose all the classes you did :^)
UPDATE: It is also possible to use a decorator as a shorthand.
class ClassHolder:
def __init__(self):
self.classes = {}
def add_class(self, c):
self.classes[c.__name__] = c
# -- the decorator
def held(self, c):
self.add_class(c)
# Decorators have to return the function/class passed (or a modified variant thereof), however I'd rather do this separately than retroactively change add_class, so.
# "held" is more succint, anyway.
return c
def __getitem__(self, n):
return self.classes[n]
food_types = ClassHolder()
@food_types.held
class bacon:
taste = "salty"
@food_types.held
class chocolate:
taste = "sweet"
@food_types.held
class tee:
taste = "bitter" # coffee, ftw ;)
@food_types.held
class lemon:
taste = "sour"
print(food_types['bacon'].taste) # No manual add_class needed! :D
you can simply do:
const objectDiff = (a, b) => _.fromPairs(_.differenceWith(_.toPairs(a), _.toPairs(b), _.isEqual))
If you right click on any result of "Edit Top 200 Rows" query in SSMS you will see the option "Pane -> SQL". It then shows the SQL Query that was run, which you can edit as you wish.
In SMSS 2012 and 2008, you can use Ctrl+3 to quickly get there.
Hello was looking for the same, and it could be also
unlist(lapply(mtcars,class))
Alternative to answer of @JosephMarikle If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.
Quotation:
If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable.
You can use forEach
on array and construct a new group of items. Here is how to do that with FlowType
annotation
// @flow
export class Group<T> {
tag: number
items: Array<T>
constructor() {
this.items = []
}
}
const groupBy = (items: Array<T>, map: (T) => number) => {
const groups = []
let currentGroup = null
items.forEach((item) => {
const tag = map(item)
if (currentGroup && currentGroup.tag === tag) {
currentGroup.items.push(item)
} else {
const group = new Group<T>()
group.tag = tag
group.items.push(item)
groups.push(group)
currentGroup = group
}
})
return groups
}
export default groupBy
A jest test can be like
// @flow
import groupBy from './groupBy'
test('groupBy', () => {
const items = [
{ name: 'January', month: 0 },
{ name: 'February', month: 1 },
{ name: 'February 2', month: 1 }
]
const groups = groupBy(items, (item) => {
return item.month
})
expect(groups.length).toBe(2)
expect(groups[1].items[1].name).toBe('February 2')
})
Yes - you would probably be arrested for your terriable abuse of strcat !
Take a look at getline() it reads the data a line at a time but importantly it can limit the number of characters you read, so you don't overflow the buffer.
Strcat is relatively slow because it has to search the entire string for the end on every character insertion. You would normally keep a pointer to the current end of the string storage and pass that to getline as the position to read the next line into.
This generates a consistent hash based on any number of params passed in:
/**
* Generates a hash from params passed in
* @returns {string} hash based on params
*/
function fastHashParams() {
var args = Array.prototype.slice.call(arguments).join('|');
var hash = 0;
if (args.length == 0) {
return hash;
}
for (var i = 0; i < args.length; i++) {
var char = args.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return String(hash);
}
fastHashParams('hello world')
outputs "990433808"
fastHashParams('this',1,'has','lots','of','params',true)
outputs "1465480334"
I like to know where does we use Native Methods
Ideally, not at all. In reality some functionality is not available in Java and you have to call some C code.
The methods are implemented in C code.
I couldn't get the most popular answer to this question (above by Dario) to work properly. The result was weird, choppy animation with weird artifacts. Best solution I have found so far: https://github.com/XamlAnimatedGif/WpfAnimatedGif
You can install it with NuGet
PM> Install-Package WpfAnimatedGif
and to use it, at a new namespace to the Window where you want to add the gif image and use it as below
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:gif="http://wpfanimatedgif.codeplex.com" <!-- THIS NAMESPACE -->
Title="MainWindow" Height="350" Width="525">
<Grid>
<!-- EXAMPLE USAGE BELOW -->
<Image gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
The package is really neat, you can set some attributes like below
<Image gif:ImageBehavior.RepeatBehavior="3x"
gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
and you can use it in your code as well:
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);
EDIT: Silverlight support
As per josh2112's comment if you want to add animated GIF support to your Silverlight project then use github.com/XamlAnimatedGif/XamlAnimatedGif
You need to edit cassandra.yaml
on the node you are trying to connect to and set the node ip address for rpc_address
and listen_address
and restart Cassandra.
rpc_address
is the address on which Cassandra listens to the client calls.
listen_address
is the address on which Cassandra listens to the other Cassandra nodes.
There is a command line program to convert any Java project into a SBT/Maven project.
It resolves all jars and tries to figure out the correct version based on SHA checksum, classpath or filename. Then it tries to compile the sources until it finds a working configuration. Custom tasks to execute per dependency configuration can be given too.
UniversalResolver 1.0
Usage: UniversalResolver [options]
-s <srcpath1>,<srcpath2>... | --srcPaths <srcpath1>,<srcpath2>...
required src paths to include
-j <jar1>,<jar2>... | --jars <jar1>,<jar2>...
required jars/jar paths to include
-t /path/To/Dir | --testDirectory /path/To/Dir
required directory where test configurations will be stored
-a <task1>,<task2>... | --sbt-tasks <task1>,<task2>...
SBT Tasks to be executed. i.e. compile
-d /path/To/dependencyFile.json | --dependencyFile /path/To/dependencyFile.json
optional file where the dependency buffer will be stored
-l | --search
load and search dependencies from remote repositories
-g | --generateConfigurations
generate dependency configurations
-c <value> | --findByNameCount <value>
number of dependencies to resolve by class name per jar
The map you using here, is not the .map()
in javascript, it's Rxjs map function which working on Observables
in Angular...
So in that case you need to import it if you'd like to use map on the result data...
map(project: function(value: T, index: number): R, thisArg: any): Observable<R>
Applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable.
So simply import it like this:
import 'rxjs/add/operator/map';
You could use Mockito. I am not sure with PostConstruct
specifically, but this generally works:
// Create a mock of Resource to change its behaviour for testing
@Mock
private Resource resource;
// Testing instance, mocked `resource` should be injected here
@InjectMocks
@Resource
private TestedClass testedClass;
@Before
public void setUp() throws Exception {
// Initialize mocks created above
MockitoAnnotations.initMocks(this);
// Change behaviour of `resource`
when(resource.getSomething()).thenReturn("Foo");
}
Comparing pointers is not portable, for example in DOS different pointer values points to the same location, comparison of the pointers returns false.
/*--{++:main.c}--------------------------------------------------*/
#include <dos.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int val_a = 123;
int * ptr_0 = &val_a;
int * ptr_1 = MK_FP(FP_SEG(&val_a) + 1, FP_OFF(&val_a) - 16);
printf(" val_a = %d -> @%p\n", val_a, (void *)(&val_a));
printf("*ptr_0 = %d -> @%p\n", *ptr_0, (void *)ptr_0);
printf("*ptr_1 = %d -> @%p\n", *ptr_1, (void *)ptr_1);
/* Check what returns the pointers comparison: */
printf("&val_a == ptr_0 ====> %d\n", &val_a == ptr_0);
printf("&val_a == ptr_1 ====> %d\n", &val_a == ptr_1);
printf(" ptr_0 == ptr_1 ====> %d\n", ptr_0 == ptr_1);
printf("val_a = %d\n", val_a);
printf(">> *ptr_0 += 100;\n");
*ptr_0 += 100;
printf("val_a = %d\n", val_a);
printf(">> *ptr_1 += 500;\n");
*ptr_1 += 500;
printf("val_a = %d\n", val_a);
return EXIT_SUCCESS;
}
/*--{--:main.c}--------------------------------------------------*/
Compile it under Borland C 5.0, here is the result:
/*--{++:result}--------------------------------------------------*/
val_a = 123 -> @167A:0FFE
*ptr_0 = 123 -> @167A:0FFE
*ptr_1 = 123 -> @167B:0FEE
&val_a == ptr_0 ====> 1
&val_a == ptr_1 ====> 0
ptr_0 == ptr_1 ====> 0
val_a = 123
>> *ptr_0 += 100;
val_a = 223
>> *ptr_1 += 500;
val_a = 723
/*--{--:result}--------------------------------------------------*/
It works for me
git config --global --unset http.proxy
OR
git config --global --unset https.proxy
Update: this will not work on iOS 7. You should use ASIdentifierManager.
More clean solution on MobileDeveloperTips website:
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
...
- (NSString *)getMacAddress
{
int mgmtInfoBase[6];
char *msgBuffer = NULL;
size_t length;
unsigned char macAddress[6];
struct if_msghdr *interfaceMsgStruct;
struct sockaddr_dl *socketStruct;
NSString *errorFlag = NULL;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = @"if_nametoindex failure";
else
{
// Get the size of the data available (store in len)
if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = @"sysctl mgmtInfoBase failure";
else
{
// Alloc memory based on above call
if ((msgBuffer = malloc(length)) == NULL)
errorFlag = @"buffer allocation failure";
else
{
// Get system information, store in buffer
if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
errorFlag = @"sysctl msgBuffer failure";
}
}
}
// Befor going any further...
if (errorFlag != NULL)
{
NSLog(@"Error: %@", errorFlag);
return errorFlag;
}
// Map msgbuffer to interface message structure
interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2],
macAddress[3], macAddress[4], macAddress[5]];
NSLog(@"Mac Address: %@", macAddressString);
// Release the buffer memory
free(msgBuffer);
return macAddressString;
}
The code below does just that. The below is a working example to log into a game. I made a similar file to log in into Yahoo and a kurzweilai.net forum.
Just copy the login form from any webpage's source code. Add value= "your user name" and value = "your password". Normally the -input- elements in the source code do not have the value attribute, and sometime, you will see something like that: value=""
Save the file as a html on a local machine double click it, or make a bat/cmd file to launch and close them as required.
<!doctype html>
<!-- saved from url=(0014)about:internet -->
<html>
<title>Ikariam Autologin</title>
</head>
<body>
<form id="loginForm" name="loginForm" method="post" action="http://s666.en.ikariam.com/index.php?action=loginAvatar&function=login">
<select name="uni_url" id="logServer" class="validate[required]">
<option class="" value="s666.en.ikariam.com" fbUrl="" cookieName="" >
Test_en
</option>
</select>
<input id="loginName" name="name" type="text" value="PlayersName" class="" />
<input id="loginPassword" name="password" type="password" value="examplepassword" class="" />
<input type="hidden" id="loginKid" name="kid" value=""/>
</form>
<script>document.loginForm.submit();</script>
</body></html>
Note that -script- is just -script-. I found there is no need to specify that is is JavaScript. It works anyway. I also found out that a bare-bones version that contains just two input filds: userName and password also work. But I left a hidded input field etc. just in case. Yahoo mail has a lot of hidden fields. Some are to do with password encryption, and it counts login attempts.
Security warnings and other staff, like Mark of the Web to make it work smoothly in IE are explained here:
Use FUNCTION:
CREATE OR REPLACE FUNCTION test_function
RETURN VARCHAR2 IS
BEGIN
RETURN 'This is being returned from a function';
END test_function;
@variable
is very useful if calling stored procedures from an application written in Java , Python etc.
There are ocassions where variable values are created in the first call and needed in functions of subsequent calls.
The advantage can be seen in Oracle PL/SQL where these variables have 3 different scopes:
I have developed an architecture in which the complete code is written in PL/SQL. These are called from a middle-ware written in Java. There are two types of middle-ware. One to cater calls from a client which is also written in Java. The other other one to cater for calls from a browser. The client facility is implemented 100 percent in JavaScript. A command set is used instead of HTML and JavaScript for writing application in PL/SQL.
I have been looking for the same facility to port the codes written in PL/SQL to another database. The nearest one I have found is Postgres. But all the variables have function scope.
@
in MySQLI am happy to see that at least this @
facility is there in MySQL. I don't think Oracle will build same facility available in PL/SQL to MySQL stored procedures since it may affect the sales of Oracle database.
Another neat option is to use the Directive
as an element and not as an attribute.
@Directive({
selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {
@Input()
public first: string;
@Input()
public second: string;
ngAfterViewInit(): void {
console.log(`Values: ${this.first}, ${this.second}`);
}
}
And this directive can be used like that:
<app-someKindOfComponent>
<app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
<app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
<app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`
Simple, neat and powerful.
The most efficient way is to consider the exponential growth of the multiplications. Check this code for p^q:
template <typename T>
T expt(T p, unsigned q){
T r =1;
while (q != 0) {
if (q % 2 == 1) { // if q is odd
r *= p;
q--;
}
p *= p;
q /= 2;
}
return r;
}
Comparator
is a functional interface, and Integer::max
complies with that interface (after autoboxing/unboxing is taken into consideration). It takes two int
values and returns an int
- just as you'd expect a Comparator<Integer>
to (again, squinting to ignore the Integer/int difference).
However, I wouldn't expect it to do the right thing, given that Integer.max
doesn't comply with the semantics of Comparator.compare
. And indeed it doesn't really work in general. For example, make one small change:
for (int i = 1; i <= 20; i++)
list.add(-i);
... and now the max
value is -20 and the min
value is -1.
Instead, both calls should use Integer::compare
:
System.out.println(list.stream().max(Integer::compare).get());
System.out.println(list.stream().min(Integer::compare).get());
As another person just mentioned, it's a base64 encoded string. In the past, I've used this website to decode it:
Moq cannot mock a static member of a class.
When designing code for testability it's important to avoid static members (and singletons). A design pattern that can help you refactoring your code for testability is Dependency Injection.
This means changing this:
public class Foo
{
public Foo()
{
Bar = new Bar();
}
}
to
public Foo(IBar bar)
{
Bar = bar;
}
This allows you to use a mock from your unit tests. In production you use a Dependency Injection tool like Ninject or Unity wich can wire everything together.
I wrote a blog about this some time ago. It explains which patterns an be used for better testable code. Maybe it can help you: Unit Testing, hell or heaven?
Another solution could be to use the Microsoft Fakes Framework. This is not a replacement for writing good designed testable code but it can help you out. The Fakes framework allows you to mock static members and replace them at runtime with your own custom behavior.
Try this:
SELECT ProductId, Name, Tags
FROM Product
WHERE '1,2,3,' LIKE '%' + CAST(ProductId AS VARCHAR(20)) + ',%';
As said on the last example of this link
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score
FROM Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND E.FileNum = V.FileNum AND E.ActivityNum = V.ActivityNum
$ find proj
proj
proj/src
proj/src/index.js
$ cat proj/src/index.js
console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);
$ cd proj; node src/index.js
process.cwd() = /tmp/proj
__dirname = /tmp/proj/src
There is solution with all necessary details for Windows 7 x64:
http://www.youtube.com/watch?v=7qNTi1sEfE8
It is in French, but you can understand everything! I solved same problem, even don't speak French. :-)
Many answers forget to mention that you need to add new version of php_curl.dll file from this location: http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
I added new version of php_curl.dll from archive php_curl-5.4.3-VC9-x64.zip to folders: C:\wamp\bin\php\php5.4.3\ext and C:\Windows\System32 and everything was fine!
I have had co-workers that have used Burp ("an interactive HTTP/S proxy server for attacking and testing web applications") for this. You also may be able to use Fiddler ("a HTTP Debugging Proxy").
For anyone still coming to this post, the other option is to simply omit the parentheses:
Sub SomeOtherSub(Stattyp As String)
'Daty and the other variables are defined here
CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2
End Sub
The Call
keywords is only really in VBA for backwards compatibilty and isn't actually required.
If however, you decide to use the Call
keyword, then you have to change your syntax to suit.
'// With Call
Call Foo(Bar)
'// Without Call
Foo Bar
Both will do exactly the same thing.
That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call
keyword and the parentheses
I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??
This depends strongly on the crypto algorithm you use:
I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.
Example:
you can also use a filter to do it.
df = PD.DataFrame([
[-0.532681, 'foo', 0],
[1.490752, 'bar', 1],
[-1.387326, 'foo', 2],
[0.814772, 'baz', ' '],
[-0.222552, ' ', 4],
[-1.176781, 'qux', ' '])
df[df=='']='nan'
df=df.astype(float)
public enum MyEvents
{
Event1
}
public class CustomEventArgs : EventArgs
{
public MyEvents MyEvents { get; set; }
}
private EventHandler<CustomEventArgs> onTrigger;
public event EventHandler<CustomEventArgs> Trigger
{
add
{
onTrigger += value;
}
remove
{
onTrigger -= value;
}
}
protected void OnTrigger(CustomEventArgs e)
{
if (onTrigger != null)
{
onTrigger(this, e);
}
}
You might want to look at ConcurrentDoublyLinkedList written by Doug Lea based on Paul Martin's "A Practical Lock-Free Doubly-Linked List". It does not implement the java.util.List interface, but offers most methods you would use in a List.
According to the javadoc:
A concurrent linked-list implementation of a Deque (double-ended queue). Concurrent insertion, removal, and access operations execute safely across multiple threads. Iterators are weakly consistent, returning elements reflecting the state of the deque at some point at or since the creation of the iterator. They do not throw ConcurrentModificationException, and may proceed concurrently with other operations.
Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.
<?php
// Convert all MyISAM tables to INNODB tables in all non-special databases.
// Note: With MySQL less than 5.6, tables with a fulltext search index cannot be converted to INNODB and will be skipped.
if($argc < 4)
exit("Usage: {$argv[0]} <host> <username> <password>\n");
$host = $argv[1];
$username = $argv[2];
$password = $argv[3];
// Connect to the database.
if(!mysql_connect($host, $username, $password))
exit("Error opening database. " . mysql_error() . "\n");
// Get all databases except special ones that shouldn't be converted.
$databases = mysql_query("SHOW databases WHERE `Database` NOT IN ('mysql', 'information_schema', 'performance_schema')");
if($databases === false)
exit("Error showing databases. " . mysql_error() . "\n");
while($db = mysql_fetch_array($databases))
{
// Select the database.
if(!mysql_select_db($db[0]))
exit("Error selecting database: {$db[0]}. " . mysql_error() . "\n");
printf("Database: %s\n", $db[0]);
// Get all MyISAM tables in the database.
$tables = mysql_query("SHOW table status WHERE Engine = 'MyISAM'");
if($tables === false)
exit("Error showing tables. " . mysql_error() . "\n");
while($tbl = mysql_fetch_array($tables))
{
// Convert the table to INNODB.
printf("--- Converting %s\n", $tbl[0]);
if(mysql_query("ALTER TABLE `{$tbl[0]}` ENGINE = INNODB") === false)
printf("--- --- Error altering table: {$tbl[0]}. " . mysql_error() . "\n");
}
}
mysql_close();
?>
It works on my case:
import * as JQuery from "jquery";
const $ = JQuery.default;
Remove the dot and import absolute_import in the beginning of your file
from __future__ import absolute_import
from p_02_paying_debt_off_in_a_year import compute_balance_after
Another option if you don't have Python 2.6:
import commands
n = commands.getoutput("grep -c processor /proc/cpuinfo")
You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.
Have you set the DataContext to your ConnectionViewModel object?
I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.
Here is my XAML content:
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<Button Click="Button_Click">asdf</Button>
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
</StackPanel>
</Grid>
</Window>
And here is my code-behind:
namespace WpfApplication6
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ConnectionViewModel vm = new ConnectionViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((ConnectionViewModel)DataContext).PhonebookEntry = "test";
}
}
public class PhoneBookEntry
{
public string Name { get; set; }
public PhoneBookEntry(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
public class ConnectionViewModel : INotifyPropertyChanged
{
public ConnectionViewModel()
{
IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
list.Add(new PhoneBookEntry("test"));
list.Add(new PhoneBookEntry("test2"));
_phonebookEntries = new CollectionView(list);
}
private readonly CollectionView _phonebookEntries;
private string _phonebookEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.
Maybe there is an issue with the CollectionView? I noticed a warning in the output console:
System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.
Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.
In Python 2.x - .items()
returned a list of (key, value) pairs. In Python 3.x, .items()
is now an itemview
object, which behaves different - so it has to be iterated over, or materialised... So, list(dict.items())
is required for what was dict.items()
in Python 2.x.
Python 2.7 also has a bit of a back-port for key handling, in that you have viewkeys
, viewitems
and viewvalues
methods, the most useful being viewkeys
which behaves more like a set
(which you'd expect from a dict
).
Simple example:
common_keys = list(dict_a.viewkeys() & dict_b.viewkeys())
Will give you a list of the common keys, but again, in Python 3.x - just use .keys()
instead.
Python 3.x has generally been made to be more "lazy" - i.e. map
is now effectively itertools.imap
, zip
is itertools.izip
, etc.
For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html
EDIT: In case that blog dies, here are the links from the blog.
All the bellow files are more them 400MB.
Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO FileVisual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO FileVisual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO FileVisual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File
Visual J# 2005 Express Edition
448,702 KB
.IMG File|.ISO File
For an old school input stream, use this code:
InputStream in = new URL("http://google.com/").openConnection().getInputStream();
To store the array values in cookie, first you need to convert them to string, so here is some options.
Storing code
setcookie('your_cookie_name', json_encode($info), time()+3600);
Reading code
$data = json_decode($_COOKIE['your_cookie_name'], true);
JSON can be good choose also if you need read cookie in front end with JavaScript.
Actually you can use any encrypt_array_to_string
/decrypt_array_from_string
methods group that will convert array to string and convert string back to same array.
For example you can also use explode
/implode
for array of integers.
From PHP.net
Do not pass untrusted user input to unserialize().
- Anything that coming by HTTP including cookies is untrusted!
References related to security
setcookie('my_array[0]', 'value1' , time()+3600);
setcookie('my_array[1]', 'value2' , time()+3600);
setcookie('my_array[2]', 'value3' , time()+3600);
And after if you will print $_COOKIE
variable, you will see the following
echo '<pre>';
print_r( $_COOKIE );
die();
Array ( [my_array] => Array ( [0] => value1 [1] => value2 [2] => value3 ) )
This is documented PHP feature.
From PHP.net
Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.
Here is a complete jquery solution that will work in IE:
Suppose the navigation bar elements are something like this:
<ul>
<li><a class="navigation" href="/#contact-us">Contact us</a></li>
<li><a class="navigation" href="/#about-us">About us</a></li>
</ul>
You can use the following jquery snippet to offset the scroll:
$(function() {
$("a.navigation").click(function(event) {
event.preventDefault();
offSetScroll($(this));
});
offSetScrollFromLocation(window.location.href.toLowerCase());
});
function offSetScroll(anchor) {
var href = anchor.attr("href");
offSetScrollFromLocation(href);
}
function offSetScrollFromLocation(href) {
//Change this according to the height of the navigation bar
var fromTop = 250;
if(href.indexOf("#")<=0)
return;
var hash=href.substring(href.indexOf("#"));
var targetOffset = $(hash).offset().top-fromTop;
$('html, body').animate({scrollTop: targetOffset}, 400, function(e) {
});
}
those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:
Using 'now()' as default value automatically generates time-stamp.
I think there is a simpler way to make excel wait till the refresh is done, without having to set the Background Query property to False. Why mess with people's preferences right?
Excel 2010 (and later) has this method called CalculateUntilAsyncQueriesDone and all you have to do it call it after you have called the RefreshAll method. Excel will wait till the calculation is complete.
ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone
I usually put these things together to do a master full calculate without interruption, before sending my models to others. Something like this:
ThisWorkbook.RefreshAll
Application.CalculateUntilAsyncQueriesDone
Application.CalculateFullRebuild
Application.CalculateUntilAsyncQueriesDone
DISCLAMER: I'm the author...
I wrote a package that does exactly this, business dates calculations. You can use custom week specification and holidays.
I had this exact problem while working with financial data and didn't find any of the available solutions particularly easy, so I wrote one.
Hope this is useful for other people.
I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.
(The strange thing was that all ssh-*
commands were valid, (bash could execute as program) but the openssh package wasn't installed.)
Check that :
Additionally, you can look at the error.log file (usually located at /var/log/apache2/error.log
) which will describe why you get the 403 error exactly.
Finally, you may want to restart apache, just to be sure all that configuration is applied.
This can be generally done with /etc/init.d/apache2 restart
. On some system, the script will be called httpd. Just figure out.
Supposing your date is today. Hope this helps you.
DateTime dt = DateTime.Today;
string thisMonth= dt.ToString("MMMM");
Console.WriteLine(thisMonth);
DateTimePicker1.value = Format(Date.Now)
Maybe try this
Select cust.*
From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null
If you want the text value of a QString object you can use the __str__
property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.
Open command prompt with admin access and type the following commands there .
a)
tasklist
it displays list of all available services . There you can see the service you want to stop/start/restart . Remember PID value of the service you want to force stop.
b) Now type
taskkill /f /PID [PID value of the service]
and press enter. On success you will get the message “SUCCESS: The process with PID has been terminated”.
Ex : taskkill /f /PID 5088
This will forcibly kill the frozen service. You can now return to Server Manager and restart the service.
In Windows, the below combinations work for me:
http://sourceforge.net/projects/pywin32/files/ - 3rd .exe down
You need to add @Valid to each member variable, which was also an object that contained validation constraints.
As I found the default Bootstrap <hr/>
size unsightly, here's some simple HTML and CSS to balance out the element visually:
HTML:
<hr class="half-rule"/>
CSS:
.half-rule {
margin-left: 0;
text-align: left;
width: 50%;
}
Just observations you could make:
poly
extends my
? This is useless...my.class
, poly.class
and poly$1.class
Can we instantiate an abstract class?
No, we can't. What we can do is, create an anonymous class (that's the third file) and instantiate it.
What about a super class instantiation?
The abstract super class is not instantiated by us but by java.
EDIT: Ask him to test this
public static final void main(final String[] args) {
final my m1 = new my() {
};
final my m2 = new my() {
};
System.out.println(m1 == m2);
System.out.println(m1.getClass().toString());
System.out.println(m2.getClass().toString());
}
output is:
false
class my$1
class my$2
This is because you are adding your <tbody>
tag before <td>
in table you cannot print any data without <td>
.
So for that you have to make a <div>
say #header
with position: fixed;
header
{
position: fixed;
}
make another <div>
which will act as <tbody>
tbody
{
overflow:scroll;
}
Now your header is fixed and the body will scroll. And the header will remain there.
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnClickListener(v -> {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
String slectedValue=radioButton.getText()
});
imageView.image = [UIImage imageNamed:@"myImage.png"];
We use A. I would put it on a shared drive (unless you don't plan on running more than one server).
If the time comes when this won't scale for you then you can investigate caching mechanisms.
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
Debian/Ubuntu handles this with a cronjob defined in /etc/cron.d/php5
# /etc/cron.d/php5: crontab fragment for php5
# This purges session files older than X, where X is defined in seconds
# as the largest value of session.gc_maxlifetime from all your php.ini
# files, or 24 minutes if not defined. See /usr/lib/php5/maxlifetime
# Look for and purge old sessions every 30 minutes
09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm
The maxlifetime script simply returns the number of minutes a session should be kept alive by checking php.ini, it looks like this
#!/bin/sh -e
max=1440
for ini in /etc/php5/*/php.ini; do
cur=$(sed -n -e 's/^[[:space:]]*session.gc_maxlifetime[[:space:]]*=[[:space:]]*\([0-9]\+\).*$/\1/p' $ini 2>/dev/null || true);
[ -z "$cur" ] && cur=0
[ "$cur" -gt "$max" ] && max=$cur
done
echo $(($max/60))
exit 0
Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.
https://tools.ietf.org/html/rfc6750
Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.
If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.
However, it will be hard way since the mac spec is still changing rapidly.
Try to use the following:
\Request::getRequestUri()
Try something like this
PdfPCell cell;
PdfPTable tableHeader;
PdfPTable tmpTable;
PdfPTable table = new PdfPTable(10) { WidthPercentage = 100, RunDirection = PdfWriter.RUN_DIRECTION_LTR, ExtendLastRow = false };
// row 1 / cell 1 (merge)
PdfPCell _c = new PdfPCell(new Phrase("SER. No")) { Rotation = -90, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1 };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 2
_c = new PdfPCell(new Phrase("TYPE OF SHIPPING")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 3
_c = new PdfPCell(new Phrase("ORDER NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 4
_c = new PdfPCell(new Phrase("QTY.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 5
_c = new PdfPCell(new Phrase("DISCHARGE PPORT")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 6 (merge)
_c = new PdfPCell(new Phrase("DESCRIPTION OF GOODS")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 7
_c = new PdfPCell(new Phrase("LINE DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 1 / cell 8 (merge)
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 9 (merge)
_c = new PdfPCell(new Phrase("CLEARANCE DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 1 / cell 10 (merge)
_c = new PdfPCell(new Phrase("CUSTOM PERMIT NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
_c.Rowspan = 2;
table.AddCell(_c);
// row 2 / cell 2
_c = new PdfPCell(new Phrase("AWB / BL NO.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 3
_c = new PdfPCell(new Phrase("COMPLEX NAME")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 4
_c = new PdfPCell(new Phrase("G.W Kgs.")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 5
_c = new PdfPCell(new Phrase("DESTINATON")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
// row 2 / cell 7
_c = new PdfPCell(new Phrase("OWNER DOC. RECI. DATE")) { VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_CENTER };
table.AddCell(_c);
_doc.Add(table);
///////////////////////////////////////////////////////////
_doc.Close();
You might need to re-adjust slightly on the widths and borders but that is a one shot to do.
you can use np.array(itertools.product(a, b))
I was having the same problem, although I solved out by creating the table using a script query instead of doing it graphically. See the snipped below:
USE [Database_Name]
GO
CREATE TABLE [dbo].[Table_Name](
[tableID] [int] IDENTITY(1,1) NOT NULL,
[column_2] [datatype] NOT NULL,
[column_3] [datatype] NOT NULL,
CONSTRAINT [PK_Table_Name] PRIMARY KEY CLUSTERED
(
[tableID] ASC
)
)
The following worked the best for me, basically I'm scrapping any existing tooltip and not bothering to show the new tooltip. If calling show on the tooltip like in other answers, it pops up even if the cursor isn't hovering above it.
The reason I went for this solution is that the other solutions, re-using the existing tooltip, led to some strange issues with the tooltip sometimes not showing when hovering the cursor above the element.
function updateTooltip(element, tooltip) {
if (element.data('tooltip') != null) {
element.tooltip('hide');
element.removeData('tooltip');
}
element.tooltip({
title: tooltip
});
}
TL:DR
row lock = A$5
column lock = $A5
Both = $A$5
Below are examples of how to use the Excel lock reference $
when creating your formulas
To prevent increments when moving from one row to another put the $ after the column letter and before the row number. e.g. A$5
To prevent increments when moving from one column to another put the $ before the row number. e.g. $A5
To prevent increments when moving from one column to another or from one row to another put the $ before the row number and before the column letter. e.g. $A$5
Using the lock reference will also prevent increments when dragging cells over to duplicate calculations.
Maybe you can try this: though please note - This pulls the column count, not the row count
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int count = reader.VisibleFieldCount;
Console.WriteLine(count);
}
}
Use functools.partial, not lambdas! And ofc Perform is a useless function, you can pass around functions directly.
for func in [Action1, partial(Action2, p), partial(Action3, p, r)]:
func()
—
:: —
:: \u2014
When representing the m-dash in a JavaScript text string for output to HTML, note that it will be represented by its unicode value. There are cases when ampersand characters ('&') will not be resolved—notably certain contexts within JSX. In this case, neither —
nor —
will work. Instead you need to use the Unicode escape sequence: \u2014
.
For example, when implementing a render()
method to output text from a JavaScript variable:
render() {
let text='JSX transcoders will preserve the & character—to '
+ 'protect from possible script hacking and cross-site hacks.'
return (
<div>{text}</div>
)
}
This will output:
<div>JSX transcoders will preserve the & character—to protect from possible script hacking and cross-site hacks.</div>
Instead of the &
– prefixed representation, you should use \u2014:
let text='JSX transcoders will preserve the & character\u2014to …'
I was able to connect my sql server5.7 running on my host using the below command : mysql -h 10.10.1.7 -P 3307 --protocol=tcp -u root -p where the ip given is my host ip and 3307 is the port forwaded in mysql docker .After entering the command type the password for myql.that is it.Now you are connected the mysql docker container from the you hostmachine
You can try creating a css for your font with font-face (like explained here)
Step #1
Create a css file with font face and place it somewhere, like in assets/fonts
customfont.css
@font-face {
font-family: YourFontFamily;
src: url("/assets/font/yourFont.otf") format("truetype");
}
Step #2
Add the css to your .angular-cli.json in the styles
config
"styles":[
//...your other styles
"assets/fonts/customFonts.css"
]
Do not forget to restart ng serve
after doing this
Step #3
Use the font in your code
component.css
span {font-family: YourFontFamily; }
(As seen in: BASH FAQ entry #68: "How do I run a command, and have it abort (timeout) after N seconds?")
If you don't mind downloading something, use timeout
(sudo apt-get install timeout
) and use it like: (most Systems have it already installed otherwise use sudo apt-get install coreutils
)
timeout 10 ping www.goooooogle.com
If you don't want to download something, do what timeout does internally:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec ping www.goooooogle.com )
In case that you want to do a timeout for longer bash code, use the second option as such:
( cmdpid=$BASHPID;
(sleep 10; kill $cmdpid) \
& while ! ping -w 1 www.goooooogle.com
do
echo crap;
done )
PHP has Heredoc and Nowdoc strings, which are the best way to handle multiline strings in PHP.
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
$var is replaced automatically.
EOD;
A Nowdoc is like a Heredoc, but it doesn't replace variables.
$str = <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
$var is NOT replaced in a nowdoc.
EOD;
Beware that the end token EOD
must not be indented at all, or PHP won't acknowledge it. Also, you don't have to use "EOD
"; it can be any string you want.
Here's my own take at it based on the xpath of the element created :
/** Returns the XPATH of an element **/
var getPathTo = function(element) {
if (element===document.body)
return element.tagName;
var ix= 0;
var siblings= element.parentNode.childNodes;
for (var i= 0; i<siblings.length; i++) {
var sibling= siblings[i];
if (sibling===element)
// stripped xpath (parent xpath + tagname + index)
return getPathTo(element.parentNode)+ element.tagName + ix+1;
if (sibling.nodeType===1 && sibling.tagName===element.tagName)
ix++;
}
}
/** hashcode function (credit http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery **/
var hashCode = function(str) {
var hash = 0, i, chr, len;
if (str.length === 0) return hash;
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
/** Genaretes according to xpath + timestamp **/
var generateUID = function(ele)
{
return hashCode(getPathTo(ele)) + new Date().getTime();
}
First the xpath of the element is fetched.
The hashcode of the xpath is then computed. We therefore have a unique id per xpath.
The problem here is that xpath are not necesseraly unique if unique elements are generated on the fly. Thus we add the timestamp at the end.
Maybe we could also garantee more unique elements by adding a final Math.Random().
Answered my own question after reading your advice on the vertical-align CSS attribute. Thanks for the tip!
.pdf:before {
padding: 0 5px 0 0;
content: url(../img/icon/pdf_small.png);
vertical-align: -50%;
}
fn + shift + leftArrow = goto beginning of line
fn + shift + rightArrow = goto end of line
these work for me
Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:
$("*[attr-name]")
Hope that helps somebody who happens to land on this page looking for the same thing that I was :).
Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):
$("[attr-name]")
Using webpack CLI: (--version, -v Show version number [boolean])
webpack --version
or:
webpack -v
Using npm list command:
npm list webpack
Results in name@version-range
:
<projectName>@<projectVersion> /path/to/project
+-- webpack@<version-range>
Using yarn list command:
yarn list webpack
Webpack 2 introduced Configuration Types.
Instead of exporting a configuration object, you may return a function which accepts an environment as argument. When running webpack, you may specify build environment keys via
--env
, such as--env.production
or--env.platform=web
.
We will use a build environment key called --env.version
.
webpack --env.version $(webpack --version)
or:
webpack --env.version $(webpack -v)
For this to work we will need to do two things:
Change our webpack.config.js
file and use DefinePlugin.
The DefinePlugin allows you to create global constants which can be configured at compile time.
-module.exports = {
+module.exports = function(env) {
+ return {
plugins: [
new webpack.DefinePlugin({
+ WEBPACK_VERSION: JSON.stringify(env.version) //<version-range>
})
]
+ };
};
Now we can access the global constant like so:
console.log(WEBPACK_VERSION);
Using npm view command will return the latest version available on the registry:
npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]
For webpack use:
npm view webpack version
Use this
DELETE FROM `articles`, `comments`
USING `articles`,`comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
or
DELETE `articles`, `comments`
FROM `articles`, `comments`
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4
Adding new certificate resolved this issue for me. Properties page -> signing -> Click on Create test certificate
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
Try Wireshark or WebScarab second is better for interpolating data into the exchange (not sure Wireshark even can). Anyway, one of them should be able to help you out.
This is a full example based on the other answers and comments to the question. In the example the timestamp (created_at
-column) is saved as unix epoch UTC timezone and converted to local timezone only when necessary.
Using unix epoch saves storage space - 4 bytes integer vs. 24 bytes string when stored as ISO8601 string, see datatypes. If 4 bytes is not enough that can be increased to 6 or 8 bytes.
Saving timestamp on UTC timezone makes it convenient to show a reasonable value on multiple timezones.
SQLite version is 3.8.6 that ships with Ubuntu LTS 14.04.
$ sqlite3 so.db
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
sqlite> .headers on
create table if not exists example (
id integer primary key autoincrement
,data text not null unique
,created_at integer(4) not null default (strftime('%s','now'))
);
insert into example(data) values
('foo')
,('bar')
;
select
id
,data
,created_at as epoch
,datetime(created_at, 'unixepoch') as utc
,datetime(created_at, 'unixepoch', 'localtime') as localtime
from example
order by id
;
id|data|epoch |utc |localtime
1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
Localtime is correct as I'm located at UTC+2 DST at the moment of the query.
This will limit it to however many lines you want it limited to and is responsive
An idea that nobody has suggested, doing it based on the height of the element and then stripping it back from there.
Fiddle - https://jsfiddle.net/hutber/u5mtLznf/ <- ES6 version
But basically you want to grab the line height of the element, loop through all the text and stop when its at a certain lines height:
'use strict';
var linesElement = 3; //it will truncate at 3 lines.
var truncateElement = document.getElementById('truncateme');
var truncateText = truncateElement.textContent;
var getLineHeight = function getLineHeight(element) {
var lineHeight = window.getComputedStyle(truncateElement)['line-height'];
if (lineHeight === 'normal') {
// sucky chrome
return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']);
} else {
return parseFloat(lineHeight);
}
};
linesElement.addEventListener('change', function () {
truncateElement.innerHTML = truncateText;
var truncateTextParts = truncateText.split(' ');
var lineHeight = getLineHeight(truncateElement);
var lines = parseInt(linesElement.value);
while (lines * lineHeight < truncateElement.clientHeight) {
console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight);
truncateTextParts.pop();
truncateElement.innerHTML = truncateTextParts.join(' ') + '...';
}
});
CSS
#truncateme {
width: auto; This will be completely dynamic to the height of the element, its just restricted by how many lines you want it to clip to
}
A couple of wires are crossed here. The various autoplay
settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.
However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.
Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)
You just have to change the structure of the if...else..endif
somewhat:
if exists(select * from Table where FieldValue='') then begin
select TableID from Table where FieldValue=''
end else begin
insert into Table (FieldValue) values ('')
select TableID from Table where TableID = scope_identity()
end
You could also do:
if not exists(select * from Table where FieldValue='') then begin
insert into Table (FieldValue) values ('')
end
select TableID from Table where FieldValue=''
Or:
if exists(select * from Table where FieldValue='') then begin
select TableID from Table where FieldValue=''
end else begin
insert into Table (FieldValue) values ('')
select scope_identity() as TableID
end
Not a complete answer, but a useful link:
"I frequently do calculations against decimal values. In some cases casting decimal values to float ASAP, prior to any calculations, yields better accuracy. "
My recommendation is to solve problems that you're interested in, writing code that might be useful to you.
Java is a huge box. It's got a lot of computer science inside: graphics, scientific computing, relational databases, user interfaces for desktop and web, messaging and queuing, multi-threading, security, and more. Each area has their own "beginner problem". Which one do you mean?
How do you define "beginner problem"? Maybe you're having trouble because you aren't narrowing your search enough.
If your imagination is lacking, your best bet is to Google something like "java beginner practice problems" and investigate what you get back.
Or start with Sun's on-line Java tutorial and work you way all the way through it. You'll know a fair amount about Java when you're done.
For those who have updated to the latest version of google-play-services_lib and/or have this error Google Play services out of date. Requires 3136100 but found 2012110
this newer version of com.google.android.gms.apk (Google Play Services 3.1.36) and com.android.vending.apk (Google Play Store 4.1.6) should work.
Test with this configuration on Android SDK Tools 22.0.1. Another configuration that targets pure Android, not the Google one, should work too.
...
Execute this in the terminal / cmd
adb -e install com.google.android.gms.apk
adb -e install com.android.vending.apk
Restart the AVD
I found this way to be the easiest, cleanest and it works with the newest version of the software, which allow you to get all the bug fixes.
My complete code as below is working well:
package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail
{
public static void main(String [] args)
{
// Sender's email ID needs to be mentioned
String from = "[email protected]";
String pass ="test123";
// Recipient's email ID needs to be mentioned.
String to = "[email protected]";
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
In short, []
operator is more efficient for updating values because it involves calling default constructor of the value type and then assigning it a new value, while insert()
is more efficient for adding values.
The quoted snippet from Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers, Item 24 might help.
template<typename MapType, typename KeyArgType, typename ValueArgType>
typename MapType::iterator
insertKeyAndValue(MapType& m, const KeyArgType&k, const ValueArgType& v)
{
typename MapType::iterator lb = m.lower_bound(k);
if (lb != m.end() && !(m.key_comp()(k, lb->first))) {
lb->second = v;
return lb;
} else {
typedef typename MapType::value_type MVT;
return m.insert(lb, MVT(k, v));
}
}
You may decide to choose a generic-programming-free version of this, but the point is that I find this paradigm (differentiating 'add' and 'update') extremely useful.
The answer to this is CSS Specificity. You need to be more "specific" in your CSS so that it can override bootstrap css properties.
For example you have a sample code for a bootstrap menu here:
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div id="home-menu-container" class="collapse navbar-collapse">
<ul id="home-menu" class="nav navbar-nav">
<li><a class="navbar-brand" href="#"><img src="images/xd_logo.png" /></a></li>
<li><a href="#intro">Home</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#services">What We Do</a></li>
<li><a href="#process">Our Process</a><br /></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#contact">Contact Us</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</nav>
Here, you need to remember the hierarchy of the specificity. It goes like this:
So, for the above if your css has something like this:
.navbar ul li a { color: red; } /* 10(.navbar) + 1(ul) + 1(li) + 1(a) = 13 points */
.navbar a { color: green; } /* 10(.navbar) + 1(a) = 11 points */
So, even if you have defined the .navbar a
after .navbar ul li a
it is still going to override with a red colour, instead of a green since the specificity is more (13 points).
So, basically all you need to do is calculate the points for the element you are wanting to change the css for, via inspect element on your browser. Here, bootstrap has specified its css for the element as
.navbar-inverse .navbar-nav>li>a { /* Total = 22 points */
color: #999;
}
So, even if your css is loading is being loaded after bootstrap.css which has the following line:
.navbar-nav li a {
color: red;
}
it's still going to be rendered as #999. In order to solve this, bootstrap has 22 points (calculate it yourself). So all we need is something more than that. Thus, I have added custom IDs to the elements i.e. home-menu-container and home-menu. Now the following css will work:
#home-menu-container #home-menu li a { color: red; } /* 100 + 100 + 1 + 1 = 202 points :) */
Done.
You can refer to this MDN link.
Change you buildToolsVersion to some other version and sync, change it back and sync again. It will work again.
Margin="1,2,3,4"
It is also possible to specify just two sizes like this:
Margin="1,2"
Finally you can specify a single size:
Margin="1"
The order is the same as in WinForms.
While other answers already fulfilled the question (it's a 3 years old question after all), I'm just gonna add some info, and probably fixed a bit of misunderstanding.
Em, while originally meant as the term for a single 'M' character's width in typography, in digital medium it was shifted to a unit relative to the point size of the typeface (font-size or textSize), in other words it's uses the height of the text, not the width of a single 'M'.
In Android, that means when you specify the ems of a TextView, it uses the said TextView's textSize as the base, excluding the added padding for accents/diacritics. When you set a 16sp TextView's ems to 4, it means its width will be 64sp wide, thus explained @stefan 's comment about why a 10 ems wide EditText is able to fit 17 'M'.
With PHP 7.4 I do it like this:
$ipaddress = '';
if (isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
But keep in mind that REMOTE_ADDR
is the only reliable IP address that you can get. All other values can easily be manipulated. This is theoretically also possible for REMOTE_ADDRESS
, but that would require to spoof the IP address.
You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.
CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4
Mind that you need to use the wildcards in PATINDEX on either side.
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
Important Note: Alert of Future Deprecation.
As of iOS 9.0, the API functions description for:
AudioServicesPlaySystemSound(inSystemSoundID: SystemSoundID)
AudioServicesPlayAlertSound(inSystemSoundID: SystemSoundID)
includes the following note:
This function will be deprecated in a future release.
Use AudioServicesPlayAlertSoundWithCompletion or
AudioServicesPlaySystemSoundWithCompletion instead.
The right way to go will be using any of these two:
AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate, nil)
or
AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate) {
//your callback code when the vibration is done (it may not vibrate in iPod, but this callback will be always called)
}
remember to
import AVFoundation
Here is a simple demo to create customview (compoundview) by inflating from xml
attrs.xml
<resources>
<declare-styleable name="CustomView">
<attr format="string" name="text"/>
<attr format="reference" name="image"/>
</declare-styleable>
</resources>
CustomView.kt
class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
ConstraintLayout(context, attrs, defStyleAttr) {
init {
init(attrs)
}
private fun init(attrs: AttributeSet?) {
View.inflate(context, R.layout.custom_layout, this)
val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
try {
val text = ta.getString(R.styleable.CustomView_text)
val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
if (drawableId != 0) {
val drawable = AppCompatResources.getDrawable(context, drawableId)
image_thumb.setImageDrawable(drawable)
}
text_title.text = text
} finally {
ta.recycle()
}
}
}
custom_layout.xml
We should use merge
here instead of ConstraintLayout
because
If we use ConstraintLayout
here, layout hierarchy will be ConstraintLayout
->ConstraintLayout
-> ImageView
+ TextView
=> we have 1 redundant ConstraintLayout
=> not very good for performance
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:parentTag="android.support.constraint.ConstraintLayout">
<ImageView
android:id="@+id/image_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="ContentDescription"
tools:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="@id/image_thumb"
app:layout_constraintStart_toStartOf="@id/image_thumb"
app:layout_constraintTop_toBottomOf="@id/image_thumb"
tools:text="Text" />
</merge>
Using activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<your_package.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f00"
app:image="@drawable/ic_android"
app:text="Android" />
<your_package.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0f0"
app:image="@drawable/ic_adb"
app:text="ADB" />
</LinearLayout>
Result
As an alternative to everyone else's answers I've always done something like this:
List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
if (someCondition) {
toRemove.add(str);
}
}
myArrayList.removeAll(toRemove);
This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.
As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:
background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;
Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).
No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.
Not sure if this answers this question. But I was looking for something else. Highly recommend see this 2 minute video. If you wanted to get into more details then see docs - Handling Parameters and this link
And then if you have something like blue ocean, the choices would look something like this:
You define and access your variables like this:
pipeline {
agent any
parameters {
string(defaultValue: "TEST", description: 'What environment?', name: 'userFlag')
choice(choices: ['TESTING', 'STAGING', 'PRODUCTION'], description: 'Select field for target environment', name: 'DEPLOY_ENV')
}
stages {
stage("foo") {
steps {
echo "flag: ${params.userFlag}"
echo "flag: ${params.DEPLOY_ENV}"
}
}
}
}
Automated builds will pick up the default params. But if you do it manually then you get the option to choose.
And then assign values like this:
Error happens in your function declarations,look the following sentence!You need a semicolon!
AST_NODE* Statement(AST_NODE* node)
The marked answer didn't work for me, I had to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
EDIT:
Or just try removing the this
:
SharedPreferences prefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
try {
JSONObject jsonObject = new JSONObject(response.body().string());
System.out.println(jsonObject);
} catch (JSONException | IOException e ) {
e.printStackTrace();
}
I'm surprised that nobody suggested guava solution yet:
com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)
or if you expect single element:
com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)
Check out ActiveModel::Dirty (available on all models by default). The documentation is really good, but it lets you do things such as:
@user.street1_changed? # => true/false
I had this same problem with port 443, process id 4 and everything. For me it was not the VPN using the port, it was IIS. To fix this I opened up IIS and right clicked on my instance and stopped it. Then IIS Express(Or apache if you're using that) was able to use port 443. Hope this helps someone else.
When connecting to SQL Server with Windows Authentication (as opposed to a local SQL Server account), attempting to use a linked server may result in the error message:
Cannot create an instance of OLE DB provider "(OLEDB provider name)"...
The most direct answer to this problem is provided by Microsoft KB 2647989, because "Security settings for the MSDAINITIALIZE DCOM class are incorrect."
The solution is to fix the security settings for MSDAINITIALIZE. In Windows Vista and later, the class is owned by TrustedInstaller, so the ownership of MSDAINITIALIZE must be changed before the security can be adjusted. The KB above has detailed instructions for doing so.
This MSDN blog post describes the reason:
MSDAINITIALIZE is a COM class that is provided by OLE DB. This class can parse OLE DB connection strings and load/initialize the provider based on property values in the connection string. MSDAINITILIAZE is initiated by users connected to SQL Server. If Windows Authentication is used to connect to SQL Server, then the provider is initialized under the logged in user account. If the logged in user is a SQL login, then provider is initialized under SQL Server service account. Based on the type of login used, permissions on MSDAINITIALIZE have to be provided accordingly.
The issue dates back at least to SQL Server 2000; KB 280106 from Microsoft describes the error (see "Message 3") and has the suggested fix of setting the In Process flag for the OLEDB provider.
While setting In Process can solve the immediate problem, it may not be what you want. According to Microsoft,
Instantiating the provider outside the SQL Server process protects the SQL Server process from errors in the provider. When the provider is instantiated outside the SQL Server process, updates or inserts referencing long columns (text, ntext, or image) are not allowed. -- Linked Server Properties doc for SQL Server 2008 R2.
The better answer is to go with the Microsoft guidance and adjust the MSDAINITIALIZE security.
If you are using spring with application.yml the following will work for you
spring:
datasource:
url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar
This data is JSON! You can deserialize it using the built-in json
module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson
module.
import json # or `import simplejson as json` if on Python < 2.6
json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string) # obj now contains a dict of the data
Use the TRY_CONVERT function.
Create a user defined function. This will avoid the issues that Fedor Hajdu mentioned with regards to currency, fractional numbers, etc:
CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS int
AS
BEGIN
SET @Value = REPLACE(@Value, ',', '')
IF ISNUMERIC(@Value + 'e0') = 0 RETURN NULL
IF ( CHARINDEX('.', @Value) > 0 AND CONVERT(bigint, PARSENAME(@Value, 1)) <> 0 ) RETURN NULL
DECLARE @I bigint =
CASE
WHEN CHARINDEX('.', @Value) > 0 THEN CONVERT(bigint, PARSENAME(@Value, 2))
ELSE CONVERT(bigint, @Value)
END
IF ABS(@I) > 2147483647 RETURN NULL
RETURN @I
END
GO
-- Testing
DECLARE @Test TABLE(Value nvarchar(50)) -- Result
INSERT INTO @Test SELECT '1234' -- 1234
INSERT INTO @Test SELECT '1,234' -- 1234
INSERT INTO @Test SELECT '1234.0' -- 1234
INSERT INTO @Test SELECT '-1234' -- -1234
INSERT INTO @Test SELECT '$1234' -- NULL
INSERT INTO @Test SELECT '1234e10' -- NULL
INSERT INTO @Test SELECT '1234 5678' -- NULL
INSERT INTO @Test SELECT '123-456' -- NULL
INSERT INTO @Test SELECT '1234.5' -- NULL
INSERT INTO @Test SELECT '123456789000000' -- NULL
INSERT INTO @Test SELECT 'N/A' -- NULL
SELECT Value, dbo.TryConvertInt(Value) FROM @Test
Reference: I used this page extensively when creating my solution.
All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.
https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337
Some snippets from the above link:
"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "
"The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables."
" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "
I think this could be useful for you.
const myObject = {_x000D_
"a":"a",_x000D_
"b":{_x000D_
"c":"c",_x000D_
"d":{_x000D_
"e":"e",_x000D_
"f":{_x000D_
"g":"g",_x000D_
"h":{_x000D_
"i":"i"_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
console.log(JSON.stringify(myObject, null, '\t'));
_x000D_
As mentioned in this answer:
JSON.stringify
's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces).
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
Click "view details" to find the inner exception.
- Each time you append or do any modification with it, it creates a new String
object.
- So use append()
method of StringBuilder
(If thread safety is not important), else use StringBuffer
(If thread safety is important.), that will be efficient way to do it.
In my case, I was missing a dependency in the app level build.gradle.
The solution was to add the dependency as google outlines below:
Open the app-level build.gradle file for your app, and look for a "dependencies" section.
dependencies {
implementation ...SOME_IMPLEMENTATION
implementation ...SOME_IMPLEMENTATION
implementation 'com.google.android.gms:play-services-ads:18.1.1'//<---ADD THIS LINE
}
Add the line above, which instruct Gradle to pull in the latest version of the Mobile Ads SDK and additional related dependencies. Once that's done, save the file and perform a Gradle sync.
If you use RelativeLayout
, you can do it something like this:
<RelativeLayout
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<ImageView
android:id = "@+id/my_image"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignParentTop ="true" />
<RelativeLayout
android:id="@+id/layout_bottom"
android:layout_width="fill_parent"
android:layout_height = "50dp"
android:layout_alignParentBottom = "true">
<Button
android:id = "@+id/but_left"
android:layout_width = "80dp"
android:layout_height = "wrap_content"
android:text="<"
android:layout_alignParentLeft = "true"/>
<TextView
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:layout_toLeftOf = "@+id/but_right"
android:layout_toRightOf = "@id/but_left" />
<Button
android:id = "@id/but_right"
android:layout_width = "80dp"
android:layout_height = "wrap_content"
android:text=">"
android:layout_alignParentRight = "true"/>
</RelativeLayout>
</RelativeLayout>
I guess the quickest way is just to disable the domain check while you're developing it
Connections have a close
method as specified in PEP-249 (Python Database API Specification v2.0):
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
conn.close() #<--- Close the connection
Since the pyodbc
connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:
import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
with conn:
crs = conn.cursor()
do_stuff
# conn.commit() will automatically be called when Python leaves the outer `with` statement
# Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!!
See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.
Note that unlike the original code, this causes conn.commit()
to be called. Use the outer with
statement to control when you want commit
to be called.
Also note that regardless of whether or not you use the with
statements, per the docs,
Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [
conn.close()
], but you can explicitly close the connection if you wish.
and similarly for cursors (my emphasis):
Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [
csr.close()
] is not usually necessary.
On laravel 8.* I following steps work for me :
Run command composer remove package-name
on terminal
Remove Provider
and aliases
from Config/app.php
Remove related file from Config folder.
Remove from your code where you used .
JSmooth .exe wrapper
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your Java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a website.
JSmooth provides a variety of wrappers for your java application, each of them having their own behavior: Choose your flavor!
Download: http://jsmooth.sourceforge.net/
JarToExe 1.8 Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe on their website:
Can generate “Console”, “Windows GUI”, “Windows Service” three types of .exe files.
Generated .exe files can add program icons and version information. Generated .exe files can encrypt and protect java programs, no temporary files will be generated when the program runs.
Generated .exe files provide system tray icon support. Generated .exe files provide record system event log support. Generated windows service .exe files are able to install/uninstall itself, and support service pause/continue.
Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows .exe file, indistinguishable from a native application. Simply double-clicking the .exe file will invoke the Java Runtime Environment and launch your application.
Just do that: getTabAt(index of your tab)
ActionBar actionBar = getSupportActionBar();
actionBar.selectTab(actionBar.getTabAt(0));
In my case I didn't want to create a new Activity only to show a image for 2 seconds. When starting my MainAvtivity
, images gets loaded into holders using picasso, I know that this takes about 1 second to load so I decided to do the following inside my MainActivity OnCreate
:
splashImage = (ImageView) findViewById(R.id.spllll);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
int secondsDelayed = 1;
new Handler().postDelayed(new Runnable() {
public void run() {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
splashImage.setVisibility(View.GONE);
}
}, secondsDelayed * 2000);
When starting the application the first thing that happens is the ImageView
gets displayed and the statusBar is removed by setting the window flags to full screen. Then I used a Handler
to run for 2 seconds, after the 2 seconds I clear the full screen flags and set the visibility of the ImageView
to GONE
. Easy, simple, effective.
Simplify in a similar fashion to what you had in mind:
DO
$do$
BEGIN
IF NOT EXISTS (
SELECT FROM pg_catalog.pg_roles -- SELECT list can be empty for this
WHERE rolname = 'my_user') THEN
CREATE ROLE my_user LOGIN PASSWORD 'my_password';
END IF;
END
$do$;
(Building on @a_horse_with_no_name's answer and improved with @Gregory's comment.)
Unlike, for instance, with CREATE TABLE
there is no IF NOT EXISTS
clause for CREATE ROLE
(up to at least pg 12). And you cannot execute dynamic DDL statements in plain SQL.
Your request to "avoid PL/pgSQL" is impossible except by using another PL. The DO
statement uses plpgsql as default procedural language. The syntax allows to omit the explicit declaration:
DO [ LANGUAGE
lang_name
] code
...
lang_name
The name of the procedural language the code is written in. If omitted, the default isplpgsql
.
You'll want to listen for escape's keyCode
(27) from the React SyntheticKeyBoardEvent
onKeyDown
:
const EscapeListen = React.createClass({
handleKeyDown: function(e) {
if (e.keyCode === 27) {
console.log('You pressed the escape key!')
}
},
render: function() {
return (
<input type='text'
onKeyDown={this.handleKeyDown} />
)
}
})
Brad Colthurst's CodePen posted in the question's comments is helpful for finding key codes for other keys.
I had this problem on a project I run on Netbeans. I simply right clicked on the file and update to fix it (after SVN up).
//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]
The reason why I add this answer is that I want to explain the relationship of .
and text()
.
The first thing is when using []
, there are only two types of data:
[number]
to select a node from node-set[bool]
to filter a node-set from node-setIn this case, the value is evaluated to boolean by function boolean()
, and there is a rule:
Filters are always evaluated with respect to a context.
When you need to compare text()
or .
with a string "Data"
, it first uses string()
function to transform those to string type, than gets a boolean result.
There are two important rule about string()
:
The string()
function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.
text()
is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]
.
When it is evaluated by string(["Data"])
, it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.
If you want the string()
function to concatenate all child text, you must then pass a single node instead of a node-set.
For example, we get a node-set ['a', 'b']
, you can pass there parent node to string(parent)
, this will return 'ab'
, and of cause string(.)
in you case will return an concatenated string "Data"
.
Both way will get same result only when there is a text node.
In a bootstrap environment none of the top answers helped, but applying the following removed all borders:
.noBorder {
border:none !important;
}
Applied as:
<td class="noBorder">
The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.