If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
to use sendmail from the shell script
subject="mail subject"
body="Hello World"
from="[email protected]"
to="[email protected],[email protected]"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"
Try resetting your network settings
Settings -> General -> Reset -> Reset Network Settings
And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".
http://support.apple.com/kb/ts2529
This one worked for me.
I used xs2bush's method of getting an interval (using timeIntervalSinceDate
) and expanded on it a little bit. I wanted to make sure that I was getting the required accuracy that I needed and also that I was not running down the battery by keeping the gps radio on more than necessary.
I keep location running continuously with the following settings:
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
locationManager.distanceFilter = 5;
this is a relatively low drain on the battery. When I'm ready to get my next periodic location reading, I first check to see if the location is within my desired accuracy, if it is, I then use the location. If it's not, then I increase the accuracy with this:
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter = 0;
get my location and then once I have the location I turn the accuracy back down again to minimize the drain on the battery. I have written a full working sample of this and also I have written the source for the server side code to collect the location data, store it to a database and allow users to view gps data in real time or retrieve and view previously stored routes. I have clients for iOS, android, windows phone and java me. All clients are natively written and they all work properly in the background. The project is MIT licensed.
The iOS project is targeted for iOS 6 using a base SDK of iOS 7. You can get the code here.
Please file an issue on github if you see any problems with it. Thanks.
In my case it was a stupid mistake. I incorrectly set the "Run" scheme to use the "Distribution" build configuration instead of the "Debug" or "Release" one. Stupid mistake, but it took a while to debug it, so I'm going to add my answer to improve the knowledge base inside stack overflow!
Follow these Steps:
1.Open the Xcode->Select the project->select targets->Tick an automatically manage signing->then add your apple developer account->clean the project->build the project->run,everything works fine.
The previous answer is correct, but if the effect you are looking for is to redirect HTTP traffic for a domain to another IP there is a way.
Since it technically is not answering your question, I have asked and answered the question here:
You might need to uninstall antivirus (in my case I had to get rid of Avast).
This makes sure that crypto::cng
command will work. Otherwise it was giving me errors:
mimikatz $ crypto::cng
ERROR kull_m_patch_genericProcessOrServiceFromBuild ; OpenProcess (0x00000005)
After removing Avast:
mimikatz $ crypto::cng
"KeyIso" service patched
Magic. (:
Windows Defender is another program blocking the program to work, so you will need also to disable it for the time of using program at least.
Using CROSS APPLY
:
SELECT ID, Col1, Col2, Col3, MinValue
FROM YourTable
CROSS APPLY (SELECT MIN(d) AS MinValue FROM (VALUES (Col1), (Col2), (Col3)) AS a(d)) A
Note: This answer is outdated
www.iphonevideorecorder.com. There's a free trial I think, but after that you'd need to buy it. And you need to jailbreak your iphone.
For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using Ad Hoc Helper available from the App Store. For further details on this method, see Craig Hockenberry's Beta testing on iPhone 2.0 article
For jailbroken iPhones, you can use the following method which I have personally tested using the AccelerometerGraph sample app on iPhone OS 3.0.
First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate:
Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate.
Name: iPhone Developer
Certificate Type: Code Signing
Let me override defaults: Yes
Click Continue
Validity: 3650 days
Click Continue
Blank out the Email address field.
Click Continue until complete.
You should see "This root certificate is not trusted". This is expected.
Set the iPhone SDK to allow the self-signed certificate to be used:
sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist
If you have Xcode open, restart it for this change to take effect.
The following steps require openssh
, and uikittools
to be installed first. Replace jasoniphone.local
with the hostname of the target device. Be sure to set your own password on both the mobile
and root
users after installing SSH.
To manually compile and install your application on the phone as a system app (bypassing Apple's installation system):
Project, Set Active SDK, Device and Set Active Build Configuration, Release.
Compile your project normally (using Build, not Build & Go).
In the build/Release-iphoneos
directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device.
scp -r AccelerometerGraph.app root@jasoniphone:/Applications/
Let SpringBoard know the new application has been installed:
ssh [email protected] uicache
This only has to be done when you add or remove applications. Updated applications just need to be relaunched.
To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project.
Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard:
ssh [email protected] rm -r /Applications/AccelerometerGraph.app &&
ssh [email protected] uicache
When adding new element with jquery plugin calls, you can do like the following:
$('<div>...</div>').hoverCard(function(){...}).appendTo(...)
You probably need more blur and a little less spread.
box-shadow: -10px 0px 10px 1px #aaaaaa;
Try messing around with the box shadow generator here http://css3generator.com/ until you get your desired effect.
You can use: git remote -v
Documentation: https://git-scm.com/docs/git-remote
Manage the set of repositories ("remotes") whose branches you track. -v --verbose Be a little more verbose and show remote url after name. NOTE: This must be placed between remote and subcommand.
Try the following query:
;WITH CTE_DocTotal
AS
(
SELECT SUM(Sale + VAT) AS DocTotal_1
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
)
UPDATE CTE_DocTotal
SET DocTotal = CTE_DocTotal.DocTotal_1
You can also do something like this:
SELECT LAST (column_name) AS LAST_CUSTOMER FROM table_name;
You should use .NET Core, instead of .NET Framework or Xamarin, in the following 6 typical scenarios according to the documentation here.
1. Cross-Platform needs
Clearly, if your goal is to have an application (web/service) that should be able to run across platforms (Windows, Linux and MacOS), the best choice in the .NET ecosystem is to use .NET Core as its runtime (CoreCLR) and libraries are cross-platform. The other choice is to use the Mono Project.
Both choices are open source, but .NET Core is directly and officially supported by Microsoft and will have a heavy investment moving forward.
When using .NET Core across platforms, the best development experience exists on Windows with the Visual Studio IDE which supports many productivity features including project management, debugging, source control, refactoring, rich editing including Intellisense, testing and much more. But rich development is also supported using Visual Studio Code on Mac, Linux and Windows including intellisense and debugging. Even third party editors like Sublime, Emacs, VI and more work well and can get editor intellisense using the open source Omnisharp project.
2. Microservices
When you are building a microservices oriented system composed of multiple independent, dynamically scalable, stateful or stateless microservices, the great advantage that you have here is that you can use different technologies/frameworks/languages at a microservice level. That allows you to use the best approach and technology per micro areas in your system, so if you want to build very performant and scalable microservices, you should use .NET Core. Eventually, if you need to use any .NET Framework library that is not compatible with .NET Core, there’s no issue, you can build that microservice with the .NET Framework and in the future you might be able to substitute it with the .NET Core.
The infrastructure platform you could use are many. Ideally, for large and complex microservice systems, you should use Azure Service Fabric. But for stateless microservices you can also use other products like Azure App Service or Azure Functions.
Note that as of June 2016, not every technology within Azure supports the .NET Core, but .NET Core support in Azure will be increasing dramatically now that .NET Core is RTM released.
3. Best performant and scalable systems
When your system needs the best possible performance and scalability so you get the best responsiveness no matter how many users you have, then is where .NET Core and ASP.NET Core really shine. The more you can do with the same amount of infrastructure/hardware, the richer the experience you’ll have for your end users – at a lower cost.
The days of Moore’s law performance improvements for single CPUs does not apply anymore; yet you need to do more while your system is growing and need higher scalability and performance for everyday’ s more demanding users which are growing exponentially in numbers. You need to get more efficient, optimize everywhere, and scale better across clusters of machines, VMs and CPU cores, ultimately. It is not just a matter of user’s satisfaction; it can also make a huge difference in cost/TCO. This is why it is important to strive for performance and scalability.
As mentioned, if you can isolate small pieces of your system as microservices or any other loosely-coupled approach, it’ll be better as you’ll be able to not just evolve each small piece/microservice independently and have a better long-term agility and maintenance, but also you’ll be able to use any other technology at a microservice level if what you need to do is not compatible with .NET Core. And eventually you’d be able to refactor it and bring it to .NET Core when possible.
4. Command line style development for Mac, Linux or Windows.
This approach is optional when using .NET Core. You can also use the full Visual Studio IDE, of course. But if you are a developer that wants to develop with lightweight editors and heavy use of command line, .NET Core is designed for CLI. It provides simple command line tools available on all supported platforms, enabling developers to build and test applications with a minimal installation on developer, lab or production machines. Editors like Visual Studio Code use the same command line tools for their development experiences. And IDE’s like Visual Studio use the same CLI tools but hide them behind a rich IDE experience. Developers can now choose the level they want to interact with the tool chain from CLI to editor to IDE.
5. Need side by side of .NET versions per application level.
If you want to be able to install applications with dependencies on different versions of frameworks in .NET, you need to use .NET Core which provides 100% side-by side as explained previously in this document.
6. Windows 10 UWP .NET apps.
In addition, you may also want to read:
Node is asynchronous by nature, and that's what's great about it, so you really shouldn't be blocking the thread, but as this seems to be for a project controlling LED's, I'll post a workaraound anyway, even if it's not a very good one and shouldn't be used (seriously).
A while loop will block the thread, so you can create your own sleep function
function sleep(time, callback) {
var stop = new Date().getTime();
while(new Date().getTime() < stop + time) {
;
}
callback();
}
to be used as
sleep(1000, function() {
// executes after one second, and blocks the thread
});
I think this is the only way to block the thread (in principle), keeping it busy in a loop, as Node doesn't have any blocking functionality built in, as it would sorta defeat the purpose of the async behaviour.
How about this?
JSONObject jsonObject = new JSONObject (YOUR_JSON_STRING);
JSONObject ipinfo = jsonObject.getJSONObject ("ipinfo");
String ip_address = ipinfo.getString ("ip_address");
JSONObject location = ipinfo.getJSONObject ("Location");
String latitude = location.getString ("latitude");
System.out.println (latitude);
This sample code using "org.json.JSONObject"
You are doing everything right, except passing your bundle path to asset()
function.
According to documentation - in your example this should look like below:
{{ asset('bundles/webshome/css/main.css') }}
Tip: you also can call assets:install with --symlink
key, so it will create symlinks in web folder. This is extremely useful when you often apply js
or css
changes (in this way your changes, applied to src/YouBundle/Resources/public
will be immediately reflected in web
folder without need to call assets:install
again):
app/console assets:install web --symlink
Also, if you wish to add some assets in your child template, you could call parent()
method for the Twig block. In your case it would be like this:
{% block stylesheets %}
{{ parent() }}
<link href="{{ asset('bundles/webshome/css/main.css') }}" rel="stylesheet">
{% endblock %}
I spend a lot time to discover why my code could not find my file running Python 3 on the Windows system. So I added . before / and everything worked fine:
import os
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, './output03.txt')
print(file_path)
fptr = open(file_path, 'w')
With this query you can execute any stored procedure(With or Without output parameter):
DECLARE @temp varchar(100)
EXEC my_sp
@parameter1 = 1,
@parameter2 = 2,
@parameter3 = @temp output,
@parameter4 = 3,
@parameter5 = 4
PRINT @temp
Here datatype of @temp should be same as @parameter3 within SP.
Hope this helps..
Oh, dear. A few little problems...
As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.
Two other matters of which you should be aware:
First, set/p
will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter
in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:
set "var="
set /p var=
That is, of course, if you don't WANT enter
to repeat the existing value.
Another useful form is
set "var=default"
set /p var=
or
set "var=default"
set /p "var=[%var%]"
(which prompts with the default value; !var!
if in a block statement with delayedexpansion)
Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment
(which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)
It's the Unicode Character 'ZERO WIDTH SPACE' (U+200B).
this character is intended for line break control; it has no width, but its presence between two characters does not prevent increased letter spacing in justification
As per the given code sample, the entity is entirely superfluous in this context. It must be inserted by some accident, most likely by a buggy editor trying to do smart things with whitespace or highlighting, or an enduser using a keyboard language wherein this character is natively been used, such as Arabic.
git config [--global] user.name "Full Name"
git config [--global] user.email "[email protected]"
Per repo basis you could also edit .git/config
manually instead.
When performing step 2 if you see credential.helper=manager
you need to open the credential manager of your computer (Win or Mac) and update the credentials there
I wouldn't use HttpListener or something like that, in that way you'll come across so many issues.
Most importantly it'll be a huge pain to support:
What you need to do is:
I wrote 2 different HTTP proxies in .NET with different requirements and I can tell you that this is the best way to do it.
Mentalis doing this, but their code is "delegate spaghetti", worse than GoTo :)
I've collected info together:
user_link
, see https://developers.facebook.com/docs/facebook-login/permissions/link
(e.g. https://graph.facebook.com/me?fields=link,name,email)link
from answer. Be aware of field length- in my case it is 202: https://www.facebook.com/app_scoped_user_id/YXNpZADpBWEd0SlhFZAElYa3BQT3U3Tm4xWVRLSlJfYUdUM3Y4YmIwQjBaRkM0VDBMNURQdUhhYk5NRDJoR1ZA5ZA1JOdGNwampsSTQyMDQwbW93bkp0dnZAmOXg3NTFISFVZAQlRscWQ5eEZAvcU4xZAC1B/And finaly: it doen't work without additional Facebook permission check:(
The result depends on the timezone that corresponds to the input time strings.
The simplest case if both dates use the same utc offset:
#!/usr/bin/env python3
from datetime import datetime, timedelta
time_format = "%Y-%d-%m %H:%M:%S"
dt1 = datetime.strptime("2010-01-01 17:31:22", time_format)
dt2 = datetime.strptime("2010-01-03 17:31:22", time_format)
print((dt2 - dt1) // timedelta(minutes=1)) # minutes
If your Python version doesn't support td // timedelta
; replace it with int(td.total_seconds() // 60)
.
If the input time is in the local timezone that might have different utc offset at different times e.g., it has daylight saving time then you should make dt1
, dt2
into aware datetime objects before finding the difference, to take into account the possible changes in the utc offset.
The portable way to make an aware local datetime objects is to use pytz
timezones:
#!/usr/bin/env python
from datetime import timedelta
import tzlocal # $ pip install tzlocal
local_tz = tzlocal.get_localzone() # get pytz timezone
aware_dt1, aware_dt2 = map(local_tz.localize, [dt1, dt2])
td = aware_dt2 - aware_dt1 # elapsed time
If either dt1
or dt2
correspond to an ambiguous time then the default is_dst=False
is used to disambiguate. You could set is_dst=None
to raise an exception for ambiguous or non-existent local times instead.
If you can't install 3rd party modules then time.mktime()
could be used from @Ken Cochrane's answer that can find the correct utc offset on some platforms for some dates in some timezones -- if you don't need a consistent (but perhaps wrong) result then it is much better than doing dt2 - dt1
with naive datetime objects that always fails if the corresponding utc offsets are different.
Use .is(':checked')
to determine whether or not it's checked, and then set your value accordingly.
First of all, a warning: what follows is strictly in the realm of ugly, undocumented hacks. Do not rely on this working - even if it works for you now, it may stop working tomorrow, with any minor or major .NET update.
You can use the information in this article on CLR internals MSDN Magazine Issue 2005 May - Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects - last I checked, it was still applicable. Here's how this is done (it retrieves the internal "Basic Instance Size" field via TypeHandle
of the type).
object obj = new List<int>(); // whatever you want to get the size of
RuntimeTypeHandle th = obj.GetType().TypeHandle;
int size = *(*(int**)&th + 1);
Console.WriteLine(size);
This works on 3.5 SP1 32-bit. I'm not sure if field sizes are the same on 64-bit - you might have to adjust the types and/or offsets if they are not.
This will work for all "normal" types, for which all instances have the same, well-defined types. Those for which this isn't true are arrays and strings for sure, and I believe also StringBuilder
. For them you'll have add the size of all contained elements to their base instance size.
If you use spyder and love GUI, you can simply click on the folder button on the upper right corner of your screen and navigate through folders/directories you want as current directory. After doing so you can go to the file explorer tab of the window in spyder IDE and you can see all the files/folders present there. to check your current working directory go to the console of spyder IDE and simply type
pwd
it will print the same path as you have selected before.
grid.store = store;
store.load({ params: { start: 0, limit: 20} });
grid.getView().refresh();
You have to import the font in your stylesheet like this:
@font-face{
font-family: "Thonburi-Bold";
src: url('Thonburi-Bold.ttf'),
url('Thonburi-Bold.eot'); /* IE */
}
It could be something like:
var qry = from t in db.Lasttraces
group t by t.AccountId into g
orderby t.Date
select new { g.AccountId, Date = g.Max(e => e.Date) };
Use SpannableBuilder class instead of HTML formatting where it possible because it more faster then HTML format parsing. See my own benchmark "SpannableBuilder vs HTML" on Github Thanks!
Make sure that you run the SQL Server Configuration Manager snap-in as Administrator if UAC is enabled. Then right click the service and then click properties, change the start mode to enabled, then start it.
Add this to the your code:
import pyspark
def spark_shape(self):
return (self.count(), len(self.columns))
pyspark.sql.dataframe.DataFrame.shape = spark_shape
Then you can do
>>> df.shape()
(10000, 10)
But just remind you that .count()
can be very slow for very large table that has not been persisted.
Maybe not as elegant as some previous answers, but if you want to achieve switch cases with few large ranges, just combine ranges to a single case beforehand:
// make a switch variable so as not to change the original value
int switchVariable = variable;
//combine range 1-100 to one single case in switch
if(1 <= variable && variable <=100)
switchVariable = 1;
switch (switchVariable)
{
case 0:
break;
case 1:
// range 1-100
doSomething();
break;
case 101:
doSomethingElse();
break;
etc.
}
In Visual Basic, you can call a parameterless method without the braces (()
). In C#, they're mandatory. So you should write:
String guid = System.Guid.NewGuid().ToString();
Without the braces, you're assigning the method itself (instead of its result) to the variable guid
, and obviously the method cannot be converted to a String
, hence the error.
You can use 'IF EXISTS' to check if the view exists and drop if it does.
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'MyView') DROP VIEW MyView GO CREATE VIEW MyView AS .... GO
My 2 cents.
This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.
On the other hand if its some client I don't control then it is a good idea to do thorough error checking.
There's a few things with your code as it stands:
The first thing we are going to do is to declare your variable as let
, as we are not going to modify it later.
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")! // We can force unwrap because we are 100% certain the constructor will not return nil in this case.
Then we need to download the contents of that URL. We can do this with the URLSession
object. When the completion handler is called, we will have a UIImage
downloaded from the web.
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
Finally you need to call resume
on the download task, otherwise your task will never start:
downloadPicTask.resume()
.
All this code may look a bit intimidating at first, but the URLSession
APIs are block based so they can work asynchronously - If you block your UI thread for a few seconds, the OS will kill your app.
Your full code should look like this:
let catPictureURL = URL(string: "http://i.imgur.com/w5rkSIj.jpg")!
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
print("Downloaded cat picture with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
let image = UIImage(data: imageData)
// Do something with your image.
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
This is caused when your request response is not received in given time(by timeout
request module option).
Basically to catch that error first, you need to register a handler on error
, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ })
. Some more explanation here.
In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }
.
If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.
If you want to wait longer, you can set timeout
option of request yourself. You can set it to 0 for no timeout.
int abc= (Math.random()*100);// wrong
you wil get below error message
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int
int abc= (int) (Math.random()*100);// add "(int)" data type
,known as type casting
if the true result is
int abc= (int) (Math.random()*1)=0.027475
Then you will get output as "0" because it is a integer data type.
int abc= (int) (Math.random()*100)=0.02745
output:2 because (100*0.02745=2.7456...etc)
It isn't that hard to deal with the character array itself without converting the array to a string. Especially in the case where the length of the character array is know or can be easily found. With the character array, the length must be determined in the same scope as the array definition, e.g.:
size_t len sizeof myarray/sizeof *myarray;
For strings you, of course, have strlen
available.
With the length known, regardless of whether it is a character array or a string, you can convert the character values to a number with a short function similar to the following:
/* convert character array to integer */
int char2int (char *array, size_t n)
{
int number = 0;
int mult = 1;
n = (int)n < 0 ? -n : n; /* quick absolute value check */
/* for each character in array */
while (n--)
{
/* if not digit or '-', check if number > 0, break or continue */
if ((array[n] < '0' || array[n] > '9') && array[n] != '-') {
if (number)
break;
else
continue;
}
if (array[n] == '-') { /* if '-' if number, negate, break */
if (number) {
number = -number;
break;
}
}
else { /* convert digit to numeric value */
number += (array[n] - '0') * mult;
mult *= 10;
}
}
return number;
}
Above is simply the standard char to int conversion approach with a few additional conditionals included. To handle stray characters, in addition to the digits
and '-'
, the only trick is making smart choices about when to start collecting digits and when to stop.
If you start collecting digits
for conversion when you encounter the first digit
, then the conversion ends when you encounter the first '-'
or non-digit
. This makes the conversion much more convenient when interested in indexes such as (e.g. file_0127.txt
).
A short example of its use:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int char2int (char *array, size_t n);
int main (void) {
char myarray[4] = {'-','1','2','3'};
char *string = "some-goofy-string-with-123-inside";
char *fname = "file-0123.txt";
size_t mlen = sizeof myarray/sizeof *myarray;
size_t slen = strlen (string);
size_t flen = strlen (fname);
printf ("\n myarray[4] = {'-','1','2','3'};\n\n");
printf (" char2int (myarray, mlen): %d\n\n", char2int (myarray, mlen));
printf (" string = \"some-goofy-string-with-123-inside\";\n\n");
printf (" char2int (string, slen) : %d\n\n", char2int (string, slen));
printf (" fname = \"file-0123.txt\";\n\n");
printf (" char2int (fname, flen) : %d\n\n", char2int (fname, flen));
return 0;
}
Note: when faced with '-'
delimited file indexes (or the like), it is up to you to negate the result. (e.g. file-0123.txt
compared to file_0123.txt
where the first would return -123
while the second 123
).
Example Output
$ ./bin/atoic_array
myarray[4] = {'-','1','2','3'};
char2int (myarray, mlen): -123
string = "some-goofy-string-with-123-inside";
char2int (string, slen) : -123
fname = "file-0123.txt";
char2int (fname, flen) : -123
Note: there are always corner cases, etc. that can cause problems. This isn't intended to be 100% bulletproof in all character sets, etc., but instead work an overwhelming majority of the time and provide additional conversion flexibility without the initial parsing or conversion to string required by atoi
or strtol
, etc.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users
is a PDOStatement
object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach
is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch
will return false
, since you have already exhausted the result set (see above), so you get an error trying to loop over false
.
In the last example you are simply fetching the first result row and are looping over it.
You could also use
ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);
if your working with a absolut value as layout.
Git reset, as mentioned in many answers before, is by far the best and simplest way to achieve what you want. I use it in the following workflow:
(on development branch)
git fetch
git merge origin/master #so development branch has all current changes from master
git reset origin/master #will show all changes from development branch to master as unstaged
git gui # do a final review, stage all changes you really want
git commit # all changes in a single commit
git branch -f master #update local master branch
git push origin master #push it
Which is best way to pause the console in C++ programs?
system("pause");
and getch();
(which comes from the DOS world, IIRC) are both unportable.
Is cin.get() is better to use to pause console?
As the only one portable and standard option, I would say it is, but I personally believe one should not write interactive console programs, i.e. programs which actually pause the console or prompt for input (unless there is a really good reason for that, because that makes shell scripting much harder). Console programs should interact with the user via command line arguments (or at least that kind of interaction should be the default one).
Just in case you need pausing the program for the my-program-is-launched-from-the-IDE-and-immediately-closed-but-I-don't-have-enough-time-to-see-the-result reason — don't do that. Just configure your IDE or launch console programs right from the console.
The error message is telling you.
Try just
"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"
When you enclose the string in single-quotes, this makes everything inside a valid string, including the "
chars. By removing the single-quotes, the shell will process the dbl-quotes as string "wrappers".
I would also wrap the filename variable in dbl-quotes so you can easily process files with spaces in their names, i.e.
"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"
IHTH
$(".show-pass").click(function (e) {_x000D_
e.preventDefault();_x000D_
var type = $("#signupform-password").attr('type');_x000D_
switch (type) {_x000D_
case 'password':_x000D_
{_x000D_
$("#signupform-password").attr('type', 'text');_x000D_
return;_x000D_
}_x000D_
case 'text':_x000D_
{_x000D_
$("#signupform-password").attr('type', 'password');_x000D_
return;_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" name="password" class="show-pass">
_x000D_
$('input').keydown(function(e) {
e.preventDefault();
return false;
});
The earlier version of the accepted answer (md5(uniqid(mt_rand(), true))
) is insecure and only offers about 2^60 possible outputs -- well within the range of a brute force search in about a week's time for a low-budget attacker:
mt_rand()
is predictable (and only adds up to 31 bits of entropy)uniqid()
only adds up to 29 bits of entropymd5()
doesn't add entropy, it just mixes it deterministicallySince a 56-bit DES key can be brute-forced in about 24 hours, and an average case would have about 59 bits of entropy, we can calculate 2^59 / 2^56 = about 8 days. Depending on how this token verification is implemented, it might be possible to practically leak timing information and infer the first N bytes of a valid reset token.
Since the question is about "best practices" and opens with...
I want to generate identifier for forgot password
...we can infer that this token has implicit security requirements. And when you add security requirements to a random number generator, the best practice is to always use a cryptographically secure pseudorandom number generator (abbreviated CSPRNG).
In PHP 7, you can use bin2hex(random_bytes($n))
(where $n
is an integer larger than 15).
In PHP 5, you can use random_compat
to expose the same API.
Alternatively, bin2hex(mcrypt_create_iv($n, MCRYPT_DEV_URANDOM))
if you have ext/mcrypt
installed. Another good one-liner is bin2hex(openssl_random_pseudo_bytes($n))
.
Pulling from my previous work on secure "remember me" cookies in PHP, the only effective way to mitigate the aforementioned timing leak (typically introduced by the database query) is to separate the lookup from the validation.
If your table looks like this (MySQL)...
CREATE TABLE account_recovery (
id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT
userid INTEGER(11) UNSIGNED NOT NULL,
token CHAR(64),
expires DATETIME,
PRIMARY KEY(id)
);
... you need to add one more column, selector
, like so:
CREATE TABLE account_recovery (
id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT
userid INTEGER(11) UNSIGNED NOT NULL,
selector CHAR(16),
token CHAR(64),
expires DATETIME,
PRIMARY KEY(id),
KEY(selector)
);
Use a CSPRNG When a password reset token is issued, send both values to the user, store the selector and a SHA-256 hash of the random token in the database. Use the selector to grab the hash and User ID, calculate the SHA-256 hash of the token the user provides with the one stored in the database using hash_equals()
.
Generating a reset token in PHP 7 (or 5.6 with random_compat) with PDO:
$selector = bin2hex(random_bytes(8));
$token = random_bytes(32);
$urlToEmail = 'http://example.com/reset.php?'.http_build_query([
'selector' => $selector,
'validator' => bin2hex($token)
]);
$expires = new DateTime('NOW');
$expires->add(new DateInterval('PT01H')); // 1 hour
$stmt = $pdo->prepare("INSERT INTO account_recovery (userid, selector, token, expires) VALUES (:userid, :selector, :token, :expires);");
$stmt->execute([
'userid' => $userId, // define this elsewhere!
'selector' => $selector,
'token' => hash('sha256', $token),
'expires' => $expires->format('Y-m-d\TH:i:s')
]);
Verifying the user-provided reset token:
$stmt = $pdo->prepare("SELECT * FROM account_recovery WHERE selector = ? AND expires >= NOW()");
$stmt->execute([$selector]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($results)) {
$calc = hash('sha256', hex2bin($validator));
if (hash_equals($calc, $results[0]['token'])) {
// The reset token is valid. Authenticate the user.
}
// Remove the token from the DB regardless of success or failure.
}
These code snippets are not complete solutions (I eschewed the input validation and framework integrations), but they should serve as an example of what to do.
For markdown table syntax see:
https://www.markdownguide.org/extended-syntax/#tables
Quick summary:
To quickly understand the syntax used in other answers, it helps to start from a more complete intuitive and easier to remember syntax, and then a minimalized version with the same result.
Basic example:
| Header A | Header B |
| -------------- | -------------- |
| row 1 col 1 | row 1 col 2 |
| row 2 column 1 | row 2 column 2 |
Same result in a more minimalist form (cell widths can vary) :
Header A | Header B
--- | ---
row 1 col 1 | row 1 col 2
row 2 column 1 | row 2 column 2
And more related to the question: side by side images with labels on top:
label 1 | label 2
--- | ---
![](https://...image1.png) | ![](https://...image2.png)
( use :---
, ---:
, and :---:
for (text) alignment in the column, respectively: left, right, center )
var json = jQuery.parseJSON(s); //If you have jQuery.
Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
Change the above code to
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
Eg:
$(document).ready(function() {
var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
s = jQuery.parseJSON(s);
alert( s[0]["Select"] );
});
And then use the parse function. It'll surely work.
EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON
Edit (30 April 2020):
Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")
My case is different, it fails because of the scope of 'this':
//this fails:
$("#My-Dialog").dialog({
...
close: ()=>{
$(this).dialog("close");
}
});
//this works:
$("#My-Dialog").dialog({
...
close: function(){
$(this).dialog("close");
}
});
You can pass input as ["apple","orange"]
if you want to leave the method as it is.
It worked for me with a similar method signature.
Try this
<video autoplay loop id="video-background" muted plays-inline>
<source src="https://player.vimeo.com/external/158148793.hd.mp4?s=8e8741dbee251d5c35a759718d4b0976fbf38b6f&profile_id=119&oauth2_token_id=57447761" type="video/mp4">
</video>
Thanks
Extra Tips:
Multiple "nots", input that is NOT hidden and NOT disabled:
:not([type="hidden"]):not([disabled])
Also did you know you can do this:
node.parentNode.querySelectorAll('div');
This is equivelent to jQuery's:
$(node).parent().find('div');
Which will effectively find all divs in "node" and below recursively, HOT DAMN!
The most fundamental thing here probably is that you don't want to transmit static images but only changes to the images, which essentially is analogous to video stream.
My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is linear movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).
The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.
I had the same issue on Windows 7 and I had to install both JDK and JRE and it's a success.
Broadcast Receivers timeout after 10 seconds. Possibly your doing an asynchronous call (wrong) from a broadcast receiver and 4.3 actually detects it.
If I understand correctly, you wish to have everything in one page and execute it from the same page.
You can use the following code to send mail from a single page, for example index.php
or contact.php
The only difference between this one and my original answer is the <form action="" method="post">
where the action has been left blank.
It is better to use header('Location: thank_you.php');
instead of echo
in the PHP handler to redirect the user to another page afterwards.
<?php
if(isset($_POST['submit'])){
$to = "[email protected]"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
I wasn't quite sure as to what the question was, but am under the impression that a copy of the message is to be sent to the person who filled in the form.
Here is a tested/working copy of an HTML form and PHP handler. This uses the PHP mail()
function.
The PHP handler will also send a copy of the message to the person who filled in the form.
You can use two forward slashes //
in front of a line of code if you're not going to use it.
For example: // $subject2 = "Copy of your form submission";
will not execute.
<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>
<form action="mail_handler.php" method="post">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
(Uses info from HTML form and sends the Email)
<?php
if(isset($_POST['submit'])){
$to = "[email protected]"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
// You cannot use header and echo together. It's one or the other.
}
?>
To send as HTML:
If you wish to send mail as HTML and for both instances, then you will need to create two separate sets of HTML headers with different variable names.
Read the manual on mail()
to learn how to send emails as HTML:
Footnotes:
You have to specify the URL of the service that will handle the submitted data, using the action attribute.
As outlined at https://www.w3.org/TR/html5/forms.html under 4.10.1.3 Configuring a form to communicate with a server. For complete information, consult the page.
Therefore, action=""
will not work in HTML5.
The proper syntax would be:
action="handler.xxx"
or action="http://www.example.com/handler.xxx"
.Note that xxx
will be the extension of the type of file used to handle the process. This could be a .php
, .cgi
, .pl
, .jsp
file extension etc.
Consult the following Q&A on Stack if sending mail fails:
You can try using the ReadDir function in the io/ioutil
package. Per the docs:
ReadDir reads the directory named by dirname and returns a list of sorted directory entries.
The resulting slice contains os.FileInfo
types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir()
method):
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
files, err := ioutil.ReadDir("./")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Println(f.Name())
}
}
It's a null coalescing operator that works similarly to a ternary operator.
a ?? b => a !=null ? a : b
Another interesting point for this is, "A nullable type can contain a value, or it can be undefined". So if you try to assign a nullable value type to a non-nullable value type you will get a compile-time error.
int? x = null; // x is nullable value type
int z = 0; // z is non-nullable value type
z = x; // compile error will be there.
So to do that using ?? operator:
z = x ?? 1; // with ?? operator there are no issues
You just need to encode the <>
s:
<strong>Look just like this line - so then know how to type it</strong>
$ ps H p pid-id
H - Lists all the individual threads in a process
or
$cat /proc/pid-id/status
pid-id is the Process ID
eg.. (Truncated the below output)
root@abc:~# cat /proc/8443/status
Name: abcdd
State: S (sleeping)
Tgid: 8443
VmSwap: 0 kB
Threads: 4
SigQ: 0/256556
SigPnd: 0000000000000000
The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()
A reliable way to set a Date is to construct one and use the setFullYear
and setTime
methods.
An example of that appears here: http://jibbering.com/faq/#parseDate
ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.
YYYY-MM-DD
can be parsed to a Date
with the following:-
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* @param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* @return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
Knockout's documentation also mentions a much cleaner way of passing extra parameters to functions bound using an on-click
binding using function.bind like this:
<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">
Click me
</button>
you need a way to say that "i am running" from the app,
1) open a WCF ping service 2) write to registry/file on startup and delete on shutdown 3) create a Mutex
... i prefer the WCF part because you may not clean up file/registry correctly and Mutex seems to have its own issues
Under Windows this worked for me:
python -m pip install -U pip setuptools
python -m pip install matplotlib
What container are you adding the UserControl to? Generally when you add controls to a Grid, they will stretch to fill the available space (unless their row/column is constrained to a certain width).
Well, unfortunately it seems that one cannot place custom markers and draw (and obtain coordinates) directly from maps.google.com if one is anonymous/not logged in (as it was possible some years ago, if I recall correctly). Still, thanks to the answers here, I managed to make a combination of examples that has both the Google Places search, and allows drawing via the drawing library, and dumps coordinates upon making a selection of any type of shape (including coordinates for polygon) that can be copypasted; the code is here:
This is how it looks like:
(The Places markers are handled separately, and can be deleted via the DEL "button" by the search input form element; "curpos" shows the current center [position] and zoom level of the map viewport).
I had a similar issue on my controller and here is what worked for me:
model.DateSigned.HasValue ? model.DateSigned.Value.ToString("MM/dd/yyyy") : ""
"DateSigned" is the value from my model The line reads, if the model value has a value then format the value, otherwise show nothing.
Hope that helps
Below snippet disable highlighting but it also disable the call to didSelectRowAtIndexPath
. So if you are not implementing didSelectRowAtIndexPath
then use below method. This should be added when you are creating the table. This will work on buttons and UITextField
inside the cell though.
self.tableView.allowsSelection = NO;
Below snippet disable highlighting and it doesn't disable the call to didSelectRowAtIndexPath
. Set the selection style of cell to None in cellForRowAtIndexPath
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Below snippet disable everything on the cell. This will disable the interaction to buttons
, textfields
:
self.tableView.userInteractionEnabled = false;
Below are the Swift
equivalent of above Objective-C
solutions:
Replacement of First Solution
self.tableView.allowsSelection = false
Replacement of Second Solution
cell?.selectionStyle = UITableViewCellSelectionStyle.None
Replacement of Third Solution
self.tableView.userInteractionEnabled = false
SELECT * FROM Table_Name LIMIT 5;
You can use the .Clear method:
Sheets("Zeros").UsedRange.Clear
Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.
When use codeIgniter Framework then refer this active records link. how the data interact with structure and more.
The following functions allow you to build SQL SELECT statements.
Selecting Data
$this->db->get();
Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:
$query = $this->db->get('mytable');
With access to each row
$query = $this->db->get('mytable');
foreach ($query->result() as $row)
{
echo $row->title;
}
Where clues
$this->db->get_where();
EG:
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
Select field
$this->db->select('title, content, date');
$query = $this->db->get('mytable');
// Produces: SELECT title, content, date FROM mytable
E.G
$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
$query = $this->db->get('mytable');
The problem with other answers here is that they use position: absolute;
This makes it difficult to layout the element itself in relation to the ::before
pseudo-element. For example, if you wish to show an image before a link like this:
Here's how I was able to achieve the layout in the picture:
a::before {_x000D_
content: "";_x000D_
float: left;_x000D_
width: 16px;_x000D_
height: 16px;_x000D_
margin-right: 5px;_x000D_
background: url(../../lhsMenu/images/internal_link.png) no-repeat 0 0;_x000D_
background-size: 80%;_x000D_
}
_x000D_
Note that this method allows you to scale the background image, as well as keep the ability to use margins and padding for layout.
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
It is not on PyPI and you should not be installing it via pip
. If you have matplotlib
installed, you should be able to import mpl_toolkits
directly:
$ pip install --upgrade matplotlib
...
$ python
>>> import mpl_toolkits
>>>
<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div class="content">
I would like to display a loading bar before the entire page is loaded.
</div>
$(function() {
$(".preload").fadeOut(2000, function() {
$(".content").fadeIn(1000);
});
});?
.content {display:none;}
.preload {
width:100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
}
?
enter code here
Create script file with below gradle and adb command, Execute script file
./gradlew clean
./gradlew assembleDebug ./gradlew installDebug
adb shell am start -n applicationID/full path of launcher activity
I know that I'm late to the party, but there is another solution that I'm using. It might be handy for distros that don't have --stdin
in passwd binary.
- hosts: localhost
become: True
tasks:
- name: Change user password
shell: "yes '{{ item.pass }}' | passwd {{ item.user }}"
loop:
- { pass: 123123, user: foo }
- { pass: asdf, user: bar }
loop_control:
label: "{{ item.user }}"
Label in loop_control
is responsible for printing only username. The whole playbook or just user variables (you can use vars_files:
) should be encrypted with ansible-vault.
The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array
's. What's more, Array
is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:
function Array() { return []; }
alert(Array(1, 2, 3)); // An empty alert box
However, the larger issue is that of consistency. Someone refactoring code could come across this function:
function fetchValue(n) {
var arr = new Array(1, 2, 3);
return arr[n];
}
As it turns out, only fetchValue(0)
is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined
:
var arr = new Array(1);
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
I needed to update my php from 5.3.8 to 5.3.29. (both Thread Safe) on Windows
Steps I did:
Hope that I covered everything.
Most probably these steps will not work if you change major versions of php, e.g. 5.3.x to 5.4.x, but for minor versions, it should work.
Also, a good way to see what's wrong... start command line and try to start httpd.exe, under xampp/apache/bin from there, it will list errors found.
As aditional information on @Quentin answer, and as he rightly says,
background
CSS property itself, is a shorthand for:
background-color
background-image
background-repeat
background-attachment
background-position
That's mean, you can group all styles in one, like:
background: red url(../img.jpg) 0 0 no-repeat fixed;
This would be (in this example):
background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;
So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none;
and all the others to the initial
state (as they are not being declared).
So, background:none;
is:
background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
Now, when you define only the color (in your case transparent
) then you are basically saying:
background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;
I repeat, as @Quentin rightly says the default
transparent
and none
values in this case are the same, so in your example and for your original question, No, there's no difference between them.
But!.. if you say background:none
Vs background:red
then yes... there's a big diference, as I say, the first would set all properties to none/default
and the second one, will only change the color
and remains the rest in his default
state.
Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.
default
)Initial value the concatenation of the initial values of its longhand properties:
background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent
background
descriptions hereUpd2: Clarify better the background:none;
specification.
# Use slicing to extract those parts of the original string to be kept
s = s[:position] + replacement + s[position+length_of_replaced:]
# Example: replace 'sat' with 'slept'
text = "The cat sat on the mat"
text = text[:8] + "slept" + text[11:]
I/P : The cat sat on the mat
O/P : The cat slept on the mat
For details of setting up a proxy for Maven, see the mini guide.
Essentially you need to ensure the proxies section in either the global settings ([maven install]/conf/settings.xml
), or user settings (${user.home}/.m2/settings.xml
) is configured correctly. It is better to do this in your user settings to avoid storing the password in plain text in a public location.
Maven 2.1 introduced password encryption, but I've not got round to checking if the encryption applies for the proxy settings as well as repository passwords (don't see why it wouldn't though).
For info, there is a commented-out proxy configuration in your settings.xml and instructions on how to modify it.
From the mini-guide, your settings should look something like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
[...]
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxy.somewhere.com</host>
<port>8080</port>
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
</proxy>
</proxies>
[...]
</settings>
It's simple. With rebase you say to use another branch as the new base for your work.
If you have, for example, a branch master
, you create a branch to implement a new feature, and say you name it cool-feature
, of course the master branch is the base for your new feature.
Now at a certain point you want to add the new feature you implemented in the master
branch. You could just switch to master
and merge the cool-feature
branch:
$ git checkout master
$ git merge cool-feature
But this way a new dummy commit is added. If you want to avoid spaghetti-history you can rebase:
$ git checkout cool-feature
$ git rebase master
And then merge it in master
:
$ git checkout master
$ git merge cool-feature
This time, since the topic branch has the same commits of master plus the commits with the new feature, the merge will be just a fast-forward.
let documentsURL = try! FileManager().url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:
let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
It can be done in your code via WMI. I've found a tool from Microsoft that creates code for it.
The WMI Code Creator tool allows you to generate VBScript, C#, and VB .NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.
You can download it here.
Get Schema Name and Table Name from a database.
public IList<Tuple<string, string>> ListTables()
{
DataTable dt = con.GetSchema("Tables");
var tables = new List<Tuple<string, string>>();
foreach (DataRow row in dt.Rows)
{
string schemaName = (string)row[1];
string tableName = (string)row[2];
//AddToList();
tables.Add(Tuple.Create(schemaName, tableName));
Console.WriteLine(schemaName +" " + tableName) ;
}
return tables;
}
You could use a nested Any()
for this check which is available on any Enumerable
:
bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));
Faster performing on larger collections would be to project parameters
to source
and then use Intersect
which internally uses a HashSet<T>
so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :
bool hasMatch = parameters.Select(x => x.source)
.Intersect(myStrings)
.Any();
Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.
Write the queue job information in long format to text file
qstat -f > queue.txt
Grep job names
grep 'Job_Name' queue.txt
Use the Attribute Equals Selector
var thevalue = 'foo';
var exists = 0 != $('#select-box option[value='+thevalue+']').length;
If the option's value was set via Javascript, that will not work. In this case we can do the following:
var exists = false;
$('#select-box option').each(function(){
if (this.value == 'bar') {
exists = true;
return false;
}
});
ECMAScript 6 introduced the let
statement. You can use it in a for
statement.
var ids:string = [];
for(let result of this.results){
ids.push(result.Id);
}
paint.setStrokeWidth(3);
paint.setColor(BLACK);
and either one of your drawRect
should work.
Unfortunately, none of the above answers worked for me, although all answers lead to the solution and eventually to my solution, here is the snippet if it helps someone. Thanks
This can be solved with the bash file, due to the layered architecture of the Docker, cron service doesn't get initiated with RUN/CMD/ENTRYPOINT commands.
Simply add a bash file which will initiate the cron and other services (if required)
DockerFile
FROM gradle:6.5.1-jdk11 AS build
# apt
RUN apt-get update
RUN apt-get -y install cron
# Setup cron to run every minute to print (you can add/update your cron here)
RUN touch /var/log/cron-1.log
RUN (crontab -l ; echo "* * * * * echo testing cron.... >> /var/log/cron-1.log 2>&1") | crontab
# entrypoint.sh
RUN chmod +x entrypoint.sh
CMD ["bash","entrypoint.sh"]
entrypoint.sh
#!/bin/sh
service cron start & tail -f /var/log/cron-2.log
If any other service is also required to run along with cron then add that service with &
in the same command, for example: /opt/wildfly/bin/standalone.sh & service cron start & tail -f /var/log/cron-2.log
Once you will get into the docker container there you can see that testing cron....
will be getting printed every minute in file: /var/log/cron-1.log
I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Edit object data that is represented in Viewat at list's "position"
view = mAdapter.getView(position, view, parent);
}
});
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
function callMethod() {
//your logic should be here and make sure your logic code note returing function
return false;
}
</script>
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
The caller and the callee need to use the same convention at the point of invokation - that's the only way it could reliably work. Both the caller and the callee follow a predefined protocol - for example, who needs to clean up the stack. If conventions mismatch your program runs into undefined behavior - likely just crashes spectacularly.
This is only required per invokation site - the calling code itself can be a function with any calling convention.
You shouldn't notice any real difference in performance between those conventions. If that becomes a problem you usually need to make less calls - for example, change the algorithm.
Alternately, you could do a Text to Columns with space as the delimiter.
To install it on a Debian based system simply do
# Install latest JDK
sudo apt install default-jdk
# install unzip if not installed yet
sudo apt install unzip
# get latest sdk tools - link will change. go to https://developer.android.com/studio/#downloads to get the latest one
cd ~
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip
# unpack archive
unzip sdk-tools-linux-4333796.zip
rm sdk-tools-linux-4333796.zip
mkdir android-sdk
mv tools android-sdk/tools
Then add the Android SDK to your PATH, open ~/.bashrc
in editor and add the following lines into the file
# Export the Android SDK path
export ANDROID_HOME=$HOME/android-sdk
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
# Fixes sdkmanager error with java versions higher than java 8
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
Run
source ~/.bashrc
Show all available sdk packages
sdkmanager --list
Identify latest android platform (here it's 28) and run
sdkmanager "platform-tools" "platforms;android-28"
Now you have adb, fastboot and the latest sdk tools installed
String is a class in Java different from other programming languages. So as for every class the object declaration and initialization is
String st1 = new String();
or
String st2 = new String("Hello");
String st3 = new String("Hello");
Here, st1
, st2
and st3
are different objects.
That is:
st1 == st2 // false
st1 == st3 // false
st2 == st3 // false
Because st1
, st2
, st3
are referencing 3 different objects, and ==
checks for the equality in memory location, hence the result.
But:
st1.equals(st2) // false
st2.equals(st3) // true
Here .equals()
method checks for the content, and the content of st1 = ""
, st2 = "hello"
and st3 = "hello"
. Hence the result.
And in the case of the String declaration
String st = "hello";
Here, intern()
method of String
class is called, and checks if "hello"
is in intern pool, and if not, it is added to intern pool, and if "hello" exist in intern pool, then st
will point to the memory of the existing "hello"
.
So in case of:
String st3 = "hello";
String st4 = "hello";
Here:
st3 == st4 // true
Because st3
and st4
pointing to same memory address.
Also:
st3.equals(st4); // true as usual
With ES6 you can now do it like this
Example Codepen URl to load
const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>';
A function component to load Iframe
function Iframe(props) {
return (<div dangerouslySetInnerHTML={ {__html: props.iframe?props.iframe:""}} />);
}
Usage:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<h1>Iframe Demo</h1>
<Iframe iframe={iframe} />,
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Edit on CodeSandbox:
Actually I work on project compatible python 2.6, 2.7 and 3.4 and I have to create IDs from free user entries.
Thanks to you, I have created this function that works wonders.
import re
import unicodedata
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
try:
text = unicode(text, 'utf-8')
except (TypeError, NameError): # unicode is a default on python 3
pass
text = unicodedata.normalize('NFD', text)
text = text.encode('ascii', 'ignore')
text = text.decode("utf-8")
return str(text)
def text_to_id(text):
"""
Convert input text to id.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
text = strip_accents(text.lower())
text = re.sub('[ ]+', '_', text)
text = re.sub('[^0-9a-zA-Z_-]', '', text)
return text
result:
text_to_id("Montréal, über, 12.89, Mère, Françoise, noël, 889")
>>> 'montreal_uber_1289_mere_francoise_noel_889'
public interface IService {
String BASE_URL = "https://api.demo.com/";
@GET("Login") //i.e https://api.demo.com/Search?
Call<Products> getUserDetails(@Query("email") String emailID, @Query("password") String password)
}
It will be called this way. Considering you did the rest of the code already.
Call<Results> call = service.getUserDetails("[email protected]", "Password@123");
For example when a query is returned, it will look like this.
https://api.demo.com/[email protected]&password=Password@123
Another method is to use the pad
keyword from plt.subplots_adjust()
, which also accepts negative values:
import matplotlib.pyplot as plt
ax = [plt.subplot(2,2,i+1) for i in range(4)]
for a in ax:
a.set_xticklabels([])
a.set_yticklabels([])
plt.subplots_adjust(pad=-5.0)
Additionally, to remove the white at the outer fringe of all subplots (i.e. the canvas), always save with plt.savefig(fname, bbox_inches="tight")
.
Visual Studio's search in folders is by far the fastest I've found.
I believe it intelligently searches only text (non-binary) files, and subsequent searches in the same folder are extremely fast, unlike with the other tools (likely the text files fit in the windows disk cache).
VS2010 on a regular hard drive, no SSD, takes 1 minute to search a 20GB folder with 26k files, source code and binaries mixed up. 15k files are searched - the rest are likely skipped due to being binary files. Subsequent searches in the same folder are on the order of seconds (until stuff gets evicted form the cache).
The next closest I've found for the same folder was grepWin. Around 3 minutes. I excluded files larger than 2000KB (default). The "Include binary files" setting seems to do nothing in terms of speeding up the search, it looks like binary files are still touched (bug?), but they don't show up in the search results. Subsequent searches all take the same 3 minutes - can't take advantage of hard drive cache. If I restrict to files smaller than 200k, the initial search is 2.5min and subsequent searches are on the order of seconds, about as fast as VS - in the cache.
Agent Ransack and FileSeek are both very slow on that folder, around 20min, due to searching through everything, including giant multi-gigabyte binary files. They search at about 10-20MB per second according to Resource Monitor.
UPDATE: Agent Ransack can be set to search files of certain sizes, and using the <200KB cutoff it's 1:15min for a fresh search and 5s for subsequent searches. Faster than grepWin and as fast as VS overall. It's actually pretty nice if you want to keep several searches in tabs and you don't want to pollute the VS recently searched folders list, and you want to keep the ability to search binaries, which VS doesn't seem to wanna do. Agent Ransack also creates an explorer context menu entry, so it's easy to launch from a folder. Same as grepWin but nicer UI and faster.
My new search setup is Agent Ransack for contents and Everything for file names (awesome tool, instant results!).
The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.
You can load it using var fs = require('fs');
fs.readFile('./content.json', (err, data) => {
if (err)
console.log(err);
else {
var json = JSON.parse(data);
//your code using json object
}
})
var json = JSON.parse(fs.readFileSync('./content.json').toString());
Great Answer by Jon.
I'm lazy though and I hate typing, so I created a simple cut and paste example for all the other people who are like me. Enjoy!
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> animals = new ArrayList<>();
animals.add("Lion");
animals.add("Tiger");
animals.add("Cat");
animals.add("Dog");
System.out.println(animals); // [Lion, Tiger, Cat, Dog]
// add() -> push(): Add items to the end of an array
animals.add("Elephant");
System.out.println(animals); // [Lion, Tiger, Cat, Dog, Elephant]
// remove() -> pop(): Remove an item from the end of an array
animals.remove(animals.size() - 1);
System.out.println(animals); // [Lion, Tiger, Cat, Dog]
// add(0,"xyz") -> unshift(): Add items to the beginning of an array
animals.add(0, "Penguin");
System.out.println(animals); // [Penguin, Lion, Tiger, Cat, Dog]
// remove(0) -> shift(): Remove an item from the beginning of an array
animals.remove(0);
System.out.println(animals); // [Lion, Tiger, Cat, Dog]
}
}
Take a look at this:
(reprinted from the expired blog page http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ based on the archived version at http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)
June 17th, 2008
With a view to writing a jQuery UI integrated with the offline functionality of Google Gears i’ve been toying with some code to poll for network connection status using jQuery.
The basic premise is very simple. We create an instance of a network detection object which will poll a URL at regular intervals. Should these HTTP requests fail we can assume that network connectivity has been lost, or the server is simply unreachable at the current time.
$.networkDetection = function(url,interval){
var url = url;
var interval = interval;
online = false;
this.StartPolling = function(){
this.StopPolling();
this.timer = setInterval(poll, interval);
};
this.StopPolling = function(){
clearInterval(this.timer);
};
this.setPollInterval= function(i) {
interval = i;
};
this.getOnlineStatus = function(){
return online;
};
function poll() {
$.ajax({
type: "POST",
url: url,
dataType: "text",
error: function(){
online = false;
$(document).trigger('status.networkDetection',[false]);
},
success: function(){
online = true;
$(document).trigger('status.networkDetection',[true]);
}
});
};
};
You can view the demo here. Set your browser to work offline and see what happens…. no, it’s not very exciting.
What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.
The demo code is more obtuse than it need to be. The network detection object publishes ’status ‘events to the document which actively listens for them and in turn publishes ‘notify’ events to all subscribers (more on those later). The reasoning behind this is that in a real world application there would probably be some more logic controlling when and how the ‘notify’ events are published.
$(document).bind("status.networkDetection", function(e, status){
// subscribers can be namespaced with multiple classes
subscribers = $('.subscriber.networkDetection');
// publish notify.networkDetection even to subscribers
subscribers.trigger("notify.networkDetection", [status])
/*
other logic based on network connectivity could go here
use google gears offline storage etc
maybe trigger some other events
*/
});
Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.
DOM elements which are to be subscribers are classed simply with “subscriber” and “networkDetection”. We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(“.subscriber.networkDetection”)
The #notifier
div which is part of the .subscriber.networkDetection
group of subscribers then has an anonymous function bound to it, effectively acting as a listener.
$('#notifier').bind("notify.networkDetection",function(e, online){
// the following simply demonstrates
notifier = $(this);
if(online){
if (!notifier.hasClass("online")){
$(this)
.addClass("online")
.removeClass("offline")
.text("ONLINE");
}
}else{
if (!notifier.hasClass("offline")){
$(this)
.addClass("offline")
.removeClass("online")
.text("OFFLINE");
}
};
});
So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page
Browser: https://jsfiddle.net/Limitlessisa/axt1Lqoz/
For mobile control: https://jsfiddle.net/Limitlessisa/axt1Lqoz/show/
$(document).ready(function() {_x000D_
$('body').on('click touch', '#share', function(e) {_x000D_
$('.share').fadeIn();_x000D_
});_x000D_
});_x000D_
_x000D_
// geri butonunu yakalama_x000D_
window.onhashchange = function(e) {_x000D_
var oldURL = e.oldURL.split('#')[1];_x000D_
var newURL = e.newURL.split('#')[1];_x000D_
_x000D_
if (oldURL == 'share') {_x000D_
$('.share').fadeOut();_x000D_
e.preventDefault();_x000D_
return false;_x000D_
}_x000D_
//console.log('old:'+oldURL+' new:'+newURL);_x000D_
}
_x000D_
.share{position:fixed; display:none; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,.8); color:white; padding:20px;
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Back Button Example</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body style="text-align:center; padding:0;">_x000D_
<a href="#share" id="share">Share</a>_x000D_
<div class="share" style="">_x000D_
<h1>Test Page</h1>_x000D_
<p> Back button press please for control.</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
def import_class(cl):
d = cl.rfind(".")
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt");
to open a stream to this file.
If you select two files in IntellijIdea and press Ctrl + D
then it will show you the diff. I use Ultimate and don't know if it will work with Community edition.
ENGINE=MEMORY
is not supported when table contains BLOB
/TEXT
columns
select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment
If you want JUST the source, and not an array with other information:
<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'thumbnail' ); ?>
<img src="<?php echo $url ?>" />
Idea is to wrap the element & unwrap the contents:
function renameElement($element,newElement){
$element.wrap("<"+newElement+">");
$newElement = $element.parent();
//Copying Attributes
$.each($element.prop('attributes'), function() {
$newElement.attr(this.name,this.value);
});
$element.contents().unwrap();
return $newElement;
}
Sample usage:
renameElement($('p'),'h5');
I found that when I created a scene via the three.js editor, I not only had to use the correct answer's code (above), to set up the renderer with an alpha value and the clear color, I had to go into the app.json file and find the "Scene" Object's "background" attribute and set it to:
"background: null"
.
The export from Three.js editor had it originally set to "background": 0
Instead of WorksheetFunction.Vlookup
, you can use Application.Vlookup
. If you set a Variant
equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum
in this case - with IsError
:
Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant
'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
MsgBox "no match"
Else
MsgBox cellNum
End If
End Sub
The Application
versions of the VLOOKUP
and MATCH
functions allow you to test for errors without raising the error. If you use the WorksheetFunction
version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application
functions, you can avoid that mess.
The above could be further simplified using the IIF
function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then
) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:
cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)
Consider those methods instead of On Error ...
statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo
and Resume
statements.
I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem
export class AppRoutingModule {
constructor(private router: Router) {
this.router.errorHandler = (error: any) => {
this.router.navigate(['404']); // or redirect to default route
}
}
}
Hope this will help you.
Just Adding Instance Properties
For example, all components can access a global appName
, you just write one line code:
Vue.prototype.$appName = 'My App'
$
isn't magic, it's a convention Vue uses for properties that are available to all instances.
Alternatively, you can write a plugin that includes all global methods or properties.
Adding a header with add_header
works fine with proxy pass, but if there is an existing header value in the response it will stack the values.
If you want to set or replace a header value (for example replace the Access-Control-Allow-Origin
header to match your client for allowing cross origin resource sharing) then you can do as follows:
# 1. hide the Access-Control-Allow-Origin from the server response
proxy_hide_header Access-Control-Allow-Origin;
# 2. add a new custom header that allows all * origins instead
add_header Access-Control-Allow-Origin *;
So proxy_hide_header
combined with add_header
gives you the power to set/replace response header values.
Similar answer can be found here on ServerFault
Note: proxy_set_header
is for setting request headers before the request is sent further, not for setting response headers (these configuration attributes for headers can be a bit confusing).
You can also create an extension:
var strArray = "Hello, playground".Letterize()
extension String {
func Letterize() -> [String] {
return map(self) { String($0) }
}
}
bundler update --source gem-name
will update the revision hash in Gemfile.lock which you can compare with the last commit hash of that git branch (master by default).
GIT
remote: [email protected]:organization/repo-name.git
revision: c810f4a29547b60ca8106b7a6b9a9532c392c954
can be found at github.com/organization/repo-name/commits/c810f4a2
(I used shorthand 8 character commit hash for the url)
It's obvious this creeps up due to many issues. For me, I was posting several OneTimeWorkRequest, each accessing a single room database, and inserting into a single table.
Making the DAO functions suspended, and calling them within the coroutine scope of the worker fixed this for me.
<section>
marks up a section, <div>
marks up a generic block with no associated semantics.
Brando ZWZ provides some great answers to handling this situation.
Re: Same navbar on multiple pages Aug 21, 2018 10:13 AM|LINK
As far as I know, there are multiple solution.
For example:
The Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar).
Then we could directly load it from the jquery without writing a lot of codes.
Like this:
<!--Navigation bar-->
<div id="nav-placeholder">
</div>
<script>
$(function(){
$("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->
Solution2:
You could use JavaScript code to generate the whole nav bar.
Like this:
Javascript code:
$(function () {
var bar = '';
bar += '<nav class="navbar navbar-default" role="navigation">';
bar += '<div class="container-fluid">';
bar += '<div>';
bar += '<ul class="nav navbar-nav">';
bar += '<li id="home"><a href="home.html">Home</a></li>';
bar += '<li id="index"><a href="index.html">Index</a></li>';
bar += '<li id="about"><a href="about.html">About</a></li>';
bar += '</ul>';
bar += '</div>';
bar += '</div>';
bar += '</nav>';
$("#main-bar").html(bar);
var id = getValueByName("id");
$("#" + id).addClass("active");
});
function getValueByName(name) {
var url = document.getElementById('nav-bar').getAttribute('src');
var param = new Array();
if (url.indexOf("?") != -1) {
var source = url.split("?")[1];
items = source.split("&");
for (var i = 0; i < items.length; i++) {
var item = items[i];
var parameters = item.split("=");
if (parameters[0] == "id") {
return parameters[1];
}
}
}
}
Html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="main-bar"></div>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<%--add this line to generate the nav bar--%>
<script src="../assets/js/nav-bar.js?id=index" id="nav-bar"></script>
</body>
</html>
https://forums.asp.net/t/2145711.aspx?Same+navbar+on+multiple+pages
You should use Terms Query
{
"query" : {
"terms" : {
"tags" : ["c", "d"]
}
}
}
First of all do not use list
as a variable name- that is a builtin function.
I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-
my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
That will create a list (a type of mutable array in python) called my_list
with the output of the np.getfromtext()
method in the first 2 indexes.
The first can be referenced with my_list[0]
and the second with my_list[1]
Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.
It's better to run the subquery once, in the FROM clause, to get the max date per control number.
SELECT n.*
FROM tblpm n
INNER JOIN (
SELECT control_number, MAX(date_updated) AS date_updated
FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated);
Gotcha!
You have to use RegisterStartupScript
instead of RegisterClientScriptBlock
Here My Example.
MasterPage:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
Inherits="prueba.MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function confirmCallBack() {
var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');
alert(a.value);
}
</script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
WebForm1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace prueba
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);
}
}
}
You can do it by making form and displaying it using ShowDialogBox....
Form.ShowDialog Method
- Shows the form as a modal dialog box.
Example:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
If you want to call functions on components from outside React, you can call them on the return value of renderComponent:
var Child = React.createClass({…});
var myChild = React.renderComponent(Child);
myChild.someMethod();
The only way to get a handle to a React Component instance outside of React is by storing the return value of React.renderComponent. Source.
There is no notion of method overloading in Python. But you can achieve a similar effect by specifying optional and keyword arguments
You need the Business Intelligence Studio ..I've checked and my version of VS2008 Pro doesn't have them installed.
Have a look at this link:
This should work for you
//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();
//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max();
(From here)
Got the same error too when connecting to GitHub with ssh as I move from one workplace to another. according to my situation, it seems that dns servers of different networks may get various ip address of github and the known_hosts file not identify it when changes happened. So change dns or switch back original network may work.
As mentioned in several other answers, mutation events have been deprecated, so you should use MutationObserver instead. Since nobody has given any details on that yet, here it goes...
The API for MutationObserver is fairly simple. It's not quite as simple as the mutation events, but it's still okay.
function callback(records) {_x000D_
records.forEach(function (record) {_x000D_
var list = record.addedNodes;_x000D_
var i = list.length - 1;_x000D_
_x000D_
for ( ; i > -1; i-- ) {_x000D_
if (list[i].nodeName === 'SELECT') {_x000D_
// Insert code here..._x000D_
console.log(list[i]);_x000D_
}_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
var observer = new MutationObserver(callback);_x000D_
_x000D_
var targetNode = document.body;_x000D_
_x000D_
observer.observe(targetNode, { childList: true, subtree: true });
_x000D_
<script>_x000D_
// For testing_x000D_
setTimeout(function() {_x000D_
var $el = document.createElement('select');_x000D_
document.body.appendChild($el);_x000D_
}, 500);_x000D_
</script>
_x000D_
Let's break that down.
var observer = new MutationObserver(callback);
This creates the observer. The observer isn't watching anything yet; this is just where the event listener gets attached.
observer.observe(targetNode, { childList: true, subtree: true });
This makes the observer start up. The first argument is the node that the observer will watch for changes on. The second argument is the options for what to watch for.
childList
means I want to watch for child elements being added or removed.subtree
is a modifier that extends childList
to watch for changes anywhere in this element's subtree (otherwise, it would just look at changes directly within targetNode
).The other two main options besides childList
are attributes
and characterData
, which mean about what they sound like. You must use one of those three.
function callback(records) {
records.forEach(function (record) {
Things get a little tricky inside the callback. The callback receives an array of MutationRecords. Each MutationRecord can describe several changes of one type (childList
, attributes
, or characterData
). Since I only told the observer to watch for childList
, I won't bother checking the type.
var list = record.addedNodes;
Right here I grab a NodeList of all the child nodes that were added. This will be empty for all the records where nodes aren't added (and there may be many such records).
From there on, I loop through the added nodes and find any that are <select>
elements.
Nothing really complex here.
...but you asked for jQuery. Fine.
(function($) {
var observers = [];
$.event.special.domNodeInserted = {
setup: function setup(data, namespaces) {
var observer = new MutationObserver(checkObservers);
observers.push([this, observer, []]);
},
teardown: function teardown(namespaces) {
var obs = getObserverData(this);
obs[1].disconnect();
observers = $.grep(observers, function(item) {
return item !== obs;
});
},
remove: function remove(handleObj) {
var obs = getObserverData(this);
obs[2] = obs[2].filter(function(event) {
return event[0] !== handleObj.selector && event[1] !== handleObj.handler;
});
},
add: function add(handleObj) {
var obs = getObserverData(this);
var opts = $.extend({}, {
childList: true,
subtree: true
}, handleObj.data);
obs[1].observe(this, opts);
obs[2].push([handleObj.selector, handleObj.handler]);
}
};
function getObserverData(element) {
var $el = $(element);
return $.grep(observers, function(item) {
return $el.is(item[0]);
})[0];
}
function checkObservers(records, observer) {
var obs = $.grep(observers, function(item) {
return item[1] === observer;
})[0];
var triggers = obs[2];
var changes = [];
records.forEach(function(record) {
if (record.type === 'attributes') {
if (changes.indexOf(record.target) === -1) {
changes.push(record.target);
}
return;
}
$(record.addedNodes).toArray().forEach(function(el) {
if (changes.indexOf(el) === -1) {
changes.push(el);
}
})
});
triggers.forEach(function checkTrigger(item) {
changes.forEach(function(el) {
var $el = $(el);
if ($el.is(item[0])) {
$el.trigger('domNodeInserted');
}
});
});
}
})(jQuery);
This creates a new event called domNodeInserted
, using the jQuery special events API. You can use it like so:
$(document).on("domNodeInserted", "select", function () {
$(this).combobox();
});
I would personally suggest looking for a class because some libraries will create select
elements for testing purposes.
Naturally, you can also use .off("domNodeInserted", ...)
or fine-tune the watching by passing in data like this:
$(document.body).on("domNodeInserted", "select.test", {
attributes: true,
subtree: false
}, function () {
$(this).combobox();
});
This would trigger checking for the appearance of a select.test
element whenever attributes changed for elements directly inside the body.
You can see it live below or on jsFiddle.
(function($) {_x000D_
$(document).on("domNodeInserted", "select", function() {_x000D_
console.log(this);_x000D_
//$(this).combobox();_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<script>_x000D_
// For testing_x000D_
setTimeout(function() {_x000D_
var $el = document.createElement('select');_x000D_
document.body.appendChild($el);_x000D_
}, 500);_x000D_
</script>_x000D_
_x000D_
<script>_x000D_
(function($) {_x000D_
_x000D_
var observers = [];_x000D_
_x000D_
$.event.special.domNodeInserted = {_x000D_
_x000D_
setup: function setup(data, namespaces) {_x000D_
var observer = new MutationObserver(checkObservers);_x000D_
_x000D_
observers.push([this, observer, []]);_x000D_
},_x000D_
_x000D_
teardown: function teardown(namespaces) {_x000D_
var obs = getObserverData(this);_x000D_
_x000D_
obs[1].disconnect();_x000D_
_x000D_
observers = $.grep(observers, function(item) {_x000D_
return item !== obs;_x000D_
});_x000D_
},_x000D_
_x000D_
remove: function remove(handleObj) {_x000D_
var obs = getObserverData(this);_x000D_
_x000D_
obs[2] = obs[2].filter(function(event) {_x000D_
return event[0] !== handleObj.selector && event[1] !== handleObj.handler;_x000D_
});_x000D_
},_x000D_
_x000D_
add: function add(handleObj) {_x000D_
var obs = getObserverData(this);_x000D_
_x000D_
var opts = $.extend({}, {_x000D_
childList: true,_x000D_
subtree: true_x000D_
}, handleObj.data);_x000D_
_x000D_
obs[1].observe(this, opts);_x000D_
_x000D_
obs[2].push([handleObj.selector, handleObj.handler]);_x000D_
}_x000D_
};_x000D_
_x000D_
function getObserverData(element) {_x000D_
var $el = $(element);_x000D_
_x000D_
return $.grep(observers, function(item) {_x000D_
return $el.is(item[0]);_x000D_
})[0];_x000D_
}_x000D_
_x000D_
function checkObservers(records, observer) {_x000D_
var obs = $.grep(observers, function(item) {_x000D_
return item[1] === observer;_x000D_
})[0];_x000D_
_x000D_
var triggers = obs[2];_x000D_
_x000D_
var changes = [];_x000D_
_x000D_
records.forEach(function(record) {_x000D_
if (record.type === 'attributes') {_x000D_
if (changes.indexOf(record.target) === -1) {_x000D_
changes.push(record.target);_x000D_
}_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
$(record.addedNodes).toArray().forEach(function(el) {_x000D_
if (changes.indexOf(el) === -1) {_x000D_
changes.push(el);_x000D_
}_x000D_
})_x000D_
});_x000D_
_x000D_
triggers.forEach(function checkTrigger(item) {_x000D_
changes.forEach(function(el) {_x000D_
var $el = $(el);_x000D_
_x000D_
if ($el.is(item[0])) {_x000D_
$el.trigger('domNodeInserted');_x000D_
}_x000D_
});_x000D_
});_x000D_
}_x000D_
_x000D_
})(jQuery);_x000D_
</script>
_x000D_
This jQuery code is a fairly basic implementation. It does not trigger in cases where modifications elsewhere make your selector valid.
For example, suppose your selector is .test select
and the document already has a <select>
. Adding the class test
to <body>
will make the selector valid, but because I only check record.target
and record.addedNodes
, the event would not fire. The change has to happen to the element you wish to select itself.
This could be avoided by querying for the selector whenever mutations happen. I chose not to do that to avoid causing duplicate events for elements that had already been handled. Properly dealing with adjacent or general sibling combinators would make things even trickier.
For a more comprehensive solution, see https://github.com/pie6k/jquery.initialize, as mentioned in Damien Ó Ceallaigh's answer. However, the author of that library has announced that the library is old and suggests that you shouldn't use jQuery for this.
We faced the same issue and fixed it. Below is the reason and solution.
Problem
When the connection pool mechanism is used, the application server (in our case, it is JBOSS) creates connections according to the min-connection
parameter. If you have 10 applications running, and each has a min-connection
of 10, then a total of 100 sessions will be created in the database. Also, in every database, there is a max-session
parameter, if your total number of connections crosses that border, then you will get Got minus one from a read call
.
FYI: Use the query below to see your total number of sessions:
SELECT username, count(username) FROM v$session
WHERE username IS NOT NULL group by username
Solution: With the help of our DBA, we increased that max-session
parameter, so that all our application min-connection
can accommodate.
Query with sub query in Laravel
$resortData = DB::table('resort')
->leftJoin('country', 'resort.country', '=', 'country.id')
->leftJoin('states', 'resort.state', '=', 'states.id')
->leftJoin('city', 'resort.city', '=', 'city.id')
->select('resort.*', 'country.name as country_name', 'states.name as state_name','city.name as city_name', DB::raw("(SELECT GROUP_CONCAT(amenities.name) from resort_amenities LEFT JOIN amenities on amenities.id= resort_amenities.amenities_id WHERE resort_amenities.resort_id=resort.id) as amenities_name"))->groupBy('resort.id')
->orderBy('resort.id', 'DESC')
->get();
Public Function RandomNumber(ByVal n As Integer) As Integer
'initialize random number generator
Dim r As New Random(System.DateTime.Now.Millisecond)
Return r.Next(1, n)
End Function
From Eclipsepedia on how to set a conditional breakpoint:
First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as
list.size()==0
. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.
As an improvement to @Akash Desarda 's answer, you could do
import argparse
from distutils.util import strtobool
parser = argparse.ArgumentParser()
parser.add_argument("--foo",
type=lambda x:bool(strtobool(x)),
nargs='?', const=True, default=False)
args = parser.parse_args()
print(args.foo)
And it supports python test.py --foo
(base) [costa@costa-pc code]$ python test.py
False
(base) [costa@costa-pc code]$ python test.py --foo
True
(base) [costa@costa-pc code]$ python test.py --foo True
True
(base) [costa@costa-pc code]$ python test.py --foo False
False
You're passing the result of somedict.keys()
to the function. In Python 3, dict.keys
doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.
To fix the problem, use list(somedict.keys())
to collect the keys, and work with that.
This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror
condition image URL, e.g. you might want to programatically set the url
parameter in CSS.
The trick is that image loading is asynchronous by nature so the onerror
doesn't happen sunchronously, i.e. if you call returnPhotoURL
it immediately returns undefined
bcs the asynchronous method of loading/handling the image load just began.
So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:
returnPhotoURL().then(function(value){
doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
});
function returnPhotoURL(){
return new Promise(function(resolve, reject){
var img = new Image();
//if the user does not have a photoURL let's try and get one from gravatar
if (!firebase.auth().currentUser.photoURL) {
//first we have to see if user han an email
if(firebase.auth().currentUser.email){
//set sign-in-button background image to gravatar url
img.addEventListener('load', function() {
resolve (getGravatar(firebase.auth().currentUser.email, 48));
}, false);
img.addEventListener('error', function() {
resolve ('//rack.pub/media/fallbackImage.png');
}, false);
img.src = getGravatar(firebase.auth().currentUser.email, 48);
} else {
resolve ('//rack.pub/media/fallbackImage.png');
}
} else {
img.addEventListener('load', function() {
resolve (firebase.auth().currentUser.photoURL);
}, false);
img.addEventListener('error', function() {
resolve ('https://rack.pub/media/fallbackImage.png');
}, false);
img.src = firebase.auth().currentUser.photoURL;
}
});
}
you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual
Here's two newer potential solutions. Apparently, you can use jqtouch or pastrykit to disable scrolling. However, I haven't got these to work. You might be more competent.
When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport
tag:
<binding name="MyServiceBinding">
<security defaultAlgorithmSuite="Basic256Rsa15"
authenticationMode="MutualCertificate" requireDerivedKeys="true"
securityHeaderLayout="Lax" includeTimestamp="true"
messageProtectionOrder="SignBeforeEncrypt"
messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
requireSignatureConfirmation="false">
<localClientSettings detectReplays="true" />
<localServiceSettings detectReplays="true" />
<secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
</security>
<textMessageEncoding messageVersion="Soap11WSAddressing10">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="4096"
maxNameTableCharCount="16384"/>
</textMessageEncoding>
<httpsTransport maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
requireClientCertificate="false" />
</binding>
The values for the float data type come from having 32 bits in total to represent the number which are allocated like this:
1 bit: sign bit
8 bits: exponent p
23 bits: mantissa
The exponent is stored as p + BIAS
where the BIAS is 127, the mantissa has 23 bits and a 24th hidden bit that is assumed 1. This hidden bit is the most significant bit (MSB) of the mantissa and the exponent must be chosen so that it is 1.
This means that the smallest number you can represent is 01000000000000000000000000000000
which is 1x2^-126 = 1.17549435E-38
.
The largest value is 011111111111111111111111111111111
, the mantissa is 2 * (1 - 1/65536) and the exponent is 127 which gives (1 - 1 / 65536) * 2 ^ 128 = 3.40277175E38
.
The same principles apply to double precision except the bits are:
1 bit: sign bit
11 bits: exponent bits
52 bits: mantissa bits
BIAS: 1023
So technically the limits come from the IEEE-754 standard for representing floating point numbers and the above is how those limits come about
NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];
or use
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
Just Go to
iOS Simulator -> Hardware -> Keyboard -> Uncheck the Connect Hardware Keyboard Option.
This will fix the issue.
Your MAC keyboard will not work after performing the above step, You have to use simulator keyboard.
Answer given by Abid Rahman K is not completely correct. I also tried it and found very helpful but got stuck.
This is how I copy image with a given mask.
x, y = np.where(mask!=0)
pts = zip(x, y)
# Assuming dst and src are of same sizes
for pt in pts:
dst[pt] = src[pt]
This is a bit slow but gives correct results.
EDIT:
Pythonic way.
idx = (mask!=0)
dst[idx] = src[idx]
Is that a faulty solution? (android java)
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String stringMD5 = bigInt.toString(16);
// Fill to 32 chars
stringMD5 = String.format("%32s", stringMD5).replace(' ', '0');
return stringMD5;
So basically it replaces spaces with 0.
The answers here, are way too complex. Here's something I've recently used:
<?php global $product; ?>
<img src="<?php echo wp_get_attachment_url( $product->get_image_id() ); ?>" />
Using wp_get_attachment_url()
to display the
ODBC works only for relational databases, it can't works with non-relational databases such as Ms Excel files. Where Olebd can do everything.
I put this question to the IETF HTTP WG. The comment from Roy Fielding (author of http/1.1 document in 1998) was that
"... an implementation would be broken to do anything other than to parse and discard that body if received"
RFC 7213 (HTTPbis) states:
"A payload within a GET request message has no defined semantics;"
It seems clear now that the intention was that semantic meaning on GET request bodies is prohibited, which means that the request body can't be used to affect the result.
There are proxies out there that will definitely break your request in various ways if you include a body on GET.
So in summary, don't do it.
Not an answer per se, but a guideline. Most of the time there is not much sense in declaring local T&&
variable (as you did with std::vector<int>&& rval_ref
). You will still have to std::move()
them to use in foo(T&&)
type methods. There is also the problem that was already mentioned that when you try to return such rval_ref
from function you will get the standard reference-to-destroyed-temporary-fiasco.
Most of the time I would go with following pattern:
// Declarations
A a(B&&, C&&);
B b();
C c();
auto ret = a(b(), c());
You don't hold any refs to returned temporary objects, thus you avoid (inexperienced) programmer's error who wish to use a moved object.
auto bRet = b();
auto cRet = c();
auto aRet = a(std::move(b), std::move(c));
// Either these just fail (assert/exception), or you won't get
// your expected results due to their clean state.
bRet.foo();
cRet.bar();
Obviously there are (although rather rare) cases where a function truly returns a T&&
which is a reference to a non-temporary object that you can move into your object.
Regarding RVO: these mechanisms generally work and compiler can nicely avoid copying, but in cases where the return path is not obvious (exceptions, if
conditionals determining the named object you will return, and probably couple others) rrefs are your saviors (even if potentially more expensive).
You can also use awk:
awk 'END {print NR,"lines"}' filename
Or
awk 'END {print NR}' filename
both seem to be working.
see fiddle: http://jsfiddle.net/maniator/PSxkS/
By default, tnsnames.ora is located in the $ORACLE_HOME/network/admin directory on UNIX operating systems and in the ORACLE_HOME\network\admin directory on Windows operating systems. tnsnames.ora can also be stored the following locations:
The directory specified by the TNS_ADMIN environment variable (or registry value)
On UNIX operating systems, the global configuration directory. For example, on the Solaris Operating System, this directory is /var/opt/oracle
If you have multiple ORACLE_HOMES, be aware of which one you are using, as the location of the tnsnames.ora file can vary from one ORACLE_HOME to the next.
For the person who mentioned the TWO_TASK environment variable, that is used to set a default database service name to connect to (which could be a database on another server). The service name you set TWO_TASK to is then looked up in the tnsnames.ora file when you connect.
Also a good example.....
struct point{int x,y;};
typedef struct point point_t;
typedef struct
{
struct point ne,se,sw,nw;
}rect_t;
rect_t temp;
int main()
{
//rotate
RotateRect(&temp);
return 0;
}
void RotateRect(rect_t *givenRect)
{
point_t temp_point;
/*Copy struct data from struct to struct within a struct*/
temp_point = givenRect->sw;
givenRect->sw = givenRect->se;
givenRect->se = givenRect->ne;
givenRect->ne = givenRect->nw;
givenRect->nw = temp_point;
}
To only find the first locations, use lapply()
with min()
:
my_string <- c("test1", "test1test1", "test1test1test1")
unlist(lapply(gregexpr(pattern = '1', my_string), min))
#> [1] 5 5 5
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(min) %>%
unlist()
#> [1] 5 5 5
To only find the last locations, use lapply()
with max()
:
unlist(lapply(gregexpr(pattern = '1', my_string), max))
#> [1] 5 10 15
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(max) %>%
unlist()
#> [1] 5 10 15
Why not use outline? it is what you want outline:1px solid red;
Just for completeness - it's worth noting that with Bootstrap 3, as per the docs, ensure the following structure in your page. It solved issues I was having with IE9 and v3.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- content -->
</body>
</html>
Had the same issue. It was a problem with udev rules. Tried a few of the rules mentioned above but didnot fix the issue. Found a set of rules here, https://github.com/M0Rf30/android-udev-rules. Followed the guide there and, voila, fixed.
If you are using a GUI and you are still getting the same problem. Just leave the size value empty, the primary key defaults the value to 11, you should be fine with this. Worked with Bitnami phpmyadmin.
Set the UINavigationBar's delegate, and then use:
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
//handle the action here
}
Try in your connection string to set MultipleActiveResultSets=true
.
This allow multitasking on database.
Server=yourserver ;AttachDbFilename=database;User Id=sa;Password=blah ;MultipleActiveResultSets=true;App=EntityFramework
That works for me ... whether your connection in app.config or you set it programmatically ... hope this helpful
Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.
In the below, @i will return 2727
DECLARE @s NVARCHAR(500)
DECLARE @i INT;
SET @s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC @i = sys.sp_executesql @s
SELECT @i AS 'Blah'
SSMS will show this Msg 2727, Level 11, State 1, Line 1 Cannot find index 'NonExistantStaticsName'.
Most commands/programs return a 0 on success and some other value, called errorlevel
, to signal an error.
You can check for this in you batch for example by:
call <THE_COMMAND_HERE>
if %ERRORLEVEL% == 0 goto :next
echo "Errors encountered during execution. Exited with status: %errorlevel%"
goto :endofscript
:next
echo "Doing the next thing"
:endofscript
echo "Script complete"
there is also another way to resolve this issue. lets say you have two tables Table1 and Table2. and it is required to fetch all entries of Table1 not referred/present in Table2 using Criteria query. So go ahead like this...
List list=new ArrayList();
Criteria cr=session.createCriteria(Table1.class);
cr.add(Restrictions.sqlRestriction("this_.id not in (select t2.t1_id from Table2 t2 )"));
.
.
. . . It will perform all the subquery function directly in SQL without including 1000 or more parameters in SQL converted by Hibernate framework. It worked for me. Note: You may need to change SQL portion as per your requirement.
You can set the format in aspx, just add the property "DateFormatString" in your BoundField.
DataFormatString="{0:dd/MM/yyyy hh:mm:ss}"
At the bottom of the Sublime window, you'll see something representing your tab/space setting.
You'll then get a dropdown with a bunch of options. The options you care about are:
Apply your desired setting to the entire document.
Hope this helps.
Client send some messages need be compressed, server (kafka) decompress the string meesage
Below is my sample:
compress:
public static String compress(String str, String inEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(inEncoding));
gzip.close();
return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
decompress:
public static String decompress(String str, String outEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
String decode = URLDecoder.decode(str, "UTF-8");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(decode.getBytes("ISO-8859-1"));
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString(outEncoding);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
pll_current_language
Returns the current language
Usage:
pll_current_language( $value );
- $value => (optional) either name or locale or slug, defaults to slug
returns either the full name, or the WordPress locale (just as the WordPress core function ‘get_locale’ or the slug ( 2-letters code) of the current language.
const express = require('express');
var app = express();
app.listen(Port Number, "Your IP Address");
// e.g.
app.listen(3000, "192.183.190.3");
You can get your IP Address by typing ipconfig
in cmd if your Windows user else you can use ifconfig
.
If you exclude the unsigned types, there is an ordered hierarchy: signed char, short, int, long, long long, float, double, long double. First, anything coming before int in the above will be converted to int. Then, in a binary operation, the lower ranked type will be converted to the higher, and the results will be the type of the higher. (You'll note that, from the hierarchy, anytime a floating point and an integral type are involved, the integral type will be converted to the floating point type.)
Unsigned complicates things a bit: it perturbs the ranking, and parts of the ranking become implementation defined. Because of this, it's best to not mix signed and unsigned in the same expression. (Most C++ experts seem to avoid unsigned unless bitwise operations are involved. That is, at least, what Stroustrup recommends.)
I am sure there must be a way of doing this without writing my own CSS, its crazy I have to overwrite the margin and padding, all I wanted was a 2 column grid.
.row-offset-0 {
margin-left: 0;
margin-right: 0;
}
.row-offset-0 > * {
padding-left: 0;
padding-right: 0;
}
Just having final
will have the intended effect.
final int x = 5;
...
x = 10; // this will cause a compilation error because x is final
Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x
Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..
Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)
But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.
Checked solution is not accurate, sometimes mouse-right-click triggers right-swipe. after trying different plugins for swipe i found an almost perfect one.
i said "almost" because this plugin does not support future elements. so we would have to reinitialize the swipe call when the swipe content is changed by ajax or something. this plugin have lots of options to play with touch events like multi-finger-touch,pinch etc.
http://labs.rampinteractive.co.uk/touchSwipe/demos/index.html
$("#myCarousel").swipe( {
swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
if(direction=='left'){
$(this).carousel('next');
}else if(direction=='right'){
$(this).carousel('prev');
}
}
});
function addSwipeTo(selector){
$(selector).swipe("destroy");
$(selector).swipe( {
swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
if(direction=='left'){
$(this).carousel('next');
}else if(direction=='right'){
$(this).carousel('prev');
}
}
});
}
addSwipeTo("#myCarousel");
I guess the problem is your js runs before the html is loaded.
If you are using jquery, you can use the document ready function to wrap your code:
$(function() {
var Grid = function(width, height) {
// codes...
}
});
Or simply put your js after the <canvas>
.
You may also write it in two statements if it mostly is true use:
a = 5
a = 10 if false
Or use a switch statement if you need more possibilities:
a = switch x
when true then 5
when false then 10
With a boolean it may be oversized but i find it very readable.
Useful for the case where you want to make sure 2 numbers are the same 'up to precision', no need to specify the tolerance:
Find minimum precision of the 2 numbers
Round both of them to minimum precision and compare
def isclose(a,b):
astr=str(a)
aprec=len(astr.split('.')[1]) if '.' in astr else 0
bstr=str(b)
bprec=len(bstr.split('.')[1]) if '.' in bstr else 0
prec=min(aprec,bprec)
return round(a,prec)==round(b,prec)
As written, only works for numbers without the 'e' in their string representation ( meaning 0.9999999999995e-4 < number <= 0.9999999999995e11 )
Example:
>>> isclose(10.0,10.049)
True
>>> isclose(10.0,10.05)
False
I ended creating my own functions:
@Component({
selector: 'cookie-consent',
template: cookieconsent_html,
styles: [cookieconsent_css]
})
export class CookieConsent {
private isConsented: boolean = false;
constructor() {
this.isConsented = this.getCookie(COOKIE_CONSENT) === '1';
}
private getCookie(name: string) {
let ca: Array<string> = document.cookie.split(';');
let caLen: number = ca.length;
let cookieName = `${name}=`;
let c: string;
for (let i: number = 0; i < caLen; i += 1) {
c = ca[i].replace(/^\s+/g, '');
if (c.indexOf(cookieName) == 0) {
return c.substring(cookieName.length, c.length);
}
}
return '';
}
private deleteCookie(name) {
this.setCookie(name, '', -1);
}
private setCookie(name: string, value: string, expireDays: number, path: string = '') {
let d:Date = new Date();
d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
let expires:string = `expires=${d.toUTCString()}`;
let cpath:string = path ? `; path=${path}` : '';
document.cookie = `${name}=${value}; ${expires}${cpath}`;
}
private consent(isConsent: boolean, e: any) {
if (!isConsent) {
return this.isConsented;
} else if (isConsent) {
this.setCookie(COOKIE_CONSENT, '1', COOKIE_CONSENT_EXPIRE_DAYS);
this.isConsented = true;
e.preventDefault();
}
}
}
If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.
<input id="addButton" type="button" value="Add" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#addButton').click(function()
{
showDialog('#addPerson');
});
});
</script>
If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:
<asp:Button ID="buttonAdd" runat="server" Text="Add" />
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
$('#<%= buttonAdd.ClientID %>').click(function(e)
{
showDialog('#addPerson');
if(/*Some Condition Is Not Met*/)
return false;
});
});
</script>
I had this issue with MacOS High Sierria.
You can set up locale as well as language to UTF-8 format using below command :
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
Now in order to check whether locale environment is updated use below command :
Locale
Centos 6.8
this work like charm for me
$yum -y install libcurl libcurl-devel
$rstudio-server verify-installation
HTML
<form id="contactform"></form>
JavaScript
var $contactform = $('#contactform')
$($contactform).find("input[type=text] , textarea ").each(function(){
$(this).val('');
});
Simple and short function to clear all fields
If this issue is Eclipse-related:
Try adding the project to your class path.
See the below image:
This method worked for me.
I happened to encounter a similar kind of issue after setting up local internal JFrog Docker Private Registry on Amazon Linux.
THE followings I did to solve the issue:
Added "--insecure-registry xx.xx.xx.xx:8081" by modifying the OPTIONS variable in the /etc/sysconfig/docker file:
OPTIONS="--default-ulimit nofile=1024:40961 --insecure-registry hostname:8081"
Then restarted the docker.
I was then able to login to the local docker registry using:
docker login -u admin -p password hostname:8081
On Windows, if the debug.keystore file is not in the location (C:\Users\username\.android), the debug.keystore file may also be found in the location where you have installed Android Studio.
From MDSN article, Controlling Transactions (Database Engine).
If a run-time statement error (such as a constraint violation) occurs in a batch, the default behavior in the Database Engine is to roll back only the statement that generated the error. You can change this behavior using the SET XACT_ABORT statement. After SET XACT_ABORT ON is executed, any run-time statement error causes an automatic rollback of the current transaction. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. For more information, see SET XACT_ABORT (Transact-SQL).
In your case it will rollback the complete transaction when any of inserts fail.
In case you develop applications for Android you should try out the TimingLogger
class.
Take a look at these articles describing the usage of the TimingLogger
helper class:
See more at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html
It's now 2019, I think the most efficient way to do it is:
df['truncate_date'] = df['timestamp'].dt.floor('d')
You can try out wsdl validator http://docs.wso2.org/wiki/display/ESB451/WSDL+Validator
You must feed the DOMDocument a version of your HTML with a header that make sense. Just like HTML5.
$profile ='<?xml version="1.0" encoding="'.$_encoding.'"?>'. $html;
maybe is a good idea to keep your html as valid as you can, so you don't get into issues when you'll start query... around :-) and stay away from htmlentities
!!!! That's an an necessary back and forth wasting resources.
keep your code insane!!!!
You are not adding the object to the session, instead you are adding it to the request.
What you need is:
HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);
In Servlets you have 4 scopes where you can store data.
Make sure you understand these. For more look here
When you want to remove one xxx.java file from SVN: