In reference to the error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified.
That error means that the Data Source Name (DSN) you are specifying in your connection configuration is not being found in the windows registry.
It is important that your ODBC driver's executable and linking format (ELF) is the same as your application. In other words, you need a 32-bit driver for a 32-bit application or a 64-bit driver for a 64-bit application.
If these do not match, it is possible to configure a DSN for a 32-bit driver and when you attempt to use that DSN in a 64-bit application, the DSN won't be found because the registry holds DSN information in different places depending on ELF (32-bit versus 64-bit).
Be sure you are using the correct ODBC Administrator tool. On 32-bit and 64-bit Windows, the default ODBC Administrator tool is in c:\Windows\System32\odbcad32.exe
. However, on a 64-bit Windows machine, the default is the 64-bit version. If you need to use the 32-bit ODBC Administrator tool on a 64-bit Windows system, you will need to run the one found here: C:\Windows\SysWOW64\odbcad32.exe
Where I see this tripping people up is when a user uses the default 64-bit ODBC Administrator to configure a DSN; thinking it is for a 32-bit DSN. Then when the 32-bit application attempts to connect using that DSN, "Data source not found..." occurs.
It's also important to make sure the spelling of the DSN matches that of the configured DSN in the ODBC Administrator. One letter wrong is all it takes for a DSN to be mismatched.
Here is an article that may provide some additional details
It may not be the same product brand that you have, however; it is a generic problem that is encountered when using ODBC data source names.
In reference to the OLE DB Provider portion of your question, it appears to be a similar type of problem where the application is not able to locate the configuration for the specified provider.
You can install the Active Directory snap-in with Powershell on Windows Server 2012 using the following command:
Install-windowsfeature -name AD-Domain-Services –IncludeManagementTools
This helped me when I had problems with the Features screen due to AppFabric and Windows Update errors.
For a thread you have the myThread.IsAlive
property. It is false if the thread method returned or the thread was aborted.
While we're big fans of Deis (deis.io) and are actively deploying to it, there are other Heroku like PaaS style deployment solutions out there, including:
Longshoreman from the Wayfinder folks:
https://github.com/longshoreman/longshoreman
Decker from the CloudCredo folks, using CloudFoundry:
http://www.cloudcredo.com/decker-docker-cloud-foundry/
As for straight up orchestration, NewRelic's opensource Centurion project seems quite promising:
A common solution is to make a base view model which contains the properties used in the layout file and then inherit from the base model to the models used on respective pages.
The problem with this approach is that you now have locked yourself into the problem of a model can only inherit from one other class, and maybe your solution is such that you cannot use inheritance on the model you intended anyways.
My solution also starts of with a base view model:
public class LayoutModel
{
public LayoutModel(string title)
{
Title = title;
}
public string Title { get;}
}
What I then use is a generic version of the LayoutModel which inherits from the LayoutModel, like this:
public class LayoutModel<T> : LayoutModel
{
public LayoutModel(T pageModel, string title) : base(title)
{
PageModel = pageModel;
}
public T PageModel { get; }
}
With this solution I have disconnected the need of having inheritance between the layout model and the model.
So now I can go ahead and use the LayoutModel in Layout.cshtml like this:
@model LayoutModel
<!doctype html>
<html>
<head>
<title>@Model.Title</title>
</head>
<body>
@RenderBody()
</body>
</html>
And on a page you can use the generic LayoutModel like this:
@model LayoutModel<Customer>
@{
var customer = Model.PageModel;
}
<p>Customer name: @customer.Name</p>
From your controller you simply return a model of type LayoutModel:
public ActionResult Page()
{
return View(new LayoutModel<Customer>(new Customer() { Name = "Test" }, "Title");
}
To use the push function of an Array your var needs to be an Array.
Change data{"name":"ananta","age":"15"}
to following:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
The containing Array Items will be typeof Object and you can do following:
var text = "You are " + data[0]->age + " old and come from " + data[0]->country;
Notice: Try to be consistent. In my example, one array contained object properties name
and age
while the other only contains country
. If I iterate this with for
or forEach
then I can't always check for one property, because my example contains Items that changing.
Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );
So you can iterate and always can get the properties, even if they are empty, null or undefined.
edit
Cool stuff to know:
var array = new Array();
is similar to:
var array = [];
Also:
var object = new Object();
is similar to:
var object = {};
You also can combine them:
var objectArray = [{}, {}, {}];
Leave visible columns before filling the GridView
. Fill the GridView
and then hide the columns.
Take a look at the domReady script that allows setting up of multiple functions to execute when the DOM has loaded. It's basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.
Example usage
// add reference to domReady script or place
// contents of script before here
function codeAddress() {
}
domReady(codeAddress);
The proper way to invoke javascript code when clicking a link would be to add an onclick
handler:
<a href="#" onclick="myFunction()">LinkText</a>
Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded.
Here is a JS function that converts "Country Code" (ISO3) to Telephone "Calling Code":
function country_iso3_to_country_calling_code(country_iso3) {
if(country_iso3 == 'AFG') return '93';
if(country_iso3 == 'ALB') return '355';
if(country_iso3 == 'DZA') return '213';
if(country_iso3 == 'ASM') return '1684';
if(country_iso3 == 'AND') return '376';
if(country_iso3 == 'AGO') return '244';
if(country_iso3 == 'AIA') return '1264';
if(country_iso3 == 'ATA') return '672';
if(country_iso3 == 'ATG') return '1268';
if(country_iso3 == 'ARG') return '54';
if(country_iso3 == 'ARM') return '374';
if(country_iso3 == 'ABW') return '297';
if(country_iso3 == 'AUS') return '61';
if(country_iso3 == 'AUT') return '43';
if(country_iso3 == 'AZE') return '994';
if(country_iso3 == 'BHS') return '1242';
if(country_iso3 == 'BHR') return '973';
if(country_iso3 == 'BGD') return '880';
if(country_iso3 == 'BRB') return '1246';
if(country_iso3 == 'BLR') return '375';
if(country_iso3 == 'BEL') return '32';
if(country_iso3 == 'BLZ') return '501';
if(country_iso3 == 'BEN') return '229';
if(country_iso3 == 'BMU') return '1441';
if(country_iso3 == 'BTN') return '975';
if(country_iso3 == 'BOL') return '591';
if(country_iso3 == 'BIH') return '387';
if(country_iso3 == 'BWA') return '267';
if(country_iso3 == 'BVT') return '_55';
if(country_iso3 == 'BRA') return '55';
if(country_iso3 == 'IOT') return '1284';
if(country_iso3 == 'BRN') return '673';
if(country_iso3 == 'BGR') return '359';
if(country_iso3 == 'BFA') return '226';
if(country_iso3 == 'BDI') return '257';
if(country_iso3 == 'KHM') return '855';
if(country_iso3 == 'CMR') return '237';
if(country_iso3 == 'CAN') return '1';
if(country_iso3 == 'CPV') return '238';
if(country_iso3 == 'CYM') return '1345';
if(country_iso3 == 'CAF') return '236';
if(country_iso3 == 'TCD') return '235';
if(country_iso3 == 'CHL') return '56';
if(country_iso3 == 'CHN') return '86';
if(country_iso3 == 'CXR') return '618';
if(country_iso3 == 'CCK') return '61';
if(country_iso3 == 'COL') return '57';
if(country_iso3 == 'COM') return '269';
if(country_iso3 == 'COG') return '242';
if(country_iso3 == 'COD') return '243';
if(country_iso3 == 'COK') return '682';
if(country_iso3 == 'CRI') return '506';
if(country_iso3 == 'HRV') return '385';
if(country_iso3 == 'CUB') return '53';
if(country_iso3 == 'CYP') return '357';
if(country_iso3 == 'CZE') return '420';
if(country_iso3 == 'DNK') return '45';
if(country_iso3 == 'DJI') return '253';
if(country_iso3 == 'DMA') return '1767';
if(country_iso3 == 'DOM') return '1';
if(country_iso3 == 'ECU') return '593';
if(country_iso3 == 'EGY') return '20';
if(country_iso3 == 'SLV') return '503';
if(country_iso3 == 'GNQ') return '240';
if(country_iso3 == 'ERI') return '291';
if(country_iso3 == 'EST') return '372';
if(country_iso3 == 'ETH') return '251';
if(country_iso3 == 'FLK') return '500';
if(country_iso3 == 'FRO') return '298';
if(country_iso3 == 'FJI') return '679';
if(country_iso3 == 'FIN') return '358';
if(country_iso3 == 'FRA') return '33';
if(country_iso3 == 'GUF') return '594';
if(country_iso3 == 'PYF') return '689';
if(country_iso3 == 'GAB') return '241';
if(country_iso3 == 'GMB') return '220';
if(country_iso3 == 'GEO') return '995';
if(country_iso3 == 'DEU') return '49';
if(country_iso3 == 'GHA') return '233';
if(country_iso3 == 'GIB') return '350';
if(country_iso3 == 'GRC') return '30';
if(country_iso3 == 'GRL') return '299';
if(country_iso3 == 'GRD') return '1473';
if(country_iso3 == 'GLP') return '590';
if(country_iso3 == 'GUM') return '1671';
if(country_iso3 == 'GTM') return '502';
if(country_iso3 == 'GIN') return '224';
if(country_iso3 == 'GNB') return '245';
if(country_iso3 == 'GUY') return '592';
if(country_iso3 == 'HTI') return '509';
if(country_iso3 == 'HMD') return '61';
if(country_iso3 == 'VAT') return '3';
if(country_iso3 == 'HND') return '504';
if(country_iso3 == 'HKG') return '852';
if(country_iso3 == 'HUN') return '36';
if(country_iso3 == 'ISL') return '354';
if(country_iso3 == 'IND') return '91';
if(country_iso3 == 'IDN') return '62';
if(country_iso3 == 'IRN') return '98';
if(country_iso3 == 'IRQ') return '964';
if(country_iso3 == 'IRL') return '353';
if(country_iso3 == 'ISR') return '972';
if(country_iso3 == 'ITA') return '39';
if(country_iso3 == 'CIV') return '225';
if(country_iso3 == 'JAM') return '1876';
if(country_iso3 == 'JPN') return '81';
if(country_iso3 == 'JOR') return '962';
if(country_iso3 == 'KAZ') return '7';
if(country_iso3 == 'KEN') return '254';
if(country_iso3 == 'KIR') return '686';
if(country_iso3 == 'PRK') return '850';
if(country_iso3 == 'KOR') return '82';
if(country_iso3 == 'KWT') return '965';
if(country_iso3 == 'KGZ') return '7';
if(country_iso3 == 'LAO') return '856';
if(country_iso3 == 'LVA') return '371';
if(country_iso3 == 'LBN') return '961';
if(country_iso3 == 'LSO') return '266';
if(country_iso3 == 'LBR') return '231';
if(country_iso3 == 'LBY') return '218';
if(country_iso3 == 'LIE') return '423';
if(country_iso3 == 'LTU') return '370';
if(country_iso3 == 'LUX') return '352';
if(country_iso3 == 'MAC') return '853';
if(country_iso3 == 'MKD') return '389';
if(country_iso3 == 'MDG') return '261';
if(country_iso3 == 'MWI') return '265';
if(country_iso3 == 'MYS') return '60';
if(country_iso3 == 'MDV') return '960';
if(country_iso3 == 'MLI') return '223';
if(country_iso3 == 'MLT') return '356';
if(country_iso3 == 'MHL') return '692';
if(country_iso3 == 'MTQ') return '596';
if(country_iso3 == 'MRT') return '222';
if(country_iso3 == 'MUS') return '230';
if(country_iso3 == 'MYT') return '262';
if(country_iso3 == 'MEX') return '52';
if(country_iso3 == 'FSM') return '691';
if(country_iso3 == 'MDA') return '373';
if(country_iso3 == 'MCO') return '377';
if(country_iso3 == 'MNG') return '976';
if(country_iso3 == 'MSR') return '1664';
if(country_iso3 == 'MAR') return '212';
if(country_iso3 == 'MOZ') return '258';
if(country_iso3 == 'MMR') return '95';
if(country_iso3 == 'NAM') return '264';
if(country_iso3 == 'NRU') return '674';
if(country_iso3 == 'NPL') return '977';
if(country_iso3 == 'NLD') return '31';
if(country_iso3 == 'ANT') return '599';
if(country_iso3 == 'NCL') return '687';
if(country_iso3 == 'NZL') return '64';
if(country_iso3 == 'NIC') return '505';
if(country_iso3 == 'NER') return '227';
if(country_iso3 == 'NGA') return '234';
if(country_iso3 == 'NIU') return '683';
if(country_iso3 == 'NFK') return '672';
if(country_iso3 == 'MNP') return '1670';
if(country_iso3 == 'NOR') return '47';
if(country_iso3 == 'OMN') return '968';
if(country_iso3 == 'PAK') return '92';
if(country_iso3 == 'PLW') return '680';
if(country_iso3 == 'PSE') return '970';
if(country_iso3 == 'PAN') return '507';
if(country_iso3 == 'PNG') return '675';
if(country_iso3 == 'PRY') return '595';
if(country_iso3 == 'PER') return '51';
if(country_iso3 == 'PHL') return '63';
if(country_iso3 == 'PCN') return '870';
if(country_iso3 == 'POL') return '48';
if(country_iso3 == 'PRT') return '351';
if(country_iso3 == 'PRI') return '1';
if(country_iso3 == 'QAT') return '974';
if(country_iso3 == 'REU') return '262';
if(country_iso3 == 'ROM') return '40';
if(country_iso3 == 'RUS') return '7';
if(country_iso3 == 'RWA') return '250';
if(country_iso3 == 'SHN') return '290';
if(country_iso3 == 'KNA') return '1869';
if(country_iso3 == 'LCA') return '1758';
if(country_iso3 == 'SPM') return '508';
if(country_iso3 == 'VCT') return '1758';
if(country_iso3 == 'WSM') return '685';
if(country_iso3 == 'SMR') return '378';
if(country_iso3 == 'STP') return '239';
if(country_iso3 == 'SAU') return '966';
if(country_iso3 == 'SEN') return '221';
if(country_iso3 == 'SRB') return '381';
if(country_iso3 == 'SYC') return '248';
if(country_iso3 == 'SLE') return '232';
if(country_iso3 == 'SGP') return '65';
if(country_iso3 == 'SVK') return '421';
if(country_iso3 == 'SVN') return '386';
if(country_iso3 == 'SLB') return '677';
if(country_iso3 == 'SOM') return '252';
if(country_iso3 == 'ZAF') return '27';
if(country_iso3 == 'SGS') return '44';
if(country_iso3 == 'ESP') return '34';
if(country_iso3 == 'LKA') return '94';
if(country_iso3 == 'SDN') return '249';
if(country_iso3 == 'SUR') return '597';
if(country_iso3 == 'SJM') return '47';
if(country_iso3 == 'SWZ') return '268';
if(country_iso3 == 'SWE') return '46';
if(country_iso3 == 'CHE') return '41';
if(country_iso3 == 'SYR') return '963';
if(country_iso3 == 'TWN') return '886';
if(country_iso3 == 'TJK') return '992';
if(country_iso3 == 'TZA') return '255';
if(country_iso3 == 'THA') return '66';
if(country_iso3 == 'TLS') return '670';
if(country_iso3 == 'TGO') return '228';
if(country_iso3 == 'TKL') return '690';
if(country_iso3 == 'TON') return '676';
if(country_iso3 == 'TTO') return '1868';
if(country_iso3 == 'TUN') return '216';
if(country_iso3 == 'TUR') return '90';
if(country_iso3 == 'TKM') return '993';
if(country_iso3 == 'TCA') return '1649';
if(country_iso3 == 'TUV') return '688';
if(country_iso3 == 'UGA') return '256';
if(country_iso3 == 'UKR') return '380';
if(country_iso3 == 'ARE') return '971';
if(country_iso3 == 'GBR') return '44';
if(country_iso3 == 'USA') return '1';
if(country_iso3 == 'UMI') return '1340';
if(country_iso3 == 'URY') return '598';
if(country_iso3 == 'UZB') return '998';
if(country_iso3 == 'VUT') return '678';
if(country_iso3 == 'VEN') return '58';
if(country_iso3 == 'VNM') return '84';
if(country_iso3 == 'VGB') return '1284';
if(country_iso3 == 'VIR') return '1340';
if(country_iso3 == 'WLF') return '681';
if(country_iso3 == 'YEM') return '260';
if(country_iso3 == 'ZMB') return '260';
if(country_iso3 == 'ZWE') return '263';
}
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
Similar to what Richard Detsch but with a bit easier to follow (works with packages as well)
Step 1: Unwrap the War file.
jar -xvf MyWar.war
Step 2: move into the directory
cd WEB-INF
Step 3: Run your main with all dependendecies
java -classpath "lib/*:classes/." my.packages.destination.FileToRun
For others in my situation, the solution was:
qmake -qt=qt5
This was on Ubuntu 14.04 after install qt5-qmake. qmake was a symlink to qtchooser which takes the -qt argument.
No, there is not really any other way : if you have many locations and want to display them on a map, the best solution is to :
This is, of course, considering that you have a lot less creation/modification of locations than you have consultations of locations.
Yes, it means you'll have to do a bit more work when saving the locations -- but it also means :
This worked for me:
I removed the single quotes.
I then used a replace ","
with "."
.
Surely this will help someone:
" & txtFinalscore.Text.Replace(",", ".") & "
They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).
In your example "HelveticaNeue-Light"
will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light"
and finally "Helvetica Neue"
.
As far as I'm aware "Helvetica Neue"
isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif"
or "sans-serif"
as a final default position.
In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.
A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.
You've gotten several good answers and I'd go with the Bash builtin myself, but since you asked about sed
and awk
and (almost) no one else offered solutions based on them, I offer you these:
echo "USCAGoleta9311734.5021-120.1287855805" | awk '{print substr($0,0,2)}'
and
echo "USCAGoleta9311734.5021-120.1287855805" | sed 's/\(^..\).*/\1/'
The awk
one ought to be fairly obvious, but here's an explanation of the sed
one:
When you killed the session, the session hangs around for a while in "KILLED" status while Oracle cleans up after it.
If you absolutely must, you can kill the OS process as well (look up v$process.spid
), which would release any locks it was holding on to.
See this for more detailed info.
I would say to just grab the underlying RDD
. In Scala:
df.rdd.isEmpty
in Python:
df.rdd.isEmpty()
That being said, all this does is call take(1).length
, so it'll do the same thing as Rohan answered...just maybe slightly more explicit?
It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:
unsigned int x = N;
In fact, we can create algorithms which evaluate at compile time (from Wikipedia):
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
The lack of a Linux-like backtick/backquote facility is a major annoyance of the pre-PowerShell world. Using backquotes via for-loops is not at all cosy. So we need kinda of setvar myvar cmd-line
command.
In my %path%
I have a dir with a number of bins and batches to cope with those Win shortcomings.
One batch I wrote is:
:: setvar varname cmd
:: Set VARNAME to the output of CMD
:: Triple escape pipes, eg:
:: setvar x dir c:\ ^^^| sort
:: -----------------------------
@echo off
SETLOCAL
:: Get command from argument
for /F "tokens=1,*" %%a in ("%*") do set cmd=%%b
:: Get output and set var
for /F "usebackq delims=" %%a in (`%cmd%`) do (
ENDLOCAL
set %1=%%a
)
:: Show results
SETLOCAL EnableDelayedExpansion
echo %1=!%1!
So in your case, you would type:
> setvar text echo Hello
text=Hello
The script informs you of the results, which means you can:
> echo text var is now %text%
text var is now Hello
You can use whatever command:
> setvar text FIND "Jones" names.txt
What if the command you want to pipe to some variable contains itself a pipe?
Triple escape it, ^^^|
:
> setvar text dir c:\ ^^^| find "Win"
Use the timeit module. It's very easy. Run your example.py file so it is active in the Python Shell, you should now be able to call your function in the shell. Try it out to check it works
>>>fun(input)
output
Good, that works, now import timeit and set up a timer
>>>import timeit
>>>t = timeit.Timer('example.fun(input)','import example')
>>>
Now we have our timer set up we can see how long it takes
>>>t.timeit(number=1)
some number here
And there we go, it will tell you how many seconds (or less) it took to execute that function. If it's a simple function then you can increase it to t.timeit(number=1000) (or any number!) and then divide the answer by the number to get the average.
I hope this helps.
If that <p>
tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support '&:hover'
. https://cssinjs.org/
You could use Extension
method to switch between Regular Style and Bold Style as below:
static class Helper
{
public static void SwtichToBoldRegular(this TextBox c)
{
if (c.Font.Style!= FontStyle.Bold)
c.Font = new Font(c.Font, FontStyle.Bold);
else
c.Font = new Font(c.Font, FontStyle.Regular);
}
}
And usage:
textBox1.SwtichToBoldRegular();
I know this is an old thread but it might be useful for some people such as myself that months after are hitting this issue for the first time.
Here is some code that resizes the image every time you reload the image. I am aware this is not optimal at all, but I provide it as a proof of concept.
Also, sorry for using jQuery for simple selectors but I just feel too comfortable with the syntax.
$(document).on('ready', createImage);_x000D_
$(window).on('resize', createImage);_x000D_
_x000D_
var createImage = function(){_x000D_
var canvas = document.getElementById('myCanvas');_x000D_
canvas.width = window.innerWidth || $(window).width();_x000D_
canvas.height = window.innerHeight || $(window).height();_x000D_
var ctx = canvas.getContext('2d');_x000D_
img = new Image();_x000D_
img.addEventListener('load', function () {_x000D_
ctx.drawImage(this, 0, 0, w, h);_x000D_
});_x000D_
img.src = 'http://www.ruinvalor.com/Telanor/images/original.jpg';_x000D_
};
_x000D_
html, body{_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background: #000;_x000D_
}_x000D_
canvas{_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
z-index: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Canvas Resize</title>_x000D_
</head>_x000D_
<body>_x000D_
<canvas id="myCanvas"></canvas>_x000D_
</body>_x000D_
</html>
_x000D_
My createImage function is called once when the document is loaded and after that it is called every time the window receives a resize event.
I tested it in Chrome 6 and Firefox 3.6, both on the Mac. This "technique" eats processor as it if was ice cream in the summer, but it does the trick.
For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it:
Button btn = new Button (this);
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
btn.setHeight((int)(display.getHeight()*0.68));
Never alter the container you're looping on, because iterators on that container are not going to be informed of your alterations and, as you've noticed, that's quite likely to produce a very different loop and/or an incorrect one. In normal cases, looping on a copy of the container helps, but in your case it's clear that you don't want that, as the container will be empty after 50 legs of the loop and if you then try popping again you'll get an exception.
What's anything BUT clear is, what behavior are you trying to achieve, if any?! Maybe you can express your desires with a while
...?
i = 0
while i < len(some_list):
print i,
print some_list.pop(0),
print some_list.pop(0)
A better approach from the correct solution here in order to not alter target:
function extend(){
let sources = [].slice.call(arguments, 0), result = {};
sources.forEach(function (source) {
for (let prop in source) {
result[prop] = source[prop];
}
});
return result;
}
The best way could be to save all the emails in a database.
You can try this code, assuming you have your email in a database
/*Your connection to your database comes here*/
$query="select email from yourtable";
$result =mysql_query($query);
/the above code depends on where you saved your email addresses, so make sure you replace it with your parameters/
Then you can make a comma separated string from the result,
while($row=$result->fetch_array()){
if($rows=='') //this prevents from inserting comma on before the first element
$rows.=$row['email'];
else
$rows.=','.$row['email'];
}
Now you can use
$to = explode(',',$rows); // to change to array
$string =implode(',',$cc); //to get back the string separated by comma
With above code you can send the email like this
mail($string, "Test", "Hi, Happy X-Mas and New Year");
You should use the OpenFileDialog class like this
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
strFileName = fd.FileName
End If
Then you can use the File class.
In this answer, will be two sections: Two unique solutions, and a graph of speed for specific solutions.
Most of these answers only remove duplicate items which are hashable, but this question doesn't imply it doesn't just need hashable items, meaning I'll offer some solutions which don't require hashable items.
collections.Counter is a powerful tool in the standard library which could be perfect for this. There's only one other solution which even has Counter in it. However, that solution is also limited to hashable keys.
To allow unhashable keys in Counter, I made a Container class, which will try to get the object's default hash function, but if it fails, it will try its identity function. It also defines an eq and a hash method. This should be enough to allow unhashable items in our solution. Unhashable objects will be treated as if they are hashable. However, this hash function uses identity for unhashable objects, meaning two equal objects that are both unhashable won't work. I suggest you override this, and changing it to use the hash of an equivalent mutable type (like using hash(tuple(my_list))
if my_list
is a list).
I also made two solutions. Another solution which keeps the order of the items, using a subclass of both OrderedDict and Counter which is named 'OrderedCounter'. Now, here are the functions:
from collections import OrderedDict, Counter
class Container:
def __init__(self, obj):
self.obj = obj
def __eq__(self, obj):
return self.obj == obj
def __hash__(self):
try:
return hash(self.obj)
except:
return id(self.obj)
class OrderedCounter(Counter, OrderedDict):
'Counter that remembers the order elements are first encountered'
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))
def __reduce__(self):
return self.__class__, (OrderedDict(self),)
def remd(sequence):
cnt = Counter()
for x in sequence:
cnt[Container(x)] += 1
return [item.obj for item in cnt]
def oremd(sequence):
cnt = OrderedCounter()
for x in sequence:
cnt[Container(x)] += 1
return [item.obj for item in cnt]
remd is non-ordered sorting, oremd is ordered sorting. You can clearly tell which one is faster, but I'll explain anyways. The non-ordered sorting is slightly faster. It keeps less data, since it doesn't need order.
Now, I also wanted to show the speed comparisons of each answer. So, I'll do that now.
For removing duplicates, I gathered 10 functions from a few answers. I calculated the speed of each function and put it into a graph using matplotlib.pyplot.
I divided this into three rounds of graphing. A hashable is any object which can be hashed, an unhashable is any object which cannot be hashed. An ordered sequence is a sequence which preserves order, an unordered sequence does not preserve order. Now, here are a few more terms:
Unordered Hashable was for any method which removed duplicates, which didn't necessarily have to keep the order. It didn't have to work for unhashables, but it could.
Ordered Hashable was for any method which kept the order of the items in the list, but it didn't have to work for unhashables, but it could.
Ordered Unhashable was any method which kept the order of the items in the list, and worked for unhashables.
On the y-axis is the amount of seconds it took.
On the x-axis is the number the function was applied to.
We generated sequences for unordered hashables and ordered hashables with the following comprehension: [list(range(x)) + list(range(x)) for x in range(0, 1000, 10)]
For ordered unhashables: [[list(range(y)) + list(range(y)) for y in range(x)] for x in range(0, 1000, 10)]
Note there is a 'step' in the range because without it, this would've taken 10x as long. Also because in my personal opinion, I thought it might've looked a little easier to read.
Also note the keys on the legend are what I tried to guess as the most vital parts of the function. As for what function does the worst or best? The graph speaks for itself.
With that settled, here are the graphs.
You can create a .a
file using the ar
utility, like so:
ar crf lib/libHeader.a header.o
lib
is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a
in the directory lib
. So, in your current directory, do:
mkdir lib
Then run the above ar
command.
When linking all libraries, you can do it like so:
g++ test.o -L./lib -lHeader -o test
The -L
flag will get g++
to add the lib/
directory to the path. This way, g++
knows what directory to search when looking for libHeader
. -llibHeader
flags the specific library to link.
where test.o is created like so:
g++ -c test.cpp -o test.o
I've occasionally thought that it might serve a purpose to add a layer of security by obscuring the back-end interpreter through a remapping of .php or whatever to .aspx or whatever so that any potential hacker would be sent down the wrong path, at least for a while. I never bothered to try it and I don't do a lot of webserver work any more so I'm unlikely to.
However, I'd be interested in the perspective of an experienced server admin on that notion.
If you are using Spring, you can force validation by annotating the class with @Validated
:
import org.springframework.validation.annotation.Validated;
More info available here: Javax validation @NotNull annotation usage
Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
<key>
<key>
<key> <start> <end>
<key>
<key> <min> <max>
Use the TYPE
command to check the type of value a key is mapping to:
<key>
Entire request and response is encrypted, including URL.
Note that when you use a HTTP Proxy, it knows the address (domain) of the target server, but doesn't know the requested path on this server (i.e. request and response are always encrypted).
Recently I also find the same problem and there some reasons behind this but I am giving you 3
It must work.
Simple math..
def average(n):
result = 0
for i in n:
result += i
ave_num = result / len(n)
return ave_num
input -> [1,2,3,4,5]
output -> 3.0
If you want to pull a directory with restricted access from a rooted device you need to restart adb as root: type adb root
before pull. Otherwise you'll get an error saying remote object '/data/data/xxx.example.app' does not exist
XOR is Exclusive Or. It means "One of the two items being XOR'd is true, but not both of them."
TRUE XOR TRUE : FALSE
TRUE XOR FALSE : TRUE
FALSE XOR TRUE : TRUE
FALSE XOR FALSE: FALSE
XAND I have not heard of.
Just use multiple in-clauses to get around this:
select field1, field2, field3 from table1
where name in ('value1', 'value2', ..., 'value999')
or name in ('value1000', ..., 'value1999')
or ...;
iter is a very small package that just provides a syntantically different way to iterate over integers.
for i := range iter.N(4) {
fmt.Println(i)
}
Rob Pike (an author of Go) has criticized it:
It seems that almost every time someone comes up with a way to avoid doing something like a for loop the idiomatic way, because it feels too long or cumbersome, the result is almost always more keystrokes than the thing that is supposedly shorter. [...] That's leaving aside all the crazy overhead these "improvements" bring.
This builds upon @Pavel's answer, to solve the possibility of Spring context not being initialized when accessing from the static getBean method:
@Component
public class Spring {
private static final Logger LOG = LoggerFactory.getLogger (Spring.class);
private static Spring spring;
@Autowired
private ApplicationContext context;
@PostConstruct
public void registerInstance () {
spring = this;
}
private Spring (ApplicationContext context) {
this.context = context;
}
private static synchronized void initContext () {
if (spring == null) {
LOG.info ("Initializing Spring Context...");
ApplicationContext context = new AnnotationConfigApplicationContext (io.zeniq.spring.BaseConfig.class);
spring = new Spring (context);
}
}
public static <T> T getBean(String name, Class<T> className) throws BeansException {
initContext();
return spring.context.getBean(name, className);
}
public static <T> T getBean(Class<T> className) throws BeansException {
initContext();
return spring.context.getBean(className);
}
public static AutowireCapableBeanFactory getBeanFactory() throws IllegalStateException {
initContext();
return spring.context.getAutowireCapableBeanFactory ();
}
}
The important piece here is the initContext
method. It ensures that the context will always get initialized. But, do note that initContext
will be a point of contention in your code as it is synchronized. If your application is heavily parallelized (for eg: the backend of a high traffic site), this might not be a good solution for you.
this is a simple alternative that gives all responses, Fullname, Path, filename.
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
I have used the Unity 3D game engine for developing games for the PC and mobile phone. We use C# in this development.
How about like this
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
return HiddenFor(htmlHelper, expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
{
return htmlHelper.Hidden(ExpressionHelper.GetExpressionText(expression), value, htmlAttributes);
}
Use it like this
@Html.HiddenFor(customerId => reviewModel.CustomerId, Site.LoggedInCustomerId, null)
Like the answer above but here is using bootstrap 3 names and colours:
/*css to add back colours for badges and make use of the colours*/_x000D_
.badge-default {_x000D_
background-color: #999999;_x000D_
}_x000D_
_x000D_
.badge-primary {_x000D_
background-color: #428bca;_x000D_
}_x000D_
_x000D_
.badge-success {_x000D_
background-color: #5cb85c;_x000D_
}_x000D_
_x000D_
.badge-info {_x000D_
background-color: #5bc0de;_x000D_
}_x000D_
_x000D_
.badge-warning {_x000D_
background-color: #f0ad4e;_x000D_
}_x000D_
_x000D_
.badge-danger {_x000D_
background-color: #d9534f;_x000D_
}
_x000D_
You can use http_build_url with no arguments to get the full URL of the current page:
$url = http_build_url();
Here's a solution to your problem using dplyr's filter
function.
Although you can pass your data frame as the first argument to any dplyr function, I've used its %>%
operator, which pipes your data frame to one or more dplyr functions (just filter in this case).
Once you are somewhat familiar with dplyr, the cheat sheet is very handy.
> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
sub day
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
6 2 2
7 2 3
8 2 4
9 3 1
10 3 2
11 3 3
12 3 4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
sub day
1 1 1
2 1 3
3 1 4
4 2 1
5 2 2
6 2 3
7 2 4
8 3 1
9 3 2
10 3 3
You can use any bash looping constructs like FOR
, with is compatible to Linux and Mac.
https://tiswww.case.edu/php/chet/bash/bashref.html#Looping-Constructs
In your specific case you can define N
iterations, with N
is a number defining how many curl
executions you want.
for n in {1..N}; do curl <arguments>; done
ex:
for n in {1..20}; do curl -d @notification.json -H 'Content-Type: application/json' localhost:3000/dispatcher/notify; done
A tty is a terminal (it stands for teletype - the original terminals used a line printer for output and a keyboard for input!). A terminal is a basically just a user interface device that uses text for input and output.
A pty is a pseudo-terminal - it's a software implementation that appears to the attached program like a terminal, but instead of communicating directly with a "real" terminal, it transfers the input and output to another program.
For example, when you ssh in to a machine and run ls
, the ls
command is sending its output to a pseudo-terminal, the other side of which is attached to the SSH daemon.
Why don't you place the account number in a div. Style it as you please and then have a hidden input in the form that also contains the account number. Then when the form gets submitted, the value should come through and not be null.
To complete the picture, since -Werror
might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:
-Werror=implicit-function-declaration
See Make one gcc warning an error?
Regarding general use of -Werror
: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.
font-family:'Open Sans' , sans-serif;
For light:
font-weight : 100;
Or
font-weight : lighter;
For normal:
font-weight : 500;
Or
font-weight : normal;
For bold:
font-weight : 700;
Or
font-weight : bold;
For more bolder:
font-weight : 900;
Or
font-weight : bolder;
DLLs (Dynamic Link Libraries) contain resources used by one or more applications or services. They can contain classes, icons, strings, objects, interfaces, and pretty much anything a developer would need to store except a UI.
For Windows users looking for a PowerShell alternative, here it is (using POST). I've split it up onto multiple lines for readability.
$url = 'https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc'
$headers = @{
'Content-Type' = 'text/xml';
'SOAPAction' = 'http://api.eyeblaster.com/IAuthenticationService/ClientLogin'
}
$envelope = @'
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<yourEnvelopeContentsHere/>
</Body>
</Envelope>
'@ # <--- This line must not be indented
Invoke-WebRequest -Uri $url -Headers $headers -Method POST -Body $envelope
Or, you can set a margin-top on the iframe...a bit of a hack but works in FF so far.
#frame {
margin-top:200px;
}
Cast bare integer to decimal:
select cast(9 as decimal(4,2)); //prints 9.00
Cast Integers 8/5 to decimal:
select cast(8/5 as decimal(11,4)); //prints 1.6000
Cast string to decimal:
select cast(".885" as decimal(11,3)); //prints 0.885
Cast two int variables into a decimal
mysql> select 5 into @myvar1;
Query OK, 1 row affected (0.00 sec)
mysql> select 8 into @myvar2;
Query OK, 1 row affected (0.00 sec)
mysql> select @myvar1/@myvar2; //prints 0.6250
Cast decimal back to string:
select cast(1.552 as char(10)); //shows "1.552"
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
If adding pypi.python.org as a trusted host does not work, you try adding files.pythonhosted.org. For example
python -m pip install --upgrade --trusted-host files.pythonhosted.org <package-name>
echo 'mystring' |cut -c1-5
is an alternative solution to ur problem.
more on unix cut program
This one drove me crazy... basically you need two things:
1) Make sure your DNS is setup to point to your subdomain. This means to make sure you have an A Record in the DNS for your subdomain and point to the same IP.
2) You must add an additional website in IIS 7 named subdomain.example.com
The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).
Here is a piece of code that checks for these cases:
/// <summary>
/// Indicates whether any network connection is available
/// Filter connections below a specified speed, as well as virtual network cards.
/// </summary>
/// <returns>
/// <c>true</c> if a network connection is available; otherwise, <c>false</c>.
/// </returns>
public static bool IsNetworkAvailable()
{
return IsNetworkAvailable(0);
}
/// <summary>
/// Indicates whether any network connection is available.
/// Filter connections below a specified speed, as well as virtual network cards.
/// </summary>
/// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param>
/// <returns>
/// <c>true</c> if a network connection is available; otherwise, <c>false</c>.
/// </returns>
public static bool IsNetworkAvailable(long minimumSpeed)
{
if (!NetworkInterface.GetIsNetworkAvailable())
return false;
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
// discard because of standard reasons
if ((ni.OperationalStatus != OperationalStatus.Up) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
continue;
// this allow to filter modems, serial, etc.
// I use 10000000 as a minimum speed for most cases
if (ni.Speed < minimumSpeed)
continue;
// discard virtual cards (virtual box, virtual pc, etc.)
if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
// discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
continue;
return true;
}
return false;
}
If you are storing values via any programming language
Here is an example in C#
To store date you have to convert it first and then store it
insert table1 (foodate)
values (FooDate.ToString("MM/dd/yyyy"));
FooDate is datetime variable which contains your date in your format.
If your data is from json, you can do that
import json
json.loads('true')
True
Implements Parcelable and send arraylist as putParcelableArrayListExtra and get it from next activity getParcelableArrayListExtra
example:
Implement parcelable on your custom class -(Alt +enter) Implement its methods
public class Model implements Parcelable {
private String Id;
public Model() {
}
protected Model(Parcel in) {
Id= in.readString();
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
@Override
public ModelcreateFromParcel(Parcel in) {
return new Model(in);
}
@Override
public Model[] newArray(int size) {
return new Model[size];
}
};
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Id);
}
}
Pass class object from activity 1
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putParcelableArrayListExtra("model", modelArrayList);
startActivity(intent);
Get extra from Activity2
if (getIntent().hasExtra("model")) {
Intent intent = getIntent();
cartArrayList = intent.getParcelableArrayListExtra("model");
}
The quickest way to get around the error is add on the -k option somewhere in your curl request. That option "allows connections to SSL cites without certs." (from curl --help)
Be aware that this may mean that you're not talking to the endpoint you think you are, as they are presenting a certificate not signed by a CA you trust.
For example:
$ curl -o /usr/bin/apt-cyg https://raw.github.com/cfg/apt-cyg/master/apt-cyg
gave me the following error response:
curl: (77) error setting certificate verify locations:
CAfile: /usr/ssl/certs/ca-bundle.crt
CApath: none
I added on -k:
curl -o /usr/bin/apt-cyg https://raw.github.com/cfg/apt-cyg/master/apt-cyg -k
and no error message. As a bonus, now I have apt-cyg installed. And ca-certificates.
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
answer[k++] = a[i] < b[j] ? a[i++] : b[j++];
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
Is a little bit more compact but exactly the same!
Try the change event and selected selector
$('#jobSel').change(function(){
var optId = $(this).find('option:selected').attr('id')
})
EDIT: The other two answers make a good point. I'm assuming that you want to order them into some other structure, or in order to print them out.
"Best" can mean a number of different things. Do you mean "easiest," "fastest," "most efficient," "least code," "most readable?"
The most obvious approach is to loop through twice. On the first pass, order the values:
if(current_value > examined_value)
{
current_value = examined_value
(and then swap them, however you like)
}
Then on the second pass, alphabetize the words, but only if their values match.
if(current_value == examined_value)
{
(alphabetize the two)
}
Strictly speaking, this is a "bubble sort" which is slow because every time you make a swap, you have to start over. One "pass" is finished when you get through the whole list without making any swaps.
There are other sorting algorithms, but the principle would be the same: order by value, then alphabetize.
You can use css filters, below and example for web-kit. please look at this example: http://jsfiddle.net/m9sjdbx6/4/
img { -webkit-filter: brightness(0.2);}
For console projects in a step-by-step fashion, you'll have to first add the System.Windows.Forms
reference. The following steps work in Visual Studio Community 2013 with .NET 4.5:
System.Windows.Forms
.Then, add the following using
statement in with the others at the top of your code:
using System.Windows.Forms;
Then, add either of the following Clipboard
.SetText
statements to your code:
Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
And lastly, add STAThreadAttribute
to your Main
method as follows, to avoid a System.Threading.ThreadStateException
:
[STAThreadAttribute]
static void Main(string[] args)
{
// ...
}
1:
[{value:5}, {value:10}].reduce((previousValue, currentValue) => { return {value: previousValue.value + currentValue.value}})
>> Object {value: 15}
2:
[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })
>> 15
3:
[{value:5}, {value:10}].reduce(function (previousValue, currentValue) {
return {value: previousValue.value + currentValue.value};
})
>> Object {value: 15}
For those like me that added Bootstrap to Wordpress without the use of plugin or theme:
I added bootstrap CSS and JS in the function.php
file.
Then, called the modal in a wordpress page.
No matter what I did, the .modal-backdrop
kept being in fron of #mymodal
. I found out that it was a z-index problem but, as #mymodal
was generated inside the content div
and .modal-backdrop
at the end of <body>
, z-index couldn't work.
What I did was moving #mymodal
to the end of as well after it was generated:
$(document).ready(function () {
$('#mymodal').on('shown.bs.modal', function () {
$('#mymodal').appendTo(document.body);
})
});
By the way, I had to add shown.bs.modal
inside $(document).ready
because it wasn't being called when I hit the button.
hash = { a: 'a', b: 'b' }
=> {:a=>"a", :b=>"b"}
hash.merge({ c: 'c', d: 'd' })
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
Returns the merged value.
hash
=> {:a=>"a", :b=>"b"}
But doesn't modify the caller object
hash = hash.merge({ c: 'c', d: 'd' })
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
hash
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
Reassignment does the trick.
Actually the minimum amount of Angular to be used (as requested in the original question) is just adding a class to the DOM element when show
variable is true, and perform the animation/transition via CSS.
So your minimum Angular code is this:
<div class="box-opener" (click)="show = !show">
Open/close the box
</div>
<div class="box" [class.opened]="show">
<!-- Content -->
</div>
With this solution, you need to create CSS rules for the transition, something like this:
.box {
background-color: #FFCC55;
max-height: 0px;
overflow-y: hidden;
transition: ease-in-out 400ms max-height;
}
.box.opened {
max-height: 500px;
transition: ease-in-out 600ms max-height;
}
If you have retro-browser-compatibility issues, just remember to add the vendor prefixes in the transition
s.
See the example here
Here are some simple techniques for vertical-align:
This one is easy: set the line-height of the text element to equal that of the container
<div>
<img style="width:30px; height:30px;">
<span style="line-height:30px;">Doesn't work.</span>
</div>
Absolutely position an inner div relative to its container
<div style="position:relative;width:30px;height:60px;">
<div style="position:absolute;bottom:0">This is positioned on the bottom</div>
</div>
<div style="display:table;width:30px;height:60px;">
<div style="display:table-cell;height:30px;">This is positioned in the middle</div>
</div>
In order to get this to work correctly across the board, you'll have to hack the CSS a bit. Luckily, there is an IE bug that works in our favor. Setting top:50%
on the container and top:-50%
on the inner div, you can achieve the same result. We can combine the two using another feature IE doesn't support: advanced CSS selectors.
<style type="text/css">
#container {
width: 30px;
height: 60px;
position: relative;
}
#wrapper > #container {
display: table;
position: static;
}
#container div {
position: absolute;
top: 50%;
}
#container div div {
position: relative;
top: -50%;
}
#container > div {
display: table-cell;
vertical-align: middle;
position: static;
}
</style>
<div id="wrapper">
<div id="container">
<div><div><p>Works in everything!</p></div></div>
</div>
</div>
This solution requires a slightly more modern browser than the other solutions, as it makes use of the transform: translateY
property. (http://caniuse.com/#feat=transforms2d)
Applying the following 3 lines of CSS to an element will vertically centre it within its parent regardless of the height of the parent element:
position: relative;
top: 50%;
transform: translateY(-50%);
For list comprehension lovers, this will write all the key : value
pairs in new lines in dog.txt
my_dict = {'foo': [1,2], 'bar':[3,4]}
# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]
# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
[ my_file.write(f'{st}\n') for st in list_of_strings ]
srand
doesn't return anything so you can't initialize a
with its return value because, well, because it doesn't return a value. Did you mean to call rand
as well?
If your x and y coords are not on a grid then you need to interpolate your x,y,z surface onto one. You can do this with kriging using any of the geostatistics packages (geoR, gstat, others) or simpler techniques such as inverse distance weighting.
I'm guessing the 'interp' function you mention is from the akima package. Note that the output matrix is independent of the size of your input points. You could have 10000 points in your input and interpolate that onto a 10x10 grid if you wanted. By default akima::interp does it onto a 40x40 grid:
require(akima)
require(rgl)
x = runif(1000)
y = runif(1000)
z = rnorm(1000)
s = interp(x,y,z)
> dim(s$z)
[1] 40 40
surface3d(s$x,s$y,s$z)
That'll look spiky and rubbish because its random data. Hopefully your data isnt!
strncpy(otherString, someString, 5);
Don't forget to allocate memory for otherString.
I very often use regex to extract data from files I just used that to replace the literal quote \"
with //
nothing :-)
cat file.csv | egrep '^\"([0-9]{1,3}\.[0-9]{1,3}\.)' | sed s/\"//g | cut -d, -f1 > list.txt
In Jackson 2.4, you can convert as follows:
MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);
where jsonObjectMapper
is a Jackson ObjectMapper
.
In older versions of Jackson, it would be
MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);
Yep, performance is the main reason and, as far as I know, the only reason.
If some of your files aren't getting compiled, maybe Python isn't able to write to the .pyc file, perhaps because of the directory permissions or something. Or perhaps the uncompiled files just aren't ever getting loaded... (scripts/modules only get compiled when they first get loaded)
Using base graphics, the standard way to do this is to use axes=FALSE, then create your own axes using Axis (or axis). For example,
x <- 1:20
y <- runif(20)
plot(x, y, axes=FALSE, frame.plot=TRUE)
Axis(side=1, labels=FALSE)
Axis(side=2, labels=FALSE)
The lattice equivalent is
library(lattice)
xyplot(y ~ x, scales=list(alternating=0))
In Marshmallow, I got this error,
Installation error: INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE
Please check logcat output for more details.
Launch canceled!
Looking for solution I searched and came here. I deleted the app but still have this problem in Nexus 6. Later found that in,
Settings > Apps > [My app name] have to removed for all user.
This may help some one with same requirement
private String getDate(long time){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
String dateString = formatter.format(new Date(time));
String date = ""+dateString;
return date;
}
Using Node.removeChild() does the job for you, simply use something like this:
var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);
In DOM 4, the remove method applied, but there is a poor browser support according to W3C:
The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.
But you can use remove method if you using jQuery...
$('#left-section').remove(); //using remove method in jQuery
Also in new frameworks like you can use conditions to remove an element, for example *ngIf
in Angular and in React, rendering different views, depends on the conditions...
In short, IoC is a much broader term that includes, but is not limited to, DI
The term Inversion of Control (IoC) originally meant any sort of programming style where an overall framework or run-time controlled the program flow
Before DI had a name, people started to refer to frameworks that manage Dependencies as Inversion of Control Containers, and soon, the meaning of IoC gradually drifted towards that particular meaning: Inversion of Control over Dependencies.
Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.
Here is a quick start to get the gears turning...
ParkingLot is a class.
ParkingSpace is a class.
ParkingSpace has an Entrance.
Entrance has a location or more specifically, distance from Entrance.
ParkingLotSign is a class.
ParkingLot has a ParkingLotSign.
ParkingLot has a finite number of ParkingSpaces.
HandicappedParkingSpace is a subclass of ParkingSpace.
RegularParkingSpace is a subclass of ParkingSpace.
CompactParkingSpace is a subclass of ParkingSpace.
ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.
ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()
Parker is a class.
Parker can Park().
Parker can Unpark().
Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.
Parker has a ParkingSpace.
Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().
Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().
HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)
In this solution, it is possible that Parker should be renamed to be Car.
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
Write this in each "new activity" after you initialized your new intent->
Intent i = new Intent(this, yourClass.class);
startActivity(i);
finish();
You just need to use the socket settimeout()
method before attempting the connect()
, please note that after connecting you must settimeout(None)
to set the socket into blocking mode, such is required for the makefile .
Here is the code I am using:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)
How about this?
formdata.append('tags', JSON.stringify(tags));
... and, correspondingly, using json_decode
on server to deparse it. See, the second value of FormData.append can be...
a Blob, File, or a string, if neither, the value is converted to a string
The way I see it, your tags
array contains objects (@Musa is right, btw; making this_tag
an Array, then assigning string properties to it makes no sense; use plain object instead), so native conversion (with toString()
) won't be enough. JSON'ing should get the info through, though.
As a sidenote, I'd rewrite the property assigning block just into this:
tags.push({article: article, gender: gender, brand: brand});
See gjvdkamp
's answer below; this feature now exists in C#
var @switch = new Dictionary<Type, Action> {
{ typeof(Type1), () => ... },
{ typeof(Type2), () => ... },
{ typeof(Type3), () => ... },
};
@switch[typeof(MyType)]();
It's a little less flexible as you can't fall through cases, continue etc. But I rarely do so anyway.
Assumption:
Phpunit (3.7) is available in the console environment.
Action:
Enter the following command in the console:
SHELL> phpunit "{{PATH TO THE FILE}}"
Comments:
You do not need to include anything in the new versions of PHPUnit unless you do not want to run in the console. For example, running tests in the browser.
from Swift 3 and above, Date is Comparable so we can directly compare dates like
let date1 = Date()
let date2 = Date().addingTimeInterval(50)
let isGreater = date1 > date2
print(isGreater)
let isSmaller = date1 < date2
print(isSmaller)
let isEqual = date1 == date2
print(isEqual)
Alternatively We can create extension on Date
extension Date {
func isEqualTo(_ date: Date) -> Bool {
return self == date
}
func isGreaterThan(_ date: Date) -> Bool {
return self > date
}
func isSmallerThan(_ date: Date) -> Bool {
return self < date
}
}
Use: let isEqual = date1.isEqualTo(date2)
If you are using TextEditingController then set the text to it, like below
TextEditingController _controller = new TextEditingController();
_controller.text = 'your initial text';
final your_text_name = TextFormField(
autofocus: false,
controller: _controller,
decoration: InputDecoration(
hintText: 'Hint Value',
),
);
and if you are not using any TextEditingController then you can directly use initialValue like below
final last_name = TextFormField(
autofocus: false,
initialValue: 'your initial text',
decoration: InputDecoration(
hintText: 'Last Name',
),
);
For more reference TextEditingController
If you don't mind the dictionary values being tuples, you can use itertuples:
>>> {x[0]: x[1:] for x in df.itertuples(index=False)}
{'p': (1, 3, 2), 'q': (4, 3, 2), 'r': (4, 0, 9)}
Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.
And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.
The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.
In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.
you could use datetime
library to get UTC time even local time.
import datetime
utc_time = datetime.datetime.utcnow()
print(utc_time.strftime('%Y%m%d %H%M%S'))
This is not a function of Maven; it's a function of the compiler. Look closely; the information you're looking for is most likely in the following line.
For those that are passing both a port and a host, keep in mind that Heroku will not bind to localhost
.
You must pass 0.0.0.0
for host.
Even if you're using the correct port. We had to make this adjustment:
# port (as described above) and host are both wrong
const host = 'localhost';
const port = 3000;
# use alternate localhost and the port Heroku assigns to $PORT
const host = '0.0.0.0';
const port = process.env.PORT || 3000;
Then you can start the server, as usual:
app.listen(port, host, function() {
console.log("Server started.......");
});
You can see more details here: https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error
This is how I solved it based on this post with some minor tweaks. This solution does not require creation of any additional classes.
SSLContext sc = SSLContext.getInstance("SSLv3");
KeyManagerFactory kmf =
KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );
KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load(new FileInputStream( certPath ), certPasswd.toCharArray() );
kmf.init( ks, certPasswd.toCharArray() );
sc.init( kmf.getKeyManagers(), null, null );
((BindingProvider) webservicePort).getRequestContext()
.put(
"com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
sc.getSocketFactory() );
I think that mobile devices dont work with fixed positions. You should try with some js plugin like skrollr.js (for example). With this kind of plugin you can select the position of your div (or whatever) in function of scrollbar position.
Python 3.3 introduces Python Launcher for Windows that is installed into c:\Windows\
as py.exe
and pyw.exe
by the installer. The installer also creates associations with .py
and .pyw
. Then add #!python3
or #!python2
as the first lline. No need to add anything to the PATH
environment variable.
Update: Just install Python 3.3 from the official python.org/download. It will add also the launcher. Then add the first line to your script that has the .py
extension. Then you can launch the script by simply typing the scriptname.py
on the cmd line, od more explicitly by py scriptname.py
, and also by double clicking on the scipt icon.
The py.exe
looks for C:\PythonXX\python.exe
where XX
is related to the installed versions of Python at the computer. Say, you have Python 2.7.6 installed into C:\Python27
, and Python 3.3.3 installed into C:\Python33
. The first line in the script will be used by the Python launcher to choose one of the installed versions. The default (i.e. without telling the version explicitly) is to use the highest version of Python 2 that is available on the computer.
Just use has_one
instead of belongs_to
in your :through
, like this:
class Choice
belongs_to :user
belongs_to :answer
has_one :question, :through => :answer
end
Unrelated, but I'd be hesitant to use validates_uniqueness_of instead of using a proper unique constraint in your database. When you do this in ruby you have race conditions.
Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if
statement. Hope this helps.
<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="tab"/>
<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/>
Now we could also use:
if (Attachment != null && Attachment.Any())
Any() is often easier to understand in a glance for the developer than checking Length() > 0. Also has very little difference with processing speed.
install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB
In Python, the name of the class refers to the class instance. Consider:
class A: pass
class B: pass
class C: pass
lst = [A, B, C]
# instantiate second class
b_instance = lst[1]()
print b_instance
I ran into this issue with custom types in stored procedures, and solved it with the script below. I didn't fully understand the scripts above, and I follow the rule of "if you don't know what it does, don't do it".
In a nutshell, I rename the old type, and create a new one with the original type name. Then, I tell SQL Server to refresh its details about each stored procedure using the custom type. You have to do this, as everything is still "compiled" with reference to the old type, even with the rename. In this case, the type I needed to change was "PrizeType". I hope this helps. I'm looking for feedback, too, so I learn :)
Note that you may need to go to Programmability > Types > [Appropriate User Type] and delete the object. I found that DROP TYPE doesn't appear to always drop the type even after using the statement.
/* Rename the UDDT you want to replace to another name */
exec sp_rename 'PrizeType', 'PrizeTypeOld', 'USERDATATYPE';
/* Add the updated UDDT with the new definition */
CREATE TYPE [dbo].[PrizeType] AS TABLE(
[Type] [nvarchar](50) NOT NULL,
[Description] [nvarchar](max) NOT NULL,
[ImageUrl] [varchar](max) NULL
);
/* We need to force stored procedures to refresh with the new type... let's take care of that. */
/* Get a cursor over a list of all the stored procedures that may use this and refresh them */
declare sprocs cursor
local static read_only forward_only
for
select specific_name from information_schema.routines where routine_type = 'PROCEDURE'
declare @sprocName varchar(max)
open sprocs
fetch next from sprocs into @sprocName
while @@fetch_status = 0
begin
print 'Updating ' + @sprocName;
exec sp_refreshsqlmodule @sprocName
fetch next from sprocs into @sprocName
end
close sprocs
deallocate sprocs
/* Drop the old type, now that everything's been re-assigned; must do this last */
drop type PrizeTypeOld;
You could the yolk3k package instead of yolk. yolk3k is a fork from the original yolk and it supports both python2 and 3.
pip install yolk3k
/^[a-z]{0,10}$/
should work. /^[a-z]{1,10}$/
if you want to match at least one character, like /^[a-z]+$/
does.
There is no way to do this in one method call, you'll have to either chain calls together, or write a function that manually does what you need.
var s = "<>\n";
s = s.replace("<", "<");
s = s.replace(">", ">");
s = s.replace("\n", "<br/>");
Script to check the Backup and Restore progress in SQL Server:
Many times it happens that your backup (or restore) activity has been started by another Database Administrator or by a job, and you cannot use the GUI anything else to check the progress of that Backup / Restore.
By combining multiple commands, I have generated below script which can give us a summary of current backups and restores which are happening on the server.
select
r.session_id,
r.blocking_session_id,
db_name(database_id) as [DatabaseName],
r.command,
[SQL_QUERY_TEXT] = Substring(Query.TEXT, (r.statement_start_offset / 2) + 1, (
(
CASE r.statement_end_offset
WHEN - 1
THEN Datalength(Query.TEXT)
ELSE r.statement_end_offset
END - r.statement_start_offset
) / 2
) + 1),
[SP_Name] =Coalesce(Quotename(Db_name(Query.dbid)) + N'.' + Quotename(Object_schema_name(Query.objectid, Query.dbid)) + N'.' +
Quotename(Object_name(Query.objectid, Query.dbid)), ''),
r.percent_complete,
start_time,
CONVERT(VARCHAR(20), DATEADD(ms, [estimated_completion_time],
GETDATE()), 20) AS [ETA_COMPLETION_TIME],
CONVERT(NUMERIC(6, 2), r.[total_elapsed_time] / 1000.0 / 60.0) AS [Elapsed_MIN],
CONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0) AS [Remaning_ETA_MIN],
CONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0/ 60.0) AS [ETA_Hours],
wait_type,
wait_time/1000 as Wait_Time_Sec,
wait_resource
from sys.dm_exec_requests r
cross apply sys.fn_get_sql(r.sql_handle) as Query where r.session_id>50 and command IN ('RESTORE DATABASE','BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG')
That message is usually an indication that some of your files have modification times later than the current system time. Since make
decides which files to compile when performing an incremental build by checking if a source files has been modified more recently than its object file, this situation can cause unnecessary files to be built, or worse, necessary files to not be built.
However, if you are building from scratch (not doing an incremental build) you can likely ignore this warning without consequence.
It seems that the latest function for this in windows 7 is robocopy.
Usage example:
robocopy <source> <destination> /e /xf <file to exclude> <another file>
/e copies subdirectories including empty ones, /xf excludes certain files from being copied.
More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx
Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored with the tag. Which I like.
<img class="loadlater" data-src="path/to/image.ext"/>
A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.
$(document).ready(function(){
$(".loadlater").each(function(index, element){
$(element).attr("src", $(element).attr("data-src"));
});
});
I bet the jQuery code could be abbreviated, but it is understandable this way.
np.average takes an optional weight parameter. If it is not supplied they are equivalent. Take a look at the source code: Mean, Average
np.mean:
try:
mean = a.mean
except AttributeError:
return _wrapit(a, 'mean', axis, dtype, out)
return mean(axis, dtype, out)
np.average:
...
if weights is None :
avg = a.mean(axis)
scl = avg.dtype.type(a.size/avg.size)
else:
#code that does weighted mean here
if returned: #returned is another optional argument
scl = np.multiply(avg, 0) + scl
return avg, scl
else:
return avg
...
The best way to force a specific JVM for MAVEN is to create a system wide file loaded by the mvn script.
This file is /etc/mavenrc
and it must declare a JAVA_HOME
environment variable pointing to your specific JVM.
Example:
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64
If the file exists, it's loaded.
Here is an extract of the mvn
script in order to understand :
if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi if [ -f "$HOME/.mavenrc" ] ; then . "$HOME/.mavenrc" fi
Alternately, the same content can be written in ~/.mavenrc
There are three unique situations:
Margin="a,b,c,d"
.Margin="a,b"
.Margin="a"
.If there are 4 numbers, then its left
, top
, right
, bottom
(a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":
<object Margin="left,top,right,bottom"/>
Example: if we use Margin="10,20,30,40"
it generates:
If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":
<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".
Example: if we use Margin="10,30"
, the left & right margin are both 10, and the top & bottom are both 30.
If there is 1 number, then the number is repeated (its essentially a border thickness).
<object Margin="a"/> // Equivalent to Margin="a,a,a,a".
Example: if we use Margin="20"
it generates:
Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.
The rule:
All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).
Why not use margin? you can apply all kinds off margins to an element. Not just the whole margin around it.
You should use css classes since this is referencing more than one element and you can use id's for those that you want to be different specifically
i.e:
<style>
.box { height: 50px; background: #0F0; width: 100%; margin-top: 10px; }
#first { margin-top: 20px; }
#second { background: #00F; }
h1.box { background: #F00; margin-bottom: 50px; }
</style>
<h1 class="box">Hello World</h1>
<div class="box" id="first"></div>
<div class="box" id="second"></div>?
Here is a jsfiddle example:
REFERENCE:
Do Cmd+F12+Fn Key on mac in IntelliJ if clicking Cmd+F12 starts.
Updating a pull request in GitHub is as easy as committing the wanted changes into existing branch (that was used with pull request), but often it is also wanted to squash the changes into single commit:
git checkout yourbranch
git rebase -i origin/master
# Edit command names accordingly
pick 1fc6c95 My pull request
squash 6b2481b Hack hack - will be discarded
squash dd1475d Also discarded
git push -f origin yourbranch
...and now the pull request contains only one commit.
Related links about rebasing:
Not sure if there was file corruption or what, but after confirming proper pom configuration I was able to resolve this issue by deleting the jar from my local m2 repository, forcing Maven to download it again when I ran the tests.
You can use this for get first record where has clause
SELECT TOP(1) * , ROW_NUMBER() OVER(ORDER BY UserId) AS rownum
FROM Users
WHERE UserName = 'Joe'
ORDER BY rownum ASC
Angular 8 HttpClient Service example with Error Handling and Custom Header
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Student } from '../model/student';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
// API path
base_path = 'http://localhost:3000/students';
constructor(private http: HttpClient) { }
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
// Handle API errors
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
// Create a new item
createItem(item): Observable<Student> {
return this.http
.post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
.pipe(
retry(2),
catchError(this.handleError)
)
}
....
....
Check complete example tutorial here
implode(' ',$array);
I recently struggled with this issue for 3 days. How the client is sending the request might not be the cause, the server might not be configured to handle multipart requests. This is what I had to do to get it working:
pom.xml - Added commons-fileupload dependency (download and add the jar to your project if you are not using dependency management such as maven)
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-version}</version>
</dependency>
web.xml - Add multipart filter and mapping
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/springrest/*</url-pattern>
</filter-mapping>
app-context.xml - Add multipart resolver
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize">
<beans:value>10000000</beans:value>
</beans:property>
</beans:bean>
Your Controller
@RequestMapping(value=Constants.REQUEST_MAPPING_ADD_IMAGE, method = RequestMethod.POST, produces = { "application/json"})
public @ResponseBody boolean saveStationImage(
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_FILE) MultipartFile file,
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_URI) String imageUri,
@RequestParam(value = Constants.MONGO_STATION_PROFILE_IMAGE_TYPE) String imageType,
@RequestParam(value = Constants.MONGO_FIELD_STATION_ID) String stationId) {
// Do something with file
// Return results
}
Your client
public static Boolean updateStationImage(StationImage stationImage) {
if(stationImage == null) {
Log.w(TAG + ":updateStationImage", "Station Image object is null, returning.");
return null;
}
Log.d(TAG, "Uploading: " + stationImage.getImageUri());
try {
RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName("UTF8"));
restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add(Constants.STATION_PROFILE_IMAGE_FILE, new FileSystemResource(stationImage.getImageFile()));
parts.add(Constants.STATION_PROFILE_IMAGE_URI, stationImage.getImageUri());
parts.add(Constants.STATION_PROFILE_IMAGE_TYPE, stationImage.getImageType());
parts.add(Constants.FIELD_STATION_ID, stationImage.getStationId());
return restTemplate.postForObject(Constants.REST_CLIENT_URL_ADD_IMAGE, parts, Boolean.class);
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
Log.e(TAG + ":addStationImage", sw.toString());
}
return false;
}
That should do the trick. I added as much information as possible because I spent days, piecing together bits and pieces of the full issue, I hope this will help.
// .blur is triggered when element loses focus
$('#target').blur(function() {
alert($(this).val());
});
// To trigger manually use:
$('#target').blur();
debug_backtrace()
Andrea solution is absolutely right, I will just write another implementation based on the same idea. If you took a look at the THREE.ImageUtils.loadTexture() source you will find it uses the javascript Image object. The $(window).load event is fired after all Images are loaded ! so at that event we can render our scene with the textures already loaded...
CoffeeScript
$(document).ready ->
material = new THREE.MeshLambertMaterial(map: THREE.ImageUtils.loadTexture("crate.gif"))
sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material)
$(window).load ->
renderer.render scene, camera
JavaScript
$(document).ready(function() {
material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture("crate.gif") });
sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material);
$(window).load(function() {
renderer.render(scene, camera);
});
});
Thanks...
Yes, you can select the data, calculate the difference, and insert all values in the other table:
insert into #temp2 (Difference)
select previous - Present
from #TEMP1
One more thing to check for this issue is html tag attribute id. You should check any other html tags in that page have the same id as nav tab id.
This can be fixed by changing your URL, example bad:
https://raw.githubusercontent.com/svnpenn/bm/master/yt-dl/yt-dl.js
Content-Type: text/plain; charset=utf-8
Example good:
https://cdn.rawgit.com/svnpenn/bm/master/yt-dl/yt-dl.js
content-type: application/javascript;charset=utf-8
rawgit.com is a caching proxy service for github. You can also go there and interactively derive a corresponding URL for your original raw.githubusercontent.com URL. See its FAQ
One point from me. I used a mutual cert authentication with spring-boot microservices. The following is working for me, key points here are
keyManagerFactory.init(...)
and sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom())
lines of code without them, at least for me, things did not work. Certificates are packaged by PKCS12.
@Value("${server.ssl.key-store-password}")
private String keyStorePassword;
@Value("${server.ssl.key-store-type}")
private String keyStoreType;
@Value("${server.ssl.key-store}")
private Resource resource;
private RestTemplate getRestTemplate() throws Exception {
return new RestTemplate(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() throws Exception {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
private HttpClient httpClient() throws Exception {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore trustStore = KeyStore.getInstance(keyStoreType);
if (resource.exists()) {
InputStream inputStream = resource.getInputStream();
try {
if (inputStream != null) {
trustStore.load(inputStream, keyStorePassword.toCharArray());
keyManagerFactory.init(trustStore, keyStorePassword.toCharArray());
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
} else {
throw new RuntimeException("Cannot find resource: " + resource.getFilename());
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1.2"}, null, getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
Here is my solution:
#include <stdexcept>
#include <sstream>
class Formatter
{
public:
Formatter() {}
~Formatter() {}
template <typename Type>
Formatter & operator << (const Type & value)
{
stream_ << value;
return *this;
}
std::string str() const { return stream_.str(); }
operator std::string () const { return stream_.str(); }
enum ConvertToString
{
to_str
};
std::string operator >> (ConvertToString) { return stream_.str(); }
private:
std::stringstream stream_;
Formatter(const Formatter &);
Formatter & operator = (Formatter &);
};
Example:
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData); // implicitly cast to std::string
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str); // explicitly cast to std::string
To expand Konamiman's solution (including all relevant null checks), this is what I've been doing:
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["Name"];
if (nameAttribute != null)
return nameAttribute.Value;
throw new InvalidOperationException("Node 'Name' not found.");
}
first use this:
LayoutInflater inflater = (LayoutInflater) Read_file.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Read file is current activity in which you want your context.
View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));
then you can use this to find any element in layout.
ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);
The context that * is in, confuses the meaning sometimes.
// when declaring a function
int function(int*); // This function is being declared as a function that takes in an 'address' that holds a number (so int*), it's asking for a 'reference', interchangeably called 'address'. When I 'call'(use) this function later, I better give it a variable-address! So instead of var, or q, or w, or p, I give it the address of var so &var, or &q, or &w, or &p.
//even though the symbol ' * ' is typically used to mean 'dereferenced variable'(meaning: to use the value at the address of a variable)--despite it's common use, in this case, the symbol means a 'reference', again, in THIS context. (context here being the declaration of a 'prototype'.)
//when calling a function
int main(){
function(&var); // we are giving the function a 'reference', we are giving it an 'address'
}
So, in the context of declaring a type such as int or char, we would use the dereferencer ' * ' to actually mean the reference (the address), which makes it confusing if you see an error message from the compiler saying: 'expecting char*' which is asking for an address.
In that case, when the * is after a type (int, char, etc.) the compiler is expecting a variable's address. We give it this by using a reference operator, alos called the address-of operator ' & ' before a variable. Even further, in the case I just made up above, the compiler is expecting the address to hold a character value, not a number. (type char * == address of a value that has a character)
int* p;
int *a; // both are 'pointer' declarations. We are telling the compiler that we will soon give these variables an address (with &).
int c = 10; //declare and initialize a random variable
//assign the variable to a pointer, we do this so that we can modify the value of c from a different function regardless of the scope of that function (elaboration in a second)
p = c; //ERROR, we assigned a 'value' to this 'pointer'. We need to assign an 'address', a 'reference'.
p = &c; // instead of a value such as: 'q',5,'t', or 2.1 we gave the pointer an 'address', which we could actually print with printf(), and would be something like
//so
p = 0xab33d111; //the address of c, (not specifically this value for the address, it'll look like this though, with the 0x in the beggining, the computer treats these different from regular numbers)
*p = 10; // the value of c
a = &c; // I can still give c another pointer, even though it already has the pointer variable "p"
*a = 10;
a = 0xab33d111;
Think of each variable as having a position (or an index value if you are familiar with arrays) and a value. It might take some getting used-to to think of each variable having two values to it, one value being it's position, physically stored with electricity in your computer, and a value representing whatever quantity or letter(s) the programmer wants to store.
//Why it's used
int function(b){
b = b + 1; // we just want to add one to any variable that this function operates on.
}
int main(){
int c = 1; // I want this variable to be 3.
function(c);
function(c);// I call the function I made above twice, because I want c to be 3.
// this will return c as 1. Even though I called it twice.
// when you call a function it makes a copy of the variable.
// so the function that I call "function", made a copy of c, and that function is only changing the "copy" of c, so it doesn't affect the original
}
//let's redo this whole thing, and use pointers
int function(int* b){ // this time, the function is 'asking' (won't run without) for a variable that 'points' to a number-value (int). So it wants an integer pointer--an address that holds a number.
*b = *b + 1; //grab the value of the address, and add one to the value stored at that address
}
int main(){
int c = 1; //again, I want this to be three at the end of the program
int *p = &c; // on the left, I'm declaring a pointer, I'm telling the compiler that I'm about to have this letter point to an certain spot in my computer. Immediately after I used the assignment operator (the ' = ') to assign the address of c to this variable (pointer in this case) p. I do this using the address-of operator (referencer)' & '.
function(p); // not *p, because that will dereference. which would give an integer, not an integer pointer ( function wants a reference to an int called int*, we aren't going to use *p because that will give the function an int instead of an address that stores an int.
function(&c); // this is giving the same thing as above, p = the address of c, so we can pass the 'pointer' or we can pass the 'address' that the pointer(variable) is 'pointing','referencing' to. Which is &c. 0xaabbcc1122...
//now, the function is making a copy of c's address, but it doesn't matter if it's a copy or not, because it's going to point the computer to the exact same spot (hence, The Address), and it will be changed for main's version of c as well.
}
Inside each and every block, it copies the variables (if any) that are passed into (via parameters within "()"s). Within those blocks, the changes to a variable are made to a copy of that variable, the variable uses the same letters but is at a different address (from the original). By using the address "reference" of the original, we can change a variable using a block outside of main, or inside a child of main.
I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString
method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.
function formatDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1, // months are zero indexed
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
minuteFormatted = minute < 10 ? "0" + minute : minute,
morning = hour < 12 ? "am" : "pm";
return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
minuteFormatted + morning;
}
This worked for me:
git init
git remote add origin PATH/TO/REPO
git fetch
git reset origin/master # Required when the versioned files existed in path before "git init" of this repo.
git checkout -t origin/master
NOTE: -t
will set the upstream branch for you, if that is what you want, and it usually is.
well, it is not really necessary to create a function for this when it can be done simply with 1 CSS class.
just wrap your text around this class and see the magic :D
<p style={{whiteSpace: 'pre-line'}}>my json text goes here \n\n</p>
note: because you will always present your text in frontend with HTML you can add the style={{whiteSpace: 'pre-line'}} to any tag, not just the p tag.
J2V8 is best solution of your problem. It's run Nodejs application on jvm(java and android).
J2V8 is Java Bindings for V8, But Node.js integration is available in J2V8 (version 4.4.0)
Github : https://github.com/eclipsesource/J2V8
Example : http://eclipsesource.com/blogs/2016/07/20/running-node-js-on-the-jvm/
Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.
Format the picture and in the Properties tab select "Move but don't size with cells"
Now you can sort the data table by any column and the pictures will stay with the respective data.
This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627
A shorthand answer assuming
import matplotlib.pyplot as plt
:
plt.gca().set_title('title')
as in:
plt.subplot(221)
plt.gca().set_title('title')
plt.subplot(222)
etc...
Then there is no need for superfluous variables.
Private outer class would be useless as nothing can access it.
See more details:
here is a link to generate a short list of options available to npm; it filters on the keywords unused packages
There's a client profile usable version, System.Net.WebUtility class, present in client profile System.dll. Here's the MSDN Link:
r = [1, 2, 3, 5, 1, 2, 3, 1, 2, 1]
r.group_by(&:itself).map { |k, v| v.size > 1 ? [k] + [v.size] : nil }.compact.sort_by(&:last).map(&:first)
Try this
For red color,
<string name="hello_worldRed"><![CDATA[<b><font color=#FF0000>Hello world!</font></b>]]></string>
For blue,
<string name="hello_worldBlue"><![CDATA[<b><font color=#0000FF>Hello world!</font></b>]]></string>
In java code,
//red color text
TextView redColorTextView = (TextView)findViewById(R.id.redText);
String redString = getResources().getString(R.string.hello_worldRed)
redColorTextView.setText(Html.fromHtml(redString));
//Blue color text
TextView blueColorTextView = (TextView)findViewById(R.id.blueText);
String blueString = getResources().getString(R.string.hello_worldBlue)
blueColorTextView.setText(Html.fromHtml(blueString));
This approach from Microsoft works very well and provides the option to compare one list to another and switch them to get the difference in each. If you are comparing classes simply add your objects to two separate lists and then run the comparison.
Following @acdcjunior answer, this is how I implemented it
service:
get(url, params): Promise<Object> {
return this.sendRequest(this.baseUrl + url, 'get', null, params)
.map((res) => {
return res as Object
}).catch((e) => {
return Observable.of(e);
})
.toPromise();
}
caller:
this.dataService.get(baseUrl, params)
.then((object) => {
if(object['name'] === 'HttpErrorResponse') {
this.error = true;
//or any handle
} else {
this.myObj = object as MyClass
}
});
Python dictionaries have a key and a value, what you are asking for is what key(s) point to a given value.
You can only do this in a loop:
[k for (k, v) in i.iteritems() if v == 0]
Note that there can be more than one key per value in a dict; {'a': 0, 'b': 0}
is perfectly legal.
If you want ordering you either need to use a list or a OrderedDict instance instead:
items = ['a', 'b', 'c']
items.index('a') # gives 0
items[0] # gives 'a'
Also you can use a MessageBox
with OKCancel
options, but it requires many codes.
The if
block is for OK
, the else
block is for Cancel
. Here is the code:
if (MessageBox.Show("Are you sure you want to do this?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
MessageBox.Show("You pressed OK!");
}
else
{
MessageBox.Show("You pressed Cancel!");
}
You can also use a MessageBox
with YesNo
options:
if (MessageBox.Show("Are you sure want to doing this?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
MessageBox.Show("You are pressed Yes!");
}
else
{
MessageBox.Show("You are pressed No!");
}
You can try strtotime() and date() functions for output in minimum code and using standard way.
echo date('Y', strtotime('2068-06-15'));
git lfs migrate import --include="fpss.tar.gz"
this should re-write your local commits with the new lfs refs
Calling the built-in function stat($fh)
returns an array with the following information about the file handle passed in (from the perlfunc man page for stat
):
0 dev device number of filesystem
1 ino inode number
2 mode file mode (type and permissions)
3 nlink number of (hard) links to the file
4 uid numeric user ID of file's owner
5 gid numeric group ID of file's owner
6 rdev the device identifier (special files only)
7 size total size of file, in bytes
8 atime last access time since the epoch
9 mtime last modify time since the epoch
10 ctime inode change time (NOT creation time!) since the epoch
11 blksize preferred block size for file system I/O
12 blocks actual number of blocks allocated
Element number 9 in this array will give you the last modified time since the epoch (00:00 January 1, 1970 GMT). From that you can determine the local time:
my $epoch_timestamp = (stat($fh))[9];
my $timestamp = localtime($epoch_timestamp);
Alternatively, you can use the built-in module File::stat
(included as of Perl 5.004) for a more object-oriented interface.
And to avoid the magic number 9 needed in the previous example, additionally use Time::localtime
, another built-in module (also included as of Perl 5.004). Together these lead to some (arguably) more legible code:
use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);
if your config.properties is not in src/main/resource directory and it is in root directory of the project then you need to do somethinglike below :-
Properties prop = new Properties();
File configFile = new File(myProp.properties);
InputStream stream = new FileInputStream(configFile);
prop.load(stream);
Below are various ways to convert to char c to String s (in decreasing order of speed and efficiency)
char c = 'a';
String s = String.valueOf(c); // fastest + memory efficient
String s = Character.toString(c);
String s = new String(new char[]{c});
String s = String.valueOf(new char[]{c});
String s = new Character(c).toString();
String s = "" + c; // slowest + memory inefficient
http://jsfiddle.net/kkobold/qMQL5/
#header {_x000D_
width: 100%;_x000D_
background-color: red;_x000D_
height: 30px;_x000D_
}_x000D_
_x000D_
#container {_x000D_
width: 300px;_x000D_
background-color: #ffcc33;_x000D_
margin: auto;_x000D_
}_x000D_
#first {_x000D_
width: 100px;_x000D_
float: left;_x000D_
height: 300px;_x000D_
background-color: blue;_x000D_
}_x000D_
#second {_x000D_
width: 200px;_x000D_
float: left;_x000D_
height: 300px;_x000D_
background-color: green;_x000D_
}_x000D_
#clear {_x000D_
clear: both;_x000D_
}
_x000D_
<div id="header"></div>_x000D_
<div id="container">_x000D_
<div id="first"></div>_x000D_
<div id="second"></div>_x000D_
<div id="clear"></div>_x000D_
</div>
_x000D_
One more solution:
c.ContactId + ""
Just add empty string and it will be converted to string.
You can just go to Breakpoints in the chrome developer console, right click and remove breakpoints. Simple.
There is an excellent answer from Orwellophile, which does include a pure bash option (function rawurlencode), which I've used on my website (shell based CGI script, large number of URLS in response to search requests). The only draw back was high CPU during peak time.
I've found a modified solution, leverage bash "global replace" feature. With this solution processing time for url encode is 4X faster. The solution identify the characters to be escaped, and uses the "global replace" operator (${var//source/replacement}) to process all substitutions. The speed up is clearly from using bash internal loops, over explicit loop.
Performance: On core i3-8100 3.60Ghz. Test case: 1000 URL from stack overflow, similar to this ticket: "https://stackoverflow.com/questions/296536/how-to-urlencode-data-for-curl-command".
url_encode()
{
local key="${1}" varname="${2:-_rval}" prefix="${3:-_ENCKEY_}"
local unsafe=${key//[-_.~a-zA-Z0-9 ]/}
local -i key_len=${#unsafe}
local ch ch1 ch0
while [ "$unsafe" ] ;do
ch=${unsafe:0:1}
ch0="\\$ch"
printf -v ch1 '%%%02x' "'$ch'"
key=${key//$ch0/"$ch1"}
unsafe=${unsafe//"$ch0"}
done
key=${key// /+}
REPLY="$key"
# printf "%s" "$REPLY"
return 0
}
As a minor extra, it uses '+' to encode the space. Slightly more compact URL.
Benchmark:
function t {
local key
for (( i=1 ; i<=$1 ; i++ )) do url_encode "$2" kkk2 ; done
echo "K=$REPLY"
}
t 1000 "https://stackoverflow.com/questions/296536/how-to-urlencode-data-for-curl-command"
This might help: https://stackoverflow.com/a/4196465/683114
if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
$(window).load(function(){
$('input:-webkit-autofill').each(function(){
var text = $(this).val();
var name = $(this).attr('name');
$(this).after(this.outerHTML).remove();
$('input[name=' + name + ']').val(text);
});
});
}
It looks like on load, it finds all inputs with autofill, adds their outerHTML and removes the original, while preserving value and name (easily changed to preserve ID etc)
If this preserves the autofill text, you could just set
var text = ""; /* $(this).val(); */
From the original form where this was posted, it claims to preserve autocomplete. :)
Good luck!
No need for jQuery! This simple snippet works fine for me. It uses angular.element() to bind window resize event.
/**
* Window resize event handling
*/
angular.element($window).on('resize', function () {
console.log($window.innerWidth);
});
/**
* Window resize unbind event
*/
angular.element($window).off('resize');
Another answer here also mentions since 2012 you can remove Remove cached login via How to remove cached server names from the Connect to Server dialog?. Just confirmed this delete in MRU list works fine in 2016 and 2017.
SQL Server Management Studio 2017 delete the file
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\14.0\SqlStudio.bin
SQL Server Management Studio 2016 delete the file
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin
SQL Server Management Studio 2014 delete the file
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\12.0\SqlStudio.bin
SQL Server Management Studio 2012 delete the file
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\11.0\SqlStudio.bin
SQL Server Management Studio 2008 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
SQL Server Management Studio 2005 delete the file – same as above answer but the Vista path.
C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat
These are profile paths for Vista / 7 / 8.
EDIT:
Note, AppData
is a hidden folder. You need to show hidden folders in explorer.
EDIT: You can simply press delete from the Server / User name drop down (confirmed to be working for SSMS v18.0). Original source from https://blog.sqlauthority.com/2013/04/17/sql-server-remove-cached-login-from-ssms-connect-dialog-sql-in-sixty-seconds-049/ which mentioned that this feature is available since 2012!
Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.
That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'
? Absolutely!
String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"
Everything seems to work fine to me! indexOf
can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.
It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!
String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;
It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):
In the Java programming language, unlike C, an array of
char
is not aString
, and neither aString
nor an array ofchar
is terminated by '\u0000' (the NUL character).
Would this be the culprit to the funky characters?
Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.
That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.
Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence)
overload.
System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU
The replaceAll
solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.
The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>
The address could be something like
1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)
or simply
1600 Amphitheatre Parkway, Mountain View, CA
By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY
inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.
{"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4222556,
"lng" : -122.0838589
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4236045802915,
"lng" : -122.0825099197085
},
"southwest" : {
"lat" : 37.4209066197085,
"lng" : -122.0852078802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}],"status" : "OK"}
Web Frameworks such like AngularJS allow us to perform these queries with ease.
string str = "123";
int i = Int.Parse(str);
If str is a valid integer string then it will be converted to integer and stored in i other wise Exception occur.
Instead of
Image.open(picture.jpg)
Img.show
You should have
from PIL import Image
#...
img = Image.open('picture.jpg')
img.show()
You should probably also think about an other system to show your messages, because this way it will be a lot of manual work. Look into string substitution (using %s
or .format()
).
Using jQuery:
function doSomething(element) {
var form = $(element).closest("form").get().
//do something with the form.
}
Update: As stated in the comments by @jeff-xiao this extension is Deprecated and it's now a built in feature of Visual Studio code. It should be available at the bottom of file explorer as "Outline" view.
Previous text: There is now an Extension that supports this. Code Outline creates a panel in the "Explorer" section and for JavaScript, will list variables and functions in a file. I've been using this for a while now and it scratches the itch I had. Other commenters have mentioned it supports Python and PHP well.
It still seems to be in development but I haven't had any issues. Development version available on GitHub. If you're the author reading this - thanks!
I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.
def rotate(origin, point, angle):
"""
Rotate a point counter-clockwise by a given angle around a given origin.
"""
# Convert negative angles to positive
angle = normalise_angle(angle)
# Convert to radians
angle = math.radians(angle)
# Convert to radians
ox, oy = origin
px, py = point
# Move point 'p' to origin (0,0)
_px = px - ox
_py = py - oy
# Rotate the point 'p'
qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
# Move point 'p' back to origin (ox, oy)
qx = ox + qx
qy = oy + qy
return [qx, qy]
def normalise_angle(angle):
""" If angle is negative then convert it to positive. """
if (angle != 0) & (abs(angle) == (angle * -1)):
angle = 360 + angle
return angle
You can have multiple CSS declarations for the same properties by separating them with commas:
.abc, .xyz {
margin-left: 20px;
}
If you are testing a string for a numeric value then you can use the a regular expression and the -match
comparison. Otherwise Christian's answer is a good solution for type checking.
function Is-Numeric ($Value) {
return $Value -match "^[\d\.]+$"
}
Is-Numeric 1.23
True
Is-Numeric 123
True
Is-Numeric ""
False
Is-Numeric "asdf123"
False
Anonymous classes must extend or implement something, like any other Java class, even if it's just java.lang.Object
.
For example:
Runnable r = new Runnable() {
public void run() { ... }
};
Here, r
is an object of an anonymous class which implements Runnable
.
An anonymous class can extend another class using the same syntax:
SomeClass x = new SomeClass() {
...
};
What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.
If you're trying to open a scala/sbt project, the sbt version set in /project/build.properties
must match the sbt version installed on your system or intellij won't detect your project's modules properly.
Once that's done, you can just delete the idea
folder and restart as the other answers suggest.
Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:
SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM
tartikel AS p1 INNER JOIN tartikelpict AS p2
ON p1.kArtikel = p2.kArtikel
WHERE
DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
AND p2.nNr = 1
ORDER BY
p1.kArtikel DESC
LIMIT
100;
With synchronized blocks, you can have multiple synchronizers, so that multiple simultaneous but non-conflicting things can go on at the same time.
Sure officially version says the cards are the new replacements for Bootstrap wells. But Cards are a quite broad Bootstrap components now. In simple terms, you can also use Bootstrap Jumbotron too.
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
Normally this error occurs when it try to load the previous state. This happened in Mac Virtual box. I tried after restarting the virtual box but again also i've encountered this issue. Right Click on the operating system in the virtual box and then Click on the Discard Saved State.. .This fixed the issue.
Spring boot has many starters, some starters have an embedded web server, some don't. The following have the embedded web server:
spring-boot-starter-web
spring-boot-starter-data-jpa
spring-boot-starter-jetty
spring-boot-starter-tomcat
spring-boot-starter-jdbc
spring-boot-starter-data-rest
...
Pick the one that meets your requirements and that does not have server support.
I only need to make restful json api request in my spring application, so the starter I need is
spring-boot-starter-json
which provide RestTemplate
and jackson
for me to use.
Where you have written the code
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
EXPLORING DOCKER IMAGE!
bash
or sh
...Inspect the image first: docker inspect name-of-container-or-image
Look for entrypoint
or cmd
in the JSON return.
docker run --rm -it --entrypoint=/bin/bash name-of-image
once inside do: ls -lsa
or any other shell command like: cd ..
The -it
stands for interactive... and TTY. The --rm
stands for remove container after run.
If there are no common tools like ls
or bash
present and you have access to the Dockerfile
simple add the common tool as a layer.
example (alpine Linux):
RUN apk add --no-cache bash
And when you don't have access to the Dockerfile
then just copy/extract the files from a newly created container and look through them:
docker create <image> # returns container ID the container is never started.
docker cp <container ID>:<source_path> <destination_path>
docker rm <container ID>
cd <destination_path> && ls -lsah
/[a-zA-Z]+/
Super simple example. Regular expressions are extremely easy to find online.
Splits the string in text
on any consecutive runs of whitespace.
words = text.split()
Split the string in text
on delimiter: ","
.
words = text.split(",")
The words variable will be a list
and contain the words from text
split on the delimiter.
If you want to clear the div and remove all child nodes, you could put:
var mydiv = document.getElementById('FirstDiv');
while(mydiv.firstChild) {
mydiv.removeChild(mydiv.firstChild);
}
Not quite, although generally you can usually use some workaround on one of the forms
[^abc]
, which is character by character not a
or b
or c
, a(?!b)
, which is a
not followed by b
(?<!a)b
, which is b
not preceeded by a
None of these answers are working (date today 9th Dec 2018). The correct resolution here is to add .table-responsive-sm to your table:
<table class='table table-responsive-sm'>
[Your table]
</table>
This applies the responsiveness aspect only to the SM view (mobile). So in mobile view you get the scrolling as desired and in larger views the table is not responsive and thus displayed full width, as desired.
Docs: https://getbootstrap.com/docs/4.0/content/tables/#breakpoint-specific
A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:
var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));
Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:
var $a = $('#demoTable td'); var inner = ''; $a.children.html().each(function() { inner = inner + this.outerHTML; }); $a.html('New text' + inner);
insert into OPT (email, campaign_id)
select '[email protected]',100
from dual
where not exists(select *
from OPT
where (email ='[email protected]' and campaign_id =100));
Yes. You know that you can put any Object
into the Object
parameter of most JOptionPane.showXXX methods
, and often that Object
happens to be a JPanel
.
In your situation, perhaps you could use a JPanel
that has several JTextFields
in it:
import javax.swing.*;
public class JOptionPaneMultiInput {
public static void main(String[] args) {
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("x:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("y:"));
myPanel.add(yField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("x value: " + xField.getText());
System.out.println("y value: " + yField.getText());
}
}
}