Bill the user: "Hey Jimmy, show me that report"
Jimmy the SP: "Hey, I'm not sure who you are yet. We have a process here so you go get yourself verified with Bob the IdP first. I trust him."
Bob the IdP: "I see Jimmy sent you here. Please give me your credentials."
Bill the user: "Hi I'm Bill. Here are my credentials."
Bob the IdP: "Hi Bill. Looks like you check out."
Bob the IdP: "Hey Jimmy. This guy Bill checks out and here's some additional information about him. You do whatever you want from here."
Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."
Bill the user: "Hey Bob. I want to go to Jimmy's place. Security is tight over there."
Bob the IdP: "Hey Jimmy. I trust Bill. He checks out and here's some additional information about him. You do whatever you want from here."
Jimmy the SP: "Ok cool. Looks like Bill is also in our list of known guests. I'll let Bill in."
I go into more detail here, but still keeping things simple: https://jorgecolonconsulting.com/saml-sso-in-simple-terms/.
Suppose we have table the table 'Student' with 2 columns:
student_id int
student_name varchar
Records:
+------------+---------------------+
| student_id | student_name |
+------------+---------------------+
| 101 | usman |
| 101 | usman |
| 101 | usman |
| 102 | usmanyaqoob |
| 103 | muhammadusmanyaqoob |
| 103 | muhammadusmanyaqoob |
+------------+---------------------+
Now we want to see duplicate records Use this query:
select student_name,student_id ,count(*) c from student group by student_id,student_name having c>1;
+---------------------+------------+---+
| student_name | student_id | c |
+---------------------+------------+---+
| usman | 101 | 3 |
| muhammadusmanyaqoob | 103 | 2 |
+---------------------+------------+---+
One way is to make the classes use a static initializers... I don't think these are inherited (it won't work if they are):
public class Dog extends Animal{
static
{
Animal a = new Dog();
//add a to the List
}
It requires you to add this code to all of the classes involved. But it avoids having a big ugly loop somewhere, testing every class searching for children of Animal.
Apart from purchasing protection, you (or your developers) can learn to copy-protect.
These are ideas:
At first, try to write a program that writes itself to console. That's a famous problem. Primary purpose of this task is to practice writing self-referencing code.
Second, you need to develop a technology that will rewrite some code in a way dependable on other methods' CIL.
You may write a virtual machine (yet in .NET). And put some code in there. Ultimately, the virtual machine runs another virtual machine which runs the code. That's for a part of rarely-called functions for not to slow the performance too much.
Rewrite some logic into C++/CLI, and mix managed code with unmanaged. This will harden the disassembling. In this case, do not forget to provide x64 binaries too.
What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.
The original information bootstraps the later use of the DHT.
Steps to install curl in windows
Install cURL on Windows
There are 4 steps to follow to get cURL installed on Windows.
Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate
Step One: Install Visual C++ 2008 Redistributables
From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)
Step Two: Install Win(32/64) OpenSSL v1.0.0k Light
From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light
Step Three: Install cURL
Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html
Copy curl.exe to C:\Windows\System32
Step Four: Install Recent Certificates
Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt
If you have already installed curl
or after doing the above steps, add the directory where it's installed to the windows path:
1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt
If you are using Visual S2019, Create a new local branch as shown in following, and then push the changes to the repo.
Unfortunately I found solutions presented by @dualed have various flaws.
Using substr($sapi_type, 0, 3) == 'cgi'
is not enogh to detect fast CGI. When using PHP-FPM FastCGI Process Manager, php_sapi_name()
returns fpm not cgi
Fasctcgi and php-fpm expose another bug mentioned by @Josh - using header('X-PHP-Response-Code: 404', true, 404);
does work properly under PHP-FPM (FastCGI)
header("HTTP/1.1 404 Not Found");
may fail when the protocol is not HTTP/1.1 (i.e. 'HTTP/1.0'). Current protocol must be detected using $_SERVER['SERVER_PROTOCOL']
(available since PHP 4.1.0
There are at least 2 cases when calling http_response_code()
result in unexpected behaviour:
For your reference here there is the full list of HTTP response status codes (this list includes codes from IETF internet standards as well as other IETF RFCs. Many of them are NOT currently supported by PHP http_response_code function): http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
You can easily test this bug by calling:
http_response_code(521);
The server will send "500 Internal Server Error" HTTP response code resulting in unexpected errors if you have for example a custom client application calling your server and expecting some additional HTTP codes.
My solution (for all PHP versions since 4.1.0):
$httpStatusCode = 521;
$httpStatusMsg = 'Web server is down';
$phpSapiName = substr(php_sapi_name(), 0, 3);
if ($phpSapiName == 'cgi' || $phpSapiName == 'fpm') {
header('Status: '.$httpStatusCode.' '.$httpStatusMsg);
} else {
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg);
}
Conclusion
http_response_code() implementation does not support all HTTP response codes and may overwrite the specified HTTP response code with another one from the same group.
The new http_response_code() function does not solve all the problems involved but make things worst introducing new bugs.
The "compatibility" solution offered by @dualed does not work as expected, at least under PHP-FPM.
The other solutions offered by @dualed also have various bugs. Fast CGI detection does not handle PHP-FPM. Current protocol must be detected.
Any tests and comments are appreciated.
The systemd
way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|
You might be able to do something inline like
ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'
or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here
in an ExecStartPost
Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.
(May want to increase TimeoutStartSec from the default 90s as well)
Beginning PowerShell 5.0 New-Item
, Remove-Item
, and Get-ChildItem
have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item
accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.
New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"
Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.
Anyway if you want to create a Run As Administrator shortcut using Powershell you can use
$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)
If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.
$(document).ready(function()
{
changeColor = $(.active).css("color","any color");
if($(".classname").hasClass('active')) {
$(this).eq(changeColor);
}
});
I used killall -9 rails
like Sri suggested and it didn't work. I adjusted the command to killall -9 ruby
and the server closed immediately.
Tl;dr: killall -9 ruby
In Windows, my git was located at
C:\Users\<username>\AppData\Local\Programs\Git\bin\git.exe
If you simply need to view the table and run queries on it you can use this third party sdf viewer. It is a lightweight viewer that has all the basic functionalities and is ready to use after install.
and ofcourse, its Free.
Using Regex:
import re
strip_unicode = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)")
print strip_unicode.sub('', u'6Â 918Â 417Â 712')
First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.
Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.
There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":
REPLACE(CAST(height as varchar(31)),'.00','')
EDIT:
This script works:
DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');
Whenever an UICommand
component (<h:commandXxx>
, <p:commandXxx>
, etc) fails to invoke the associated action method, or an UIInput
component (<h:inputXxx>
, <p:inputXxxx>
, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per Exception handling in JSF ajax requests, nor when you set below context parameter in web.xml
,
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the Console tab), then work through below list of possible causes.
UICommand
and UIInput
components must be placed inside an UIForm
component, e.g. <h:form>
(and thus not plain HTML <form>
), otherwise nothing can be sent to the server. UICommand
components must also not have type="button"
attribute, otherwise it will be a dead button which is only useful for JavaScript onclick
. See also How to send form input values and invoke a method in JSF bean and <h:commandButton> does not initiate a postback.
You cannot nest multiple UIForm
components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use UIForm
components in parallel, but they won't process each other during submit. You should also watch out with "God Form" antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?.
No UIInput
value validation/conversion error should have occurred. You can use <h:messages>
to show any messages which are not shown by any input-specific <h:message>
components. Don't forget to include the id
of <h:messages>
in the <f:ajax render>
, if any, so that it will be updated as well on ajax requests. See also h:messages does not display messages when p:commandButton is pressed.
If UICommand
or UIInput
components are placed inside an iterating component like <h:dataTable>
, <ui:repeat>
, etc, then you need to ensure that exactly the same value
of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in @PostConstruct
of the bean (and thus not in a getter method!) should fix it. See also How and when should I load the model from database for h:dataTable.
If UICommand
or UIInput
components are included by a dynamic source such as <ui:include src="#{bean.include}">
, then you need to ensure that exactly the same #{bean.include}
value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in @PostConstruct
of the bean (and thus not in a getter method!) should fix it. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).
The rendered
attribute of the component and all of its parents and the test
attribute of any parent <c:if>
/<c:when>
should not evaluate to false
during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a @ViewScoped
bean or making sure that you're properly preinitializing the condition in @PostConstruct
of a @RequestScoped
bean should fix it. The same applies to the disabled
and readonly
attributes of the component, which should not evaluate to true
during apply request values phase. See also JSF CommandButton action not invoked, Form submit in conditionally rendered component is not processed, h:commandButton is not working once I wrap it in a <h:panelGroup rendered> and Force JSF to process, validate and update readonly/disabled input components anyway
The onclick
attribute of the UICommand
component and the onsubmit
attribute of the UIForm
component should not return false
or cause a JavaScript error. There should in case of <h:commandLink>
or <f:ajax>
also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors.
If you're using Ajax via JSF 2.x <f:ajax>
or e.g. PrimeFaces <p:commandXxx>
, make sure that you have a <h:head>
in the master template instead of the <head>
. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like "mojarra is not defined" or "PrimeFaces is not defined" in browser's JS console. See also h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat.
If you're using Ajax, and the submitted values end up being null
, then make sure that the UIInput
and UICommand
components of interest are covered by the <f:ajax execute>
or e.g. <p:commandXxx process>
, otherwise they won't be executed/processed. See also Submitted form values not updated in model when adding <f:ajax> to <h:commandButton> and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.
If the submitted values still end up being null
, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to @Dependent
which effectively recreates the bean on every single evaluation of the EL expression. See also @SessionScoped bean looses scope and gets recreated all the time, fields become null and What is the default Managed Bean Scope in a JSF 2 application?
If a parent of the <h:form>
with the UICommand
button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as JSF spec issue 790 and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <h:form>
in the render
of the <f:ajax>
. See also h:commandButton/h:commandLink does not work on first click, works only on second click.
If the <h:form>
has enctype="multipart/form-data"
set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the FacesServlet
will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <t:inputFileUpload>
, check this answer and for PrimeFaces <p:fileUpload>
, check this answer. Or, if you're actually not uploading a file at all, then remove the attribute altogether.
Make sure that the ActionEvent
argument of actionListener
is an javax.faces.event.ActionEvent
and thus not java.awt.event.ActionEvent
, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use actionListener="#{bean.method}"
. If you don't want an argument in your method, use actionListener="#{bean.method()}"
. Or perhaps you actually want to use action
instead of actionListener
. See also Differences between action and actionListener.
Make sure that no PhaseListener
or any EventListener
in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling FacesContext#renderResponse()
or FacesContext#responseComplete()
.
Make sure that no Filter
or Servlet
in the same request-response chain has blocked the request fo the FacesServlet
somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also Spring Security 4 and PrimeFaces 5 AJAX request handling.
If you are using a PrimeFaces <p:dialog>
or a <p:overlayPanel>
, then make sure that they have their own <h:form>
. Because, these components are by default by JavaScript relocated to end of HTML <body>
. So, if they were originally sitting inside a <form>
, then they would now not anymore sit in a <form>
. See also p:commandbutton action doesn't work inside p:dialog
Bug in the framework. For example, RichFaces has a "conversion error" when using a rich:calendar
UI element with a defaultLabel
attribute (or, in some cases, a rich:placeholder
sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.
In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the Console tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <f:ajax>
enabled button while not having <h:head>
declared (as described in point 7 above).
Click the Network tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <h:inputText>
and a single <h:commandButton>
with <f:ajax execute="@form" render="@form">
.
(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)
In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of UICommand
component, that would be UICommand#queueEvent()
and in case of UIInput
component, that would be UIInput#validate()
. Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.
Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do. The if is telling the compiler that you have a question, and the question is the condition between parenthesis
if (condition) {
thingsToDo()..
}
the else part is an addition to this structure to tell the compiler what to do if the condition is false
if (condition) {
thingsToDo()..
} else {
thingsToDoInOtherCase()..
}
you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.
if (condition) {
thingsToDo()..
} else if (condition2) {
thingsToDoInTheSecondCase()..
}else {
thingsToDoInOtherCase()..
}
I solved this by going to the following url (while connected to google with the account I want to send mail from):
https://www.google.com/settings/security/lesssecureapps
There I enabled less secure apps.
Done
I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.
#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function
#define TRUE 1
#define FALSE 0
int main(void)
{
char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
int intTest;
printf("Give me an int: ");
do
{
scanf(" %s", n);
intTest = TRUE; // Sets the default for the integer test variable to TRUE
int i = 0, l = strlen(n);
if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
i++;
while (i < l)
{
if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
{
intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
break;
}
i++;
}
if (intTest == TRUE)
printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
else
printf("Retry: "); // Prints "Retry:" if tested FALSE
}
while (intTest == FALSE); // Continues to ask the user to input a valid integer value
return 0;
}
Yes it is possible. You need one ON for each join table.
LEFT JOIN ab
ON ab.sht = cd.sht
LEFT JOIN aa
ON aa.sht = cd.sht
Incidentally my personal formatting preference for complex SQL is described in http://bentilly.blogspot.com/2011/02/sql-formatting-style.html. If you're going to be writing a lot of this, it likely will help.
Use Invalidations to clear the cache, you can put the path to the files you want to clear, or simply use wild cards to clear everything.
This can also be done using the API! http://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateInvalidation.html
The AWS PHP SDK now has the methods but if you want to use something lighter check out this library: http://www.subchild.com/2010/09/17/amazon-cloudfront-php-invalidator/
user3305600's solution doesn't work as setting it to zero is the equivalent of Using the Origin Cache Headers.
Wrap the sections you want to hide in their own tbody and dynamically show/hide that.
Consider Following enum ::
public static enum MyEnum {
ValueA,
ValueB
}
For Passing ::
Intent mainIntent = new Intent(this,MyActivity.class);
mainIntent.putExtra("ENUM_CONST", MyEnum.ValueA);
this.startActivity(mainIntent);
To retrieve back from the intent/bundle/arguments ::
MyEnum myEnum = (MyEnum) intent.getSerializableExtra("ENUM_CONST");
As vartec says above, the HTTP spec does not define a limit, however many servers do by default. This means, practically speaking, the lower limit is 8K. For most servers, this limit applies to the sum of the request line and ALL header fields (so keep your cookies short).
It's worth noting that nginx uses the system page size by default, which is 4K on most systems. You can check with this tiny program:
pagesize.c:
#include <unistd.h>
#include <stdio.h>
int main() {
int pageSize = getpagesize();
printf("Page size on your system = %i bytes\n", pageSize);
return 0;
}
Compile with gcc -o pagesize pagesize.c
then run ./pagesize
. My ubuntu server from Linode dutifully informs me the answer is 4k.
The subset command is not necessary. Just use data frame indexing
studentdata[studentdata$Drink == 'water',]
Read the warning from ?subset
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like ‘[’, and in particular the non-standard evaluation of argument ‘subset’ can have unanticipated consequences.
Based on Joey's answer, I came up with an intended (by jQuery, read about 'queue') solution.
It somewhat follows the jQuery.animate() syntax - allows to be chained with other fx functions, supports 'slow' and other jQuery.fx.speeds as well as being fully jQuery. And will be handled the same way as animations, if you stop those.
jsFiddle test ground with more usages (like showing off .stop()), can be found here.
the core of the solution is:
$('<queue/>')_x000D_
.delay(100 /*ms*/)_x000D_
.queue( (next) => { $('#result').text('done.'); next(); } );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
the whole as a plugin, supporting usage of $.wait() and $(..).wait() :
// add wait as $.wait() standalone and $(elem).wait() for animation chaining_x000D_
(function($) {_x000D_
_x000D_
$.wait = function(duration, completeCallback, target) {_x000D_
$target = $(target || '<queue />');_x000D_
return $target.delay(duration).queue(function(next){completeCallback && completeCallback.call($target); next();});_x000D_
}_x000D_
_x000D_
$.fn.wait = function(duration, completeCallback) {_x000D_
return $.wait.call(this, duration, completeCallback, this);_x000D_
};_x000D_
_x000D_
})(jQuery);_x000D_
_x000D_
//TEST_x000D_
$(function() {_x000D_
_x000D_
// stand alone_x000D_
$.wait(1000, function() {_x000D_
$('#result')_x000D_
.append('...done');_x000D_
});_x000D_
_x000D_
// chained_x000D_
$('#result')_x000D_
.append('go...')_x000D_
.wait('slow', function() {_x000D_
$(this).append('after slow');_x000D_
})_x000D_
.css({color: 'green'});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
Note: since wait adds to the animation stack, $.css() is executed immediately - as it is supposed: expected jQuery behaviour.
@mani's Original answer is all you want, but if you'd also like to read it in official way, here's
https://router.vuejs.org/guide/essentials/history-mode.html#caveat
If you use bower.json file to specify your dependencies:
{
"dependencies": {
...
"photo-swipe": "[email protected]:dimsemenov/PhotoSwipe.git#v3.0.x",
#bower 1.4 (tested with that version) can read repositorios with uri format
"photo-swipe": "git://github.com/dimsemenov/PhotoSwipe.git#v3.0.x",
}
}
Just remember bower also searches for released versions and tags so you can point to almost everything, and can interprate basic query patterns like previous example. that will fetch latest minor update of version 3.0 (tested from bower 1.3.5)
Update, as the question description also mention using only a URL and no mention of a github repository.
Another example is to execute this command using the desired url, like:
bower install gmap3MarkerWithLabel=http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.0/src/markerwithlabel.js -S
that command downloads your js library puts in {your destination path}/gmap3MarkerWithLabel/index.js and automatically creates an entry in your bower.json file called gmap3MarkerWithLabel: "..." After that, you can only execute bower update gmap3MarkerWithLabel
if needed.
Funny thing if you do the process backwars (add manually the entry in bower.json, an then bower install entryName) it doesn't work, you get a
bower ENOTFOUND Package gmapV3MarkerWithLabel not found
It's because you're missing position:relative;
on #contentframe
<div id="contentframe" style="position:relative; top: 160px; left: 0px;">
position:absolute;
positions itself against the closest ancestor that has a position
that is not static
. Since the default is static
that is what was causing your issue.
I hope this answer is not considered too off-topic, but I had a similar issue where I was looking for a tool to parse only parts of a nested JSON
which is not that straightforward with the accepted solutions.
If you have a similar issue, it might be worth to check out JTokken
as described in this original post or in my answer to a similar question.
Attention: Please see Leo Dabus' answer for a proper implementation for Swift 4 and Swift 5.
The Substring
type was introduced in Swift 4 to make substrings
faster and more efficient by sharing storage with the original string, so that's what the subscript functions should return.
extension StringProtocol {
subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] }
subscript(range: Range<Int>) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex..<index(startIndex, offsetBy: range.count)]
}
subscript(range: ClosedRange<Int>) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex..<index(startIndex, offsetBy: range.count)]
}
subscript(range: PartialRangeFrom<Int>) -> SubSequence { self[index(startIndex, offsetBy: range.lowerBound)...] }
subscript(range: PartialRangeThrough<Int>) -> SubSequence { self[...index(startIndex, offsetBy: range.upperBound)] }
subscript(range: PartialRangeUpTo<Int>) -> SubSequence { self[..<index(startIndex, offsetBy: range.upperBound)] }
}
To convert the Substring
into a String
, you can simply
do String(string[0..2])
, but you should only do that if
you plan to keep the substring around. Otherwise, it's more
efficient to keep it a Substring
.
It would be great if someone could figure out a good way to merge
these two extensions into one. I tried extending Note: This answer has been already edited, it is properly implemented and now works for substrings as well. Just make sure to use a valid range to avoid crashing when subscripting your StringProtocol type. For subscripting with a range that won't crash with out of range values you can use this implementationStringProtocol
without success, because the index
method does not exist there.
The error message says "see the documentation comment for discussion". Apple provides the following explanation in the file UnavailableStringAPIs.swift:
Subscripting strings with integers is not available.
The concept of "the
i
th character in a string" has different interpretations in different libraries and system components. The correct interpretation should be selected according to the use case and the APIs involved, soString
cannot be subscripted with an integer.Swift provides several different ways to access the character data stored inside strings.
String.utf8
is a collection of UTF-8 code units in the string. Use this API when converting the string to UTF-8. Most POSIX APIs process strings in terms of UTF-8 code units.
String.utf16
is a collection of UTF-16 code units in string. Most Cocoa and Cocoa touch APIs process strings in terms of UTF-16 code units. For example, instances ofNSRange
used withNSAttributedString
andNSRegularExpression
store substring offsets and lengths in terms of UTF-16 code units.
String.unicodeScalars
is a collection of Unicode scalars. Use this API when you are performing low-level manipulation of character data.
String.characters
is a collection of extended grapheme clusters, which are an approximation of user-perceived characters.Note that when processing strings that contain human-readable text, character-by-character processing should be avoided to the largest extent possible. Use high-level locale-sensitive Unicode algorithms instead, for example,
String.localizedStandardCompare()
,String.localizedLowercaseString
,String.localizedStandardRangeOfString()
etc.
X returns (value +3), while Y returns (value*2)
Given a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56
.
Although functions are not limited in scope (which means that you can safely 'nest' function definitions), this particular example is prone to errors:
1) You can't call y()
before calling x()
, because function y()
won't actually be defined until x()
has executed once.
2) Calling x()
twice will cause PHP to redeclare function y()
, leading to a fatal error:
Fatal error: Cannot redeclare y()
The solution to both would be to split the code, so that both functions are declared independent of each other:
function x ($y)
{
return($y+3);
}
function y ($z)
{
return ($z*2);
}
This is also a lot more readable.
Lets put this baby to bed; tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:
Bottom line performance wise, use:
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
or
function isEmpty(obj) {
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }
return true;
}
Results under Node:
return (Object.keys(obj).length === 0)
for (var x in obj) { return false; }...
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }...
return ('{}' === JSON.stringify(obj))
Testing for Object with 0 keys 0.00018 0.000015 0.000015 0.000324
Testing for Object with 1 keys 0.000346 0.000458 0.000577 0.000657
Testing for Object with 2 keys 0.000375 0.00046 0.000565 0.000773
Testing for Object with 3 keys 0.000406 0.000476 0.000577 0.000904
Testing for Object with 4 keys 0.000435 0.000487 0.000589 0.001031
Testing for Object with 5 keys 0.000465 0.000501 0.000604 0.001148
Testing for Object with 6 keys 0.000492 0.000511 0.000618 0.001269
Testing for Object with 7 keys 0.000528 0.000527 0.000637 0.00138
Testing for Object with 8 keys 0.000565 0.000538 0.000647 0.00159
Testing for Object with 100 keys 0.003718 0.00243 0.002535 0.01381
Testing for Object with 1000 keys 0.0337 0.0193 0.0194 0.1337
Note that if your typical use case tests a non empty object with few keys, and rarely do you get to test empty objects or objects with 10 or more keys, consider the Object.keys(obj).length option. - otherwise go with the more generic (for... in...) implementation.
Note that Firefox seem to have a faster support for Object.keys(obj).length and Object.getOwnPropertyNames(obj).length, making it a better choice for any non empty Object, but still when it comes to empty objects, the (for...in...) is simply 10 times faster.
My 2 cents is that Object.keys(obj).length is a poor idea since it creates an object of keys just to count how many keys are inside, than destroys it! In order to create that object he needs to loop overt the keys... so why use it and not the (for... in...) option :)
var a = {};_x000D_
_x000D_
function timeit(func,count) {_x000D_
if (!count) count = 100000;_x000D_
var start = Date.now();_x000D_
for (i=0;i<count;i++) func();_x000D_
var end = Date.now();_x000D_
var duration = end - start;_x000D_
console.log(duration/count)_x000D_
}_x000D_
_x000D_
function isEmpty1() {_x000D_
return (Object.keys(a).length === 0)_x000D_
}_x000D_
function isEmpty2() {_x000D_
for (x in a) { return false; }_x000D_
return true;_x000D_
}_x000D_
function isEmpty3() {_x000D_
for (x in a) { if (a.hasOwnProperty(x)) return false; }_x000D_
return true;_x000D_
}_x000D_
function isEmpty4() {_x000D_
return ('{}' === JSON.stringify(a))_x000D_
}_x000D_
_x000D_
_x000D_
for (var j=0;j<10;j++) {_x000D_
a = {}_x000D_
for (var i=0;i<j;i++) a[i] = i;_x000D_
console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
timeit(isEmpty1);_x000D_
timeit(isEmpty2);_x000D_
timeit(isEmpty3);_x000D_
timeit(isEmpty4);_x000D_
}_x000D_
_x000D_
a = {}_x000D_
for (var i=0;i<100;i++) a[i] = i;_x000D_
console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
timeit(isEmpty1);_x000D_
timeit(isEmpty2);_x000D_
timeit(isEmpty3);_x000D_
timeit(isEmpty4, 10000);_x000D_
_x000D_
a = {}_x000D_
for (var i=0;i<1000;i++) a[i] = i;_x000D_
console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
timeit(isEmpty1,10000);_x000D_
timeit(isEmpty2,10000);_x000D_
timeit(isEmpty3,10000);_x000D_
timeit(isEmpty4,10000);
_x000D_
You could just use string division
require(roperators)
my_strings <- c('apple', banana', 'pear', 'melon')
my_strings %s/% 'a'
Which will give you 1, 3, 1, 0. You can also use string division with regular expressions and whole words.
I understand your problem boils down to how to call a SOAP (JAX-WS) web service from Java and get its returning object. In that case, you have two possible approaches:
wsimport
and use them; or
About the first approach (using wsimport
):
I see you already have the services' (entities or other) business classes, and it's a fact that the wsimport
generates a whole new set of classes (that are somehow duplicates of the classes you already have).
I'm afraid, though, in this scenario, you can only either:
wsimport
generated code to make it use your business classes (this is difficult and somehow not worth it - bear in mind everytime the WSDL changes, you'll have to regenerate and readapt the code); orwsimport
generated classes. (In this solution, you business code could "use" the generated classes as a service from another architectural layer.)About the second approach (create your custom SOAP client):
In order to implement the second approach, you'll have to:
java.net.HttpUrlconnection
(and some java.io
handling).Creating a SOAP client using classic java.net.HttpUrlConnection
is not that hard (but not that simple either), and you can find in this link a very good starting code.
I recommend you use the SAAJ framework:
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
https://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "https://www.w3schools.com/xml/tempconvert.asmx";
String soapAction = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "https://www.w3schools.com/xml/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="https://www.w3schools.com/xml/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:CelsiusToFahrenheit>
<myNamespace:Celsius>100</myNamespace:Celsius>
</myNamespace:CelsiusToFahrenheit>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("CelsiusToFahrenheit", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("Celsius", myNamespace);
soapBodyElem1.addTextNode("100");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
About using JAXB for serializing/deserializing, it is very easy to find information about it. You can start here: http://www.mkyong.com/java/jaxb-hello-world-example/.
Starting from Bootstrap v4 you can simply add the following to your div
class attribute: mt-2 (margin top 2)
<div class="mt-2 col-md-12">
This will have a two-point top margin!
</div>
More examples are given in the docs: Bootstrap v4 docs
Raymond Chen has a few ideas:
https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573
Quoted here in full because MSDN archives tend to be somewhat unreliable:
The easy way is to use the
%CD%
pseudo-variable. It expands to the current working directory.
set OLDDIR=%CD%
.. do stuff ..
chdir /d %OLDDIR% &rem restore current directory
(Of course, directory save/restore could more easily have been done with
pushd
/popd
, but that's not the point here.)The
%CD%
trick is handy even from the command line. For example, I often find myself in a directory where there's a file that I want to operate on but... oh, I need to chdir to some other directory in order to perform that operation.
set _=%CD%\curfile.txt
cd ... some other directory ...
somecommand args %_% args
(I like to use
%_%
as my scratch environment variable.)Type
SET /?
to see the other pseudo-variables provided by the command processor.
Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):
http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741
This covers the use of %~dp0:
If you want to know where the batch file lives:
%~dp0
%0
is the name of the batch file.~dp
gives you the drive and path of the specified argument.
You have to use builder.setSound
Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if(alarmSound == null){
alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
}
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
builder.setSound(alarmSound);
manager.notify(1, builder.build());
The accepted answer is correct but needs to be wary that this way imposes a 255 character limit. Better to reference an actual worksheet range object.
Finding the linked examples somewhat confusing, I worked out some code that demonstrates a working array insert into a test table (jkl_test). Here's the table:
create table jkl_test (id number(9));
Here is .Net code for a simple Console application that connects to Oracle using ODP.Net and inserts an array of 5 integers:
using Oracle.DataAccess.Client;
namespace OracleArrayInsertExample
{
class Program
{
static void Main(string[] args)
{
// Open a connection using ODP.Net
var connection = new OracleConnection("Data Source=YourDatabase; Password=YourPassword; User Id=YourUser");
connection.Open();
// Create an insert command
var command = connection.CreateCommand();
command.CommandText = "insert into jkl_test values (:ids)";
// Set up the parameter and provide values
var param = new OracleParameter("ids", OracleDbType.Int32);
param.Value = new int[] { 22, 55, 7, 33, 11 };
// This is critical to the process; in order for the command to
// recognize and bind arrays, an array bind count must be specified.
// Set it to the length of the array.
command.ArrayBindCount = 5;
command.Parameters.Add(param);
command.ExecuteNonQuery();
}
}
}
Timer.Elapsed
expects method of specific signature (with arguments object
and EventArgs
). If you want to use your PlayMusicEvent
method with additional argument evaluated during event registration, you can use lambda expression as an adapter:
myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));
Edit: you can also use shorter version:
myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);
For Swift 3.0
btn.titleLabel?.textAlignment = .center
You can also do it "the joiner way" by inserting "U+2060
Word Joiner".
If Accept-Charset
permits, the unicode character itself can be inserted directly into the HTML output.
Otherwise, it can be done using entity encoding. E.g. to join the text red-brown
, use:
red-⁠brown
or (decimal equivalent):
red-⁠brown
. Another usable character is "U+FEFF
Zero Width No-break Space"[ 1 ]:
red-brown
and (decimal equivalent):
red-brown
[1]: Note that while this method still works in major browsers like Chrome, it has been deprecated since Unicode 3.2.
Comparison of "the joiner way" with "U+2011
Non-breaking Hyphen":
The word joiner can be used for all other characters, not just hyphens.
When using the word joiner, most renderers will rasterize the text identically. On Chrome, FireFox, IE, and Opera, the rendering of normal hyphens, eg:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z
is identical to the rendering of normal hyphens (with U+2060 Word Joiner), eg:
a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z
while the above two renders differ from the rendering of "Non-breaking Hyphen", eg:
a‑b‑c‑d‑e‑f‑g‑h‑i‑j‑k‑l‑m‑n‑o‑p‑q‑r‑s‑t‑u‑v‑w‑x‑y‑z
. (The extent of the difference is browser-dependent and font-dependent. E.g. when using a font declaration of "arial
", Firefox and IE11 show relatively huge variations, while Chrome and Opera show smaller variations.)
Comparison of "the joiner way" with <span class=c1></span>
(CSS .c1 {white-space:nowrap;}
) and <nobr></nobr>
:
The word joiner can be used for situations where usage of HTML tags is restricted, e.g. forms of websites and forums.
On the spectrum of presentation and content, majority will consider the word joiner to be closer to content, when compared to tags.
• As tested on Windows 8.1 Core 64-bit using:
• IE 11.0.9600.18205
• Firefox 43.0.4
• Chrome 48.0.2564.109 (Official Build) m (32-bit)
• Opera 35.0.2066.92
This works.
<html>
<head>
<script type = "text/javascript">
function write_below(form)
{
var input = document.forms.write.input_to_write.value;
document.getElementById('write_here').innerHTML="Your input was:"+input;
return false;
}
</script>
</head>
<!--Insert more code here-->
<body>
<form name='write' onsubmit='return write_below(this);'>
<input type = "text" name='input_to_write'>
<input type = "button" value = "submit" />
</form>
<div id='write_here'></div></body>
</html>
Returning false from the function never posts it to other page,but does edit the html content.
Supposing d
is your list of dicts, simply:
df = pd.DataFrame(d)
Note: this does not work with nested data.
Kinda old subject but I had same question a few days ago and I came up with another idea (maybe someone will still find it usefull)
For example you can make a config.bat with different subjects (family, size, color, animals) and apply them individually in any order anywhere you want in your batch scripts:
@echo off
rem Empty the variable to be ready for label config_all
set config_all_selected=
rem Go to the label with the parameter you selected
goto :config_%1
REM This next line is just to go to end of file
REM in case that the parameter %1 is not set
goto :end
REM next label is to jump here and get all variables to be set
:config_all
set config_all_selected=1
:config_family
set mother=Mary
set father=John
set sister=Anna
rem This next line is to skip going to end if config_all label was selected as parameter
if not "%config_all_selected%"=="1" goto :end
:config_test
set "test_parameter_all=2nd set: The 'all' parameter WAS used before this echo"
if not "%config_all_selected%"=="1" goto :end
:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end
:config_color
set first_color=blue
set second_color=green
if not "%config_all_selected%"=="1" goto :end
:config_animals
set dog=Max
set cat=Miau
if not "%config_all_selected%"=="1" goto :end
:end
After that, you can use it anywhere by calling fully with 'call config.bat all' or calling only parts of it (see example bellow) The idea in here is that sometimes is more handy when you have the option not to call everything at once. Some variables maybe you don't want to be called yet so you can call them later.
Example test.bat
@echo off
rem This is added just to test the all parameter
set "test_parameter_all=1st set: The 'all' parameter was NOT used before this echo"
call config.bat size
echo My birthday present had a width of %width% and a height of %height%
call config.bat family
call config.bat animals
echo Yesterday %father% and %mother% surprised %sister% with a cat named %cat%
echo Her brother wanted the dog %dog%
rem This shows you if the 'all' parameter was or not used (just for testing)
echo %test_parameter_all%
call config.bat color
echo His lucky color is %first_color% even if %second_color% is also nice.
echo.
pause
Hope it helps the way others help me in here with their answers.
A short version of the above:
config.bat
@echo off
set config_all_selected=
goto :config_%1
goto :end
:config_all
set config_all_selected=1
:config_family
set mother=Mary
set father=John
set daughter=Anna
if not "%config_all_selected%"=="1" goto :end
:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end
:end
test.bat
@echo off
call config.bat size
echo My birthday present had a width of %width% and a height of %height%
call config.bat family
echo %father% and %mother% have a daughter named %daughter%
echo.
pause
Good day.
The OP's error specifies a host (my-store.myshopify.com
).
The error I encountered is the same in all respects except that no domain is specified.
My solution may help others who are drawn here by the title "Error: getaddrinfo EAI_AGAIN"
I encountered the error when trying to serve a NodeJs & VueJs app from a different VM from where the code was developed originally.
The file vue.config.js
read :
module.exports = {
devServer: {
host: 'tstvm01',
port: 3030,
},
};
When served on the original machine the start up output is :
App running at:
- Local: http://tstvm01:3030/
- Network: http://tstvm01:3030/
Using the same settings on a VM tstvm07
got me a very similar error to the one the OP describes:
INFO Starting development server...
10% building modules 1/1 modules 0 activeevents.js:183
throw er; // Unhandled 'error' event
^
Error: getaddrinfo EAI_AGAIN
at Object._errnoException (util.js:1022:11)
at errnoException (dns.js:55:15)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
If it ain't already obvious, changing vue.config.js
to read ...
module.exports = {
devServer: {
host: 'tstvm07',
port: 3030,
},
};
... solved the problem.
The following worked for me after hours of trying
$http.post("http://localhost:8080/yourresource", parameter, {headers:
{'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }).
However following code did not work, I am unclear as to why, hopefully someone can improve this answer.
$http({ method: 'POST', url: "http://localhost:8080/yourresource",
parameter,
headers: {'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'}
})
I'm using Visual Studio with Parallels/Win 7 on a MacBook laptop keyboard and the only thing that worked was Fn + Enter/Return (that's the Mac shortcut for Insert).
Without using Collections in Java:
import java.util.Scanner;
public class SortingaString {
public static String Sort(String s1)
{
char ch[]=s1.toCharArray();
String res=" ";
for(int i=0; i<ch.length ; i++)
{
for(int j=i+1;j<ch.length; j++)
{
if(ch[i]>=ch[j])
{
char m=ch[i];
ch[i]=ch[j];
ch[j]=m;
}
}
res=res+ch[i];
}
return res;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the string");
String s1=sc.next();
String ans=Sort( s1);
System.out.println("after sorting=="+ans);
}
}
Output:
enter the string==
sorting
after sorting== ginorst
There are several ways to concatenate two strings together.
Use the concatenation operator .
(and .=
)
In PHP .
is the concatenation operator which returns the concatenation of its right and left arguments
$data1 = "the color is";
$data2 = "red";
$result = $data1 . ' ' . $data2;
If you want to append a string to another string you would use the .=
operator:
$data1 = "the color is ";
$data1 .= "red"
Complex (curly) syntax / double quotes strings
In PHP variables contained in double quoted strings are interpolated (i.e. their values are "swapped out" for the variable). This means you can place the variables in place of the strings and just put a space in between them. The curly braces make it clear where the variables are.
$result = "{$data1} {$data2}";
Note: this will also work without the braces in your case:
$result = "$data1 $data2";
You can also concatenate array values inside a string :
$arr1 = ['val' => 'This is a'];
$arr2 = ['val' => 'test'];
$variable = "{$arr1['val']} {$arr2['val']}";
Use sprintf()
or printf()
sprintf()
allows us to format strings using powerful formatting options. It is overkill for such simple concatenation but it handy when you have a complex string and/or want to do some formatting of the data as well.
$result = sprintf("%s %s", $data1, $data2);
printf()
does the same thing but will immediately display the output.
printf("%s %s", $data1, $data2);
// same as
$result = sprintf("%s %s", $data1, $data2);
echo $result;
Heredoc
Heredocs can also be used to combine variables into a string.
$result= <<<EOT
$data1 $data2
EOT;
Use a ,
with echo()
This only works when echoing out content and not assigning to a variable. But you can use a comma to separate a list of expressions for PHP to echo out and use a string with one blank space as one of those expressions:
echo $data1, ' ', $data2;
var str = "43215";
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
str = "0" + str;
}
console.log("After : \n string :"+str+"\n Length :"+str.length);
It worked for me ! To increase the zeroes, update the 'max' variable
Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:
Try this. It's the easiest & most efficient way
<style name="datepicker" parent="Theme.AppCompat.Light.Dialog">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/primary</item>
</style>
I found this to occur when you mix ggplot charts with plot charts in the same session. Using the 'dev.off' solution suggested by Paul solves the issue.
You can make your ImageButton widget as I did. In my case, I needed a widget with a fixed icon size. Let's start from custom attributes:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ImageButtonFixedIconSize">
<attr name="imageButton_icon" format="reference" />
<attr name="imageButton_iconWidth" format="dimension" />
<attr name="imageButton_iconHeight" format="dimension" />
</declare-styleable>
</resources>
Widget class is quite simple (the key point is padding calculations in onLayout method):
class ImageButtonFixedIconSize
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.imageButtonStyle
) : ImageButton(context, attrs, defStyleAttr) {
private lateinit var icon: Drawable
@Px
private var iconWidth: Int = 0
@Px
private var iconHeight: Int = 0
init {
scaleType = ScaleType.FIT_XY
attrs?.let { retrieveAttributes(it) }
}
/**
*
*/
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
val width = right - left
val height = bottom - top
val horizontalPadding = if(width > iconWidth) (width - iconWidth) / 2 else 0
val verticalPadding = if(height > iconHeight) (height - iconHeight) / 2 else 0
setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)
setImageDrawable(icon)
super.onLayout(changed, left, top, right, bottom)
}
/**
*
*/
private fun retrieveAttributes(attrs: AttributeSet) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageButtonFixedIconSize)
icon = typedArray.getDrawable(R.styleable.ImageButtonFixedIconSize_imageButton_icon)!!
iconWidth = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconWidth, 0f).toInt()
iconHeight = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconHeight, 0f).toInt()
typedArray.recycle()
}
}
And at last you should use your widget like this:
<com.syleiman.gingermoney.ui.common.controls.ImageButtonFixedIconSize
android:layout_width="90dp"
android:layout_height="63dp"
app:imageButton_icon="@drawable/ic_backspace"
app:imageButton_iconWidth="20dp"
app:imageButton_iconHeight="15dp"
android:id="@+id/backspaceButton"
tools:ignore="ContentDescription"
/>
From Maven - Settings Reference
The repositories for download and deployment are defined by the repositories
and distributionManagement
elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.
<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">
...
<servers>
<server>
<id>server001</id>
<username>my_login</username>
<password>my_password</password>
<privateKey>${user.home}/.ssh/id_dsa</privateKey>
<passphrase>some_passphrase</passphrase>
<filePermissions>664</filePermissions>
<directoryPermissions>775</directoryPermissions>
<configuration></configuration>
</server>
</servers>
...
</settings>
id: This is the ID of the server (not of the user to login as) that matches the id element of the repository/mirror that Maven tries to connect to.
username, password: These elements appear as a pair denoting the login and password required to authenticate to this server.
privateKey, passphrase: Like the previous two elements, this pair specifies a path to a private key (default is ${user.home}/.ssh/id_dsa
) and a passphrase, if required. The passphrase and password elements may be externalized in the future, but for now they must be set plain-text in the settings.xml file.
filePermissions, directoryPermissions: When a repository file or directory is created on deployment, these are the permissions to use. The legal values of each is a three digit number corrosponding to *nix file permissions, ie. 664, or 775.
Note: If you use a private key to login to the server, make sure you omit the element. Otherwise, the key will be ignored.
All you should need is the id
, username
and password
The id
and URL
should be defined in your pom.xml
like this:
<repositories>
...
<repository>
<id>acme-nexus-releases</id>
<name>acme nexus</name>
<url>https://nexus.acme.net/content/repositories/releases</url>
</repository>
...
</repositories>
If you need a username and password to your server, you should encrypt it. Maven Password Encryption
You can specify the whole day by doing a range, like so:
WHERE bk_date >= TO_DATE('2012-03-18', 'YYYY-MM-DD')
AND bk_date < TO_DATE('2012-03-19', 'YYYY-MM-DD')
More simply you can use TRUNC:
WHERE TRUNC(bk_date) = TO_DATE('2012-03-18', 'YYYY-MM-DD')
TRUNC without parameter removes hours, minutes and seconds from a DATE.
This question touches a very stinking part of the "famous" and "obvious" Python syntax - what takes precedence, the lambda, or the for of list comprehension.
I don't think the purpose of the OP was to generate a list of squares from 0 to 9. If that was the case, we could give even more solutions:
squares = []
for x in range(10): squares.append(x*x)
But it's not the point. The point is W(hy)TF is this ambiguous expression so counter-intuitive? And I have an idiotic case for you at the end, so don't dismiss my answer too early (I had it on a job interview).
So, the OP's comprehension returned a list of lambdas:
[(lambda x: x*x) for x in range(10)]
This is of course just 10 different copies of the squaring function, see:
>>> [lambda x: x*x for _ in range(3)]
[<function <lambda> at 0x00000000023AD438>, <function <lambda> at 0x00000000023AD4A8>, <function <lambda> at 0x00000000023AD3C8>]
Note the memory addresses of the lambdas - they are all different!
You could of course have a more "optimal" (haha) version of this expression:
>>> [lambda x: x*x] * 3
[<function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>, <function <lambda> at 0x00000000023AD2E8>]
See? 3 time the same lambda.
Please note, that I used _
as the for
variable. It has nothing to do with the x
in the lambda
(it is overshadowed lexically!). Get it?
I'm leaving out the discussion, why the syntax precedence is not so, that it all meant:
[lambda x: (x*x for x in range(10))]
which could be: [[0, 1, 4, ..., 81]]
, or [(0, 1, 4, ..., 81)]
, or which I find most logical, this would be a list
of 1 element - a generator
returning the values. It is just not the case, the language doesn't work this way.
BUT What, If...
What if you DON'T overshadow the for
variable, AND use it in your lambda
s???
Well, then crap happens. Look at this:
[lambda x: x * i for i in range(4)]
this means of course:
[(lambda x: x * i) for i in range(4)]
BUT it DOESN'T mean:
[(lambda x: x * 0), (lambda x: x * 1), ... (lambda x: x * 3)]
This is just crazy!
The lambdas in the list comprehension are a closure over the scope of this comprehension. A lexical closure, so they refer to the i
via reference, and not its value when they were evaluated!
So, this expression:
[(lambda x: x * i) for i in range(4)]
IS roughly EQUIVALENT to:
[(lambda x: x * 3), (lambda x: x * 3), ... (lambda x: x * 3)]
I'm sure we could see more here using a python decompiler (by which I mean e.g. the dis
module), but for Python-VM-agnostic discussion this is enough.
So much for the job interview question.
Now, how to make a list
of multiplier lambdas, which really multiply by consecutive integers? Well, similarly to the accepted answer, we need to break the direct tie to i
by wrapping it in another lambda
, which is getting called inside the list comprehension expression:
Before:
>>> a = [(lambda x: x * i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
2
After:
>>> a = [(lambda y: (lambda x: y * x))(i) for i in (1, 2)]
>>> a[1](1)
2
>>> a[0](1)
1
(I had the outer lambda variable also = i
, but I decided this is the clearer solution - I introduced y
so that we can all see which witch is which).
Edit 2019-08-30:
Following a suggestion by @josoler, which is also present in an answer by @sheridp - the value of the list comprehension "loop variable" can be "embedded" inside an object - the key is for it to be accessed at the right time. The section "After" above does it by wrapping it in another lambda
and calling it immediately with the current value of i
. Another way (a little bit easier to read - it produces no 'WAT' effect) is to store the value of i
inside a partial
object, and have the "inner" (original) lambda
take it as an argument (passed supplied by the partial
object at the time of the call), i.e.:
After 2:
>>> from functools import partial
>>> a = [partial(lambda y, x: y * x, i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)
Great, but there is still a little twist for you! Let's say we wan't to make it easier on the code reader, and pass the factor by name (as a keyword argument to partial
). Let's do some renaming:
After 2.5:
>>> a = [partial(lambda coef, x: coef * x, coef=i) for i in (1, 2)]
>>> a[0](1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() got multiple values for argument 'coef'
WAT?
>>> a[0]()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() missing 1 required positional argument: 'x'
Wait... We're changing the number of arguments by 1, and going from "too many" to "too few"?
Well, it's not a real WAT, when we pass coef
to partial
in this way, it becomes a keyword argument, so it must come after the positional x
argument, like so:
After 3:
>>> a = [partial(lambda x, coef: coef * x, coef=i) for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)
I would prefer the last version over the nested lambda, but to each their own...
Edit 2020-08-18:
Thanks to commenter dasWesen, I found out that this stuff is covered in the Python documentation: https://docs.python.org/3.4/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result - it deals with loops instead of list comprehensions, but the idea is the same - global or nonlocal variable access in the lambda function. There's even a solution - using default argument values (like for any function):
>>> a = [lambda x, coef=i: coef * x for i in (1, 2)]
>>> a[0](2), a[1](2)
(2, 4)
This way the coef value is bound to the value of i at the time of function definition (see James Powell's talk "Top To Down, Left To Right", which also explains why mutable default values are shunned).
public static void main(String[] args) {
char ch='m';
String str="Hello",k=String.valueOf(ch),b,c;
System.out.println(str);
int index=3;
b=str.substring(0,index-1 );
c=str.substring(index-1,str.length());
str=b+k+c;
}
or do it with Route Attribute:
public class InventoryController : Controller
{
[Route("whatever/{firstItem}")]
public ActionResult ViewStockNext(int firstItem)
{
int yourNewVariable = firstItem;
// ...
}
}
Anyone who's still having issues with this one and have tried all the options above and never got it. I'm sharing my solution, this is to take consideration that you don't wan't to explicitly state the properties of your object vs the array.
function isIdentical(left, right){
return JSON.stringify(left) === JSON.stringify(right);
}
function contains(array, obj){
let count = 0;
array.map((cur) => {
if(this.isIdentical(cur, obj)) count++;
});
return count > 0;
}
This is a combination of iterating the reference array and comparing it to the object you wanted to check, convert both of them into a string then iterated if it matched. Then you can just count. This can be improved but this is where I settled. Hope this helps.
As mentioned in Yoshua Wuyts' answer, using git branch
:
git branch --unset-upstream
You don't have to delete your local branch.
Simply delete the local branch that is tracking the remote branch:
git branch -d -r origin/<remote branch name>
-r, --remotes
tells git to delete the remote-tracking branch (i.e., delete the branch set to track the remote branch). This will not delete the branch on the remote repo!
See "Having a hard time understanding git-fetch"
there's no such concept of local tracking branches, only remote tracking branches.
Soorigin/master
is a remote tracking branch formaster
in theorigin
repo
As mentioned in Dobes Vandermeer's answer, you also need to reset the configuration associated to the local branch:
git config --unset branch.<branch>.remote
git config --unset branch.<branch>.merge
Remove the upstream information for
<branchname>
.
If no branch is specified it defaults to the current branch.
(git 1.8+, Oct. 2012, commit b84869e by Carlos Martín Nieto (carlosmn
))
That will make any push/pull completely unaware of origin/<remote branch name>
.
As the plural in getElementsByName()
implies, does it always return list of elements that have this name. So when you have an input element with that name:
<input type="text" name="Tue">
And it is the first one with that name, you have to use document.getElementsByName('Tue')[0]
to get the first element of the list of elements with this name.
Beside that are properties case sensitive and the correct spelling of the value property is .value
.
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
If you set display:
to inline-block
, block
, flex
, ..., on the element with no content, then
For min-width
to take effect on a tag with no content, you only need to apply padding for either top or bot.
For min-height
to take effect on a tag with no content, you only need to apply padding for left or right.
It's my solution:
public void getBytes(int val) {
byte[] bytes = new byte[Integer.BYTES];
for (int i = 0;i < bytes.length; i ++) {
int j = val % Byte.MAX_VALUE;
bytes[i] = (j == 0 ? Byte.MAX_VALUE : j);
}
}
Also String
y method:
public void getBytes(int val) {
String hex = Integer.toHexString(val);
byte[] val = new byte[hex.length()/2]; // because byte is 2 hex chars
for (int i = 0; i < hex.length(); i+=2)
val[i] = Byte.parseByte("0x" + hex.substring(i, i+2), 16);
return val;
}
This is with reference to @Ladislav Mrnka's answer on using fluent api for configuring one-to-one relationship.
Had a situation where having FK of dependent must be it's PK
was not feasible.
E.g., Foo
already has one-to-many relationship with Bar
.
public class Foo {
public Guid FooId;
public virtual ICollection<> Bars;
}
public class Bar {
//PK
public Guid BarId;
//FK to Foo
public Guid FooId;
public virtual Foo Foo;
}
Now, we had to add another one-to-one relationship between Foo and Bar.
public class Foo {
public Guid FooId;
public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
public virtual Bar PrimaryBar;
public virtual ICollection<> Bars;
}
public class Bar {
public Guid BarId;
public Guid FooId;
public virtual Foo PrimaryBarOfFoo;
public virtual Foo Foo;
}
Here is how to specify one-to-one relationship using fluent api:
modelBuilder.Entity<Bar>()
.HasOptional(p => p.PrimaryBarOfFoo)
.WithOptionalPrincipal(o => o.PrimaryBar)
.Map(x => x.MapKey("PrimaryBarId"));
Note that while adding PrimaryBarId
needs to be removed, as we specifying it through fluent api.
Also note that method name [WithOptionalPrincipal()][1]
is kind of ironic. In this case, Principal is Bar. WithOptionalDependent() description on msdn makes it more clear.
You can do it this:
$clientName = $request->request->get('appbundle_client')['clientName'];
Sometimes, when the attributes are protected, you can not have access to get the value for the common method of access:
(POST)
$clientName = $request->request->get('clientName');
(GET)
$clientName = $request->query->get('clientName');
(GENERIC)
$clientName = $request->get('clientName');
Cell cell = row.getCell(x, Row.CREATE_NULL_AS_BLANK);
This trick helped me a lot, see if it's useful for you
If you are using WAMP then type the following in the browser
http://localhost/?phpinfo=-1,
you will get the phpinfo page.
You can also click the localhost icon in the wamp menu from the systray and then find the phpinfo page. WAMP localhost from WAMP Menu
I came up with this one liner recently for getting True
if a list contains any number of occurrences of an item, or False
if it contains no occurrences or nothing at all. Using next(...)
gives this a default return value (False
) and means it should run significantly faster than running the whole list comprehension.
list_does_contain = next((True for item in list_to_test if item == test_item), False)
Yes you can if you are using HTML5, this code is valid not otherwise:
<a href="#foo"><div>.......</div></a>
If you are not using HTML5, you can make your link block
:
<a href="#foo" id="link">Click Here</a>
CSS:
#link {
display : block;
width:100px;
height:40px;
}
Notice that you can apply width
, height
only after making your link block level element.
A small snippet I use very often to create map from other maps:
static public <K, V> Map<K, V> merge(Map<K, V>... args) {
final Map<K, V> buffer = new HashMap<>();
for (Map m : args) {
buffer.putAll(m);
}
return buffer;
}
np.array()
is even more powerful than what unutbu said above.
You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:
aArray=np.array([1,1,1])
bArray=np.array([2,2,2])
aList=[aArray, bArray]
xArray=np.array(aList)
xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.
Yess, possible with conditions:
If you have your app installed in the user phone and a server app communicating with this app, and there at last one of location service providers activated in the user phone, and some horrible android permissions!
In most of android phones there 3 location providers that can give exact location (GPS_PROVIDER 1m) or estimated (NETWORK_PROVIDER around 2-20m) and PASSIVE_PROVIDER (more in LocationManager official documentation).
1* App sends SMS to user's phone
Yess, can be server app or you create an android app if you want something automated, so you can do it manually by sending SMS from your default SMS app! I use Kannel: Open Source WAP and SMS Gateway and here (lot of APIs to send SMS )
2* App receives SMS at user's phone from the SMS sender
Yess, you can get all received SMS, and you can filter them by sender phone number! and do some actions when your specified sms received, basic tuto here (i do some actions according to the content of my SMS)
3* App gets location coordinates of the user's phone
Yess, you can get actual user coordinates easily if one of location providers is activated, so you can get last known location when the user have activated one of location providers, if those disabled or the phone don't have GPS hardware you can use Open Cell Id api to get the nearest cell coordinates(10m-10Km) or Loc8 api but those not available in all around the world, and some apps use IP location apis to get the country, city and province, here the simplest way to get current user location.
4* App sends location coordinates to the SMS sender via SMS
Yess, you can get sender phone number and send user location, immediately when SMS received or at specified times in the day.
(Those 4 yesses for you :) )
Viber and other apps that access to users locations, identify there users by there phone numbers by obligating them to send SMS to the server app to create an account and activate the free service (Ex:VOIP) , and lunch a service that can:
And your application users must accept all of that when installing it, of corse i don't gonna install apps like this because i read permissions before installing :) and permissions maybe something like that:
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<-- and more if you wanna more -->
The final user will accept for something like that (those permissions of an android app u asked about):
This app has access to these permissions:
Your accounts -create accounts and set passwords -find accounts on the device -add or remove accounts -use accounts on the device -read Google service configuration
Your location -approximate location (network-based) -precise location (GPS and network-based)
Your messages -receive text messages (SMS) -send SMS messages -edit your text messages (SMS or MMS) -read your text messages (SMS or MMS)
Network communication -receive data from Internet -full network access -view Wi-Fi connections -view network connections -change network connectivity
Phone calls -read phone status and identity -directly call phone numbers
Storage -modify or delete the contents of your USB storage
Your applications information -retrieve running apps -close other apps -run at startup
Bluetooth -pair with Bluetooth devices -access Bluetooth settings
Camera -take pictures and videos
Other Application UI -draw over other apps
Microphone -record audio
Lock screen -disable your screen lock
Your social information -read your contacts -modify your contacts -read call log -write call log -read your social stream -write to your social stream
Development tools -read sensitive log data
System tools -modify system settings -send sticky broadcast -test access to protected storage
Affects battery -control vibration -prevent device from sleeping
Audio settings -change your audio settings
Sync Settings -read sync settings -toggle sync on and off -read sync statistics
Wallpaper -set wallpaper
This is your code:
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "databasename");
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
?>
The only error that causes this message is that:
DB_USER
but you're calling after as DB_USERNAME
.Please be more careful next time.
It is better for an entry-level programmer that wants to start coding in PHP
not to use what he or she does not know very well.
ONLY as advice, please try to use (for the first time) code more ubiquitous.
ex: do not use the define()
statement, try to use variables declaration as $db_user = 'root';
Have a nice experience :)
In general, the cause of the problem could be the following:
You started a new project with the new virtual environment. So probably you install numpy from the terminal, but it is not in your venv. So
either install it from PyCahrm Interface: Settings -> Project Interpreter -> Add the package
or activate your venv and -> pip install numPy
I've used bootstrap header classes ("h1", "h2", etc.) for this. This way you get all the style benefits without using the actual tags. Here is an example:
<div class="h3"><span class="glyphicon glyphicon-tags" aria-hidden="true"></span></div>
I solved just by: given correct host and port so:
in Listener on address 2 then copy host to Oracle Developer
finally connect to oracle
new AlertDialog.Builder(context)
.setTitle("title")
.setMessage("message")
.setPositiveButton(android.R.string.ok, null)
.show();
Shorter way:
var queue = function (args){
typeof variableToCheck !== "undefined"? doSomething(args) : setTimeout(function () {queue(args)}, 2000);
};
You can also pass arguments
If if doesn't work then use "!Important"
@media (min-width: 1200px) { .container { width: 970px !important; } }
var result = jsObjects.filter(x=> x.b === 6);
will be better, using return in filter sometimes you can't get result (I dunno why)
Use jquery-dateFormat. It will solve your problem.
You need to include the jquery.dateFormat in your html file.
<script>
var date = $('#scheduleDate').val();
document.write($.format.date(date, "dd,MM,yyyy"));
var dateTypeVar = $('#scheduleDate').datepicker('getDate');
document.write($.format.date(dateTypeVar, "dd-MM-yy"));
</script>
I had this same problem installing my app to a server. It ended up being the installer project, it wasn't installing all the files needed to run the web app. I tried to figure out where it was broken but in the end I had to revert the project to the previous version to fix it. Hope this helps someone...
The simplest, and best long-term solution
Go to the main menu on top of Eclipse and locate Window next to Run and expand it.
Window->Reset Perspective... to restore all views to their defaults
It will reset the default setting.
Some pages may require more than login/pass. There may even be hidden fields. The most reliable way is to use inspect tool and look at the network tab while logging in, to see what data is being passed on.
FOR %%A IN (%*) DO (
REM Now your batch file handles %%A instead of %1
REM No need to use SHIFT anymore.
ECHO %%A
)
This loops over the batch parameters (%*) either they are quoted or not, then echos each parameter.
In my case, using MAC OS X 10.11 and Android 2.0, and by doing exactly what Aqib Mumtaz has explained.
But, each time, I had this message : "A problem occurred configuring project ':app'. > Cannot evaluate module xxx : Configuration with name 'default' not found."
I found that the reason of this message is that Android 2.0 doesn't allow to create a library directly. So, I have decided first to create an app projet and then to modify the build.gradle in order to transform it as a library.
This solution doesn't work, because a Library project is very different than an app project.
So, I have resolved my problem like this :
Then continue with the solution proposed by Aqib Mumtaz.
As a result, your library source will be shared without needing to duplicate source files each time (it was an heresy for me!)
Hoping that this help you.
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
The best thing that you can do is to set a function to be called on a given amount of time and this function to check the contents of your textarea.
self.setInterval('checkTextAreaValue()', 50);
Use the tag @import
@import url('http://fonts.googleapis.com/css?family=Kavoon');
422 Unprocessable Entity Explained Updated: March 6, 2017
What Is 422 Unprocessable Entity?
A 422 status code occurs when a request is well-formed, however, due to semantic errors it is unable to be processed. This HTTP status was introduced in RFC 4918 and is more specifically geared toward HTTP extensions for Web Distributed Authoring and Versioning (WebDAV).
There is some controversy out there on whether or not developers should return a 400 vs 422 error to clients (more on the differences between both statuses below). However, in most cases, it is agreed upon that the 422 status should only be returned if you support WebDAV capabilities.
A word-for-word definition of the 422 status code taken from section 11.2 in RFC 4918 can be read below.
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.
The definition goes on to say:
For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
400 vs 422 Status Codes
Bad request errors make use of the 400 status code and should be returned to the client if the request syntax is malformed, contains invalid request message framing, or has deceptive request routing. This status code may seem pretty similar to the 422 unprocessable entity status, however, one small piece of information that distinguishes them is the fact that the syntax of a request entity for a 422 error is correct whereas the syntax of a request that generates a 400 error is incorrect.
The use of the 422 status should be reserved only for very particular use-cases. In most other cases where a client error has occurred due to malformed syntax, the 400 Bad Request status should be used.
Timing with random strings of ASCII printables:
from inspect import getsource
from random import sample
import re
from string import printable
from timeit import timeit
pattern_single = re.compile(r'[\W]')
pattern_repeat = re.compile(r'[\W]+')
translation_tb = str.maketrans('', '', ''.join(c for c in map(chr, range(256)) if not c.isalnum()))
def generate_test_string(length):
return ''.join(sample(printable, length))
def main():
for i in range(0, 60, 10):
for test in [
lambda: ''.join(c for c in generate_test_string(i) if c.isalnum()),
lambda: ''.join(filter(str.isalnum, generate_test_string(i))),
lambda: re.sub(r'[\W]', '', generate_test_string(i)),
lambda: re.sub(r'[\W]+', '', generate_test_string(i)),
lambda: pattern_single.sub('', generate_test_string(i)),
lambda: pattern_repeat.sub('', generate_test_string(i)),
lambda: generate_test_string(i).translate(translation_tb),
]:
print(timeit(test), i, getsource(test).lstrip(' lambda: ').rstrip(',\n'), sep='\t')
if __name__ == '__main__':
main()
Result (Python 3.7):
Time Length Code
6.3716264850008880 00 ''.join(c for c in generate_test_string(i) if c.isalnum())
5.7285426190064750 00 ''.join(filter(str.isalnum, generate_test_string(i)))
8.1875841680011940 00 re.sub(r'[\W]', '', generate_test_string(i))
8.0002205439959650 00 re.sub(r'[\W]+', '', generate_test_string(i))
5.5290945199958510 00 pattern_single.sub('', generate_test_string(i))
5.4417179649972240 00 pattern_repeat.sub('', generate_test_string(i))
4.6772285089973590 00 generate_test_string(i).translate(translation_tb)
23.574712151996210 10 ''.join(c for c in generate_test_string(i) if c.isalnum())
22.829975890002970 10 ''.join(filter(str.isalnum, generate_test_string(i)))
27.210196289997840 10 re.sub(r'[\W]', '', generate_test_string(i))
27.203713296003116 10 re.sub(r'[\W]+', '', generate_test_string(i))
24.008979928999906 10 pattern_single.sub('', generate_test_string(i))
23.945240008994006 10 pattern_repeat.sub('', generate_test_string(i))
21.830899796994345 10 generate_test_string(i).translate(translation_tb)
38.731336012999236 20 ''.join(c for c in generate_test_string(i) if c.isalnum())
37.942474347000825 20 ''.join(filter(str.isalnum, generate_test_string(i)))
42.169366310001350 20 re.sub(r'[\W]', '', generate_test_string(i))
41.933375883003464 20 re.sub(r'[\W]+', '', generate_test_string(i))
38.899814646996674 20 pattern_single.sub('', generate_test_string(i))
38.636144253003295 20 pattern_repeat.sub('', generate_test_string(i))
36.201238164998360 20 generate_test_string(i).translate(translation_tb)
49.377356811004574 30 ''.join(c for c in generate_test_string(i) if c.isalnum())
48.408927293996385 30 ''.join(filter(str.isalnum, generate_test_string(i)))
53.901889764994850 30 re.sub(r'[\W]', '', generate_test_string(i))
52.130339455994545 30 re.sub(r'[\W]+', '', generate_test_string(i))
50.061149017004940 30 pattern_single.sub('', generate_test_string(i))
49.366573111998150 30 pattern_repeat.sub('', generate_test_string(i))
46.649754120997386 30 generate_test_string(i).translate(translation_tb)
63.107938601999194 40 ''.join(c for c in generate_test_string(i) if c.isalnum())
65.116287978999030 40 ''.join(filter(str.isalnum, generate_test_string(i)))
71.477421126997800 40 re.sub(r'[\W]', '', generate_test_string(i))
66.027950693998720 40 re.sub(r'[\W]+', '', generate_test_string(i))
63.315361931003280 40 pattern_single.sub('', generate_test_string(i))
62.342320287003530 40 pattern_repeat.sub('', generate_test_string(i))
58.249303059004890 40 generate_test_string(i).translate(translation_tb)
73.810345625002810 50 ''.join(c for c in generate_test_string(i) if c.isalnum())
72.593953348005020 50 ''.join(filter(str.isalnum, generate_test_string(i)))
76.048324580995540 50 re.sub(r'[\W]', '', generate_test_string(i))
75.106637657001560 50 re.sub(r'[\W]+', '', generate_test_string(i))
74.681338128997600 50 pattern_single.sub('', generate_test_string(i))
72.430461594005460 50 pattern_repeat.sub('', generate_test_string(i))
69.394243567003290 50 generate_test_string(i).translate(translation_tb)
str.maketrans
& str.translate
is fastest, but includes all non-ASCII characters.
re.compile
& pattern.sub
is slower, but is somehow faster than ''.join
& filter
.
In PHP you simply can convert a value to a boolean by using double not operator (!!
):
var_dump(!! true); // true
var_dump(!! "Hello"); // true
var_dump(!! 1); // true
var_dump(!! [1, 2]); // true
var_dump(!! false); // false
var_dump(!! null); // false
var_dump(!! []); // false
var_dump(!! 0); // false
var_dump(!! ''); // false
Padding around the collapsing div must be 0
Check this link , it is advanced github search https://github.com/search?l=Java&o=desc&q=android&ref=searchresults&s=stars&type=Repositories and this project contain a lot of libraries to Kick-starts you in Android https://github.com/mttkay/ignition
getView()
method create new View
or ViewGroup
for each row of Listview
or Spinner . You can define this View
or ViewGroup
in a Layout XML
file in res/layout
folder and can give the reference it to Adapter
class Object.
if you have 4 item in a Array passed to Adapter. getView()
method will create 4 View for 4 rows of Adaper.
LayoutInflater class has a Method inflate() whic create View Object from XML resource layout.
ALTER TABLE tablename
ALTER COLUMN columnname columndatatype(size)
Note: if there is a size of columns, just write the size also.
Both will have a key of 0
, and that method of combining the arrays will collapse duplicates. Try using array_merge()
instead.
$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')
// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);
If the elements in your array used different keys, the +
operator would be more appropriate.
$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');
// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;
Edit: Added a code snippet to clarify
You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:
input[type="range"] {_x000D_
position: absolute;_x000D_
top: 40%;_x000D_
transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
or the 3d transform equivalent:
input[type="range"] {
transform: rotateZ(270deg);
}
You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString()
and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
Lets see what happens if we won't use $this and try to have instance variables and constructor arguments with the same name with the following code snippet
<?php
class Student {
public $name;
function __construct( $name ) {
$name = $name;
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
It echos nothing but
<?php
class Student {
public $name;
function __construct( $name ) {
$this->name = $name; // Using 'this' to access the student's name
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
this echoes 'Tom'
You can find the URL for your class first. If it's a JAR, then you load the manifest from there. For example,
Class clazz = MyClass.class;
String className = clazz.getSimpleName() + ".class";
String classPath = clazz.getResource(className).toString();
if (!classPath.startsWith("jar")) {
// Class not from JAR
return;
}
String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) +
"/META-INF/MANIFEST.MF";
Manifest manifest = new Manifest(new URL(manifestPath).openStream());
Attributes attr = manifest.getMainAttributes();
String value = attr.getValue("Manifest-Version");
$("#togglebutton").click(function () {
$(".fa-arrow-circle-left").toggleClass("fa-arrow-circle-right");
}
I have a button with the id "togglebutton" and an icon from FontAwesome . This can be a way to toggle it . from left arrow to right arrow icon
In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
count := 10
then := now.Add(time.Duration(-count) * time.Minute)
// if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
// then := now.Add(-10 * time.Minute)
fmt.Println("10 minutes ago:", then)
}
Produces:
now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
Not to mention, you can also use time.Hour
or time.Second
instead of time.Minute
as per your needs.
Playground: https://play.golang.org/p/DzzH4SA3izp
Just wrote before for the same reason (works with any amount of arrays):
/**
* Returns with the union of the given arrays.
*
* @param Any amount of arrays to be united.
* @returns {array} The union array.
*/
function uniteArrays()
{
var union = [];
for (var argumentIndex = 0; argumentIndex < arguments.length; argumentIndex++)
{
eachArgument = arguments[argumentIndex];
if (typeof eachArgument !== 'array')
{
eachArray = eachArgument;
for (var index = 0; index < eachArray.length; index++)
{
eachValue = eachArray[index];
if (arrayHasValue(union, eachValue) == false)
union.push(eachValue);
}
}
}
return union;
}
function arrayHasValue(array, value)
{ return array.indexOf(value) != -1; }
xprop -root &> /dev/null
...is my tried & true command to test for an "X-able" situation. And, it's pretty much guaranteed to be on any system running X, of course, the command fails if not found anyways, so even if it doesnt exist, you can pretty much assume there is no X either. (thats why I use &> instead of >)
The thought process here is that you spend most of your time in development
. When in development, you create a feature
branch (off of development
), complete the feature, and then merge back into development
. This can then be added to the final production version by merging into production
.
See A Successful Git Branching Model for more detail on this approach.
raise ValueError('could not find %c in %s' % (ch,str))
Simple 3 steps:
1- Right click on database ? Tasks ? restore ? Database
2- Check Device
as source and locate .bak (or zipped .bak) file
3- In the left pane click on options
and:
Other options are really optional (and important of course)!
For Windows Users:
In Environment Variables, add a new variable in system variable with name "TESSDATA_PREFIX" and value is "C:\Program Files (x86)\Tesseract-OCR\tessdata"
You can add a facade in your folder\config\app.php
'Input' => Illuminate\Support\Facades\Input::class,
I would suggest using the String.Compare method. Using that method you can also control whether to to have it perform case-sensitive comparisons or not.
Sample:
Dim str1 As String = "String one"
Dim str2 As String = str1
Dim str3 As String = "String three"
Dim str4 As String = str3
If String.Compare(str1, str2) = 0 And String.Compare(str3, str4) = 0 Then
MessageBox.Show("str1 = str2 And str3 = str4")
Else
MessageBox.Show("Else")
End If
Edit: if you want to perform a case-insensitive search you can use the StringComparison parameter:
If String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) = 0 And String.Compare(str3, str4, StringComparison.InvariantCultureIgnoreCase) = 0 Then
This code here you give a list of strings of keys that you don't want to delete, then it filters those from all the keys in local storage then deletes the others.
const allKeys = Object.keys(localStorage);
const toBeDeleted = allKeys.filter(value => {
return !this.doNotDeleteList.includes(value);
});
toBeDeleted.forEach(value => {
localStorage.removeItem(value);
});
If you see the man page of logger:
$ man logger
LOGGER(1) BSD General Commands Manual LOGGER(1)
NAME logger — a shell command interface to the syslog(3) system log module
SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]
DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.
It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.
Here is another. We had a need to provide friendly names for our EnumValues. We used the System.ComponentModel.DescriptionAttribute to show a custom string value for each enum value.
public static class StaticClass
{
public static string GetEnumDescription(Enum currentEnum)
{
string description = String.Empty;
DescriptionAttribute da;
FieldInfo fi = currentEnum.GetType().
GetField(currentEnum.ToString());
da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi,
typeof(DescriptionAttribute));
if (da != null)
description = da.Description;
else
description = currentEnum.ToString();
return description;
}
public static List<string> GetEnumFormattedNames<TEnum>()
{
var enumType = typeof(TEnum);
if (enumType == typeof(Enum))
throw new ArgumentException("typeof(TEnum) == System.Enum", "TEnum");
if (!(enumType.IsEnum))
throw new ArgumentException(String.Format("typeof({0}).IsEnum == false", enumType), "TEnum");
List<string> formattedNames = new List<string>();
var list = Enum.GetValues(enumType).OfType<TEnum>().ToList<TEnum>();
foreach (TEnum item in list)
{
formattedNames.Add(GetEnumDescription(item as Enum));
}
return formattedNames;
}
}
In Use
public enum TestEnum
{
[Description("Something 1")]
Dr = 0,
[Description("Something 2")]
Mr = 1
}
static void Main(string[] args)
{
var vals = StaticClass.GetEnumFormattedNames<TestEnum>();
}
This will end returning "Something 1", "Something 2"
you could write a simple function like the following:
public static MyGender ConvertTo(TheirGender theirGender)
{
switch(theirGender)
{
case TheirGender.Male:
break;//return male
case TheirGender.Female:
break;//return female
case TheirGender.Unknown:
break;//return whatever
}
}
getResources().getDrawable()
was deprecated in API level 22. Now we must add the theme:getDrawable (int id, Resources.Theme theme) (Added in API level 21)
This is an example:
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
This is an example how to validate for later versions:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
} else {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage));
}
EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value
syntax is incorrect.
I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
error message. In 2008, the modified script is still successful.
declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)
You want to create a "Dynamic Web Project". Follow the steps here: Spring MVC Tutorial with Eclipse and Tomcat.
Also, here is the Eclipse documentation for Dynamic Web Projects: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.webtools.doc.user/topics/ccwebprj.html
you must parse JSON string to become object
var dataObject = jQuery.parseJSON(data);
so you can call it like:
success: function (data) {
var dataObject = jQuery.parseJSON(data);
if (dataObject.success == 1) {
var insertedGoalId = dataObject.inserted.goal_id;
...
...
}
}
You can also get all the result always as array by changing
// application/config/database.php
'fetch' => PDO::FETCH_CLASS,
// to
'fetch' => PDO::FETCH_ASSOC,
Hope this will help.
I just discovered Telerik has some great components, including Grid, and they are open source too. http://demos.telerik.com/aspnet-mvc/
Why so complicated? just put this :
data-html='true'
Hobodave you were very close. The only thing I have changed is within the if statement that checks to see if the href attribute of the found anchor tag begins with 'http'. Instead of simply adding the $url variable which would contain the page that was passed in you must first strip it down to the host which can be done using the parse_url php function.
<?php
function crawl_page($url, $depth = 5)
{
static $seen = array();
if (isset($seen[$url]) || $depth === 0) {
return;
}
$seen[$url] = true;
$dom = new DOMDocument('1.0');
@$dom->loadHTMLFile($url);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $element) {
$href = $element->getAttribute('href');
if (0 !== strpos($href, 'http')) {
/* this is where I changed hobodave's code */
$host = "http://".parse_url($url,PHP_URL_HOST);
$href = $host. '/' . ltrim($href, '/');
}
crawl_page($href, $depth - 1);
}
echo "New Page:<br /> ";
echo "URL:",$url,PHP_EOL,"<br />","CONTENT:",PHP_EOL,$dom->saveHTML(),PHP_EOL,PHP_EOL," <br /><br />";
}
crawl_page("http://hobodave.com/", 5);
?>
I also encountered the same problem but brew install python3
does not work properly to install pip3
.
brre will throw the warning The post-install step did not complete successfully
.
It has to do with homebrew does not have permission to /usr/local
Create the directory if not exist
sudo mkdir lib
sudo mkdir Frameworks
Give the permissions inside /usr/local
to homebrew so it can access them:
sudo chown -R $(whoami) $(brew --prefix)/*
Now ostinstall python3
brew postinstall python3
This will give you a successful installation
With plain old vanilla javaScript, here's a solution to promisify an api callback.
function get(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('successful ... should call callback ... ');
callback(null, JSON.parse(xhr.responseText));
} else {
console.log('error ... callback with error data ... ');
callback(xhr, null);
}
}
});
xhr.send();
}
/**
* @function promisify: convert api based callbacks to promises
* @description takes in a factory function and promisifies it
* @params {function} input function to promisify
* @params {array} an array of inputs to the function to be promisified
* @return {function} promisified function
* */
function promisify(fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
return new Promise(function(resolve, reject) {
fn.apply(null, args.concat(function (err, result) {
if (err) reject(err);
else resolve(result);
}));
});
}
}
var get_promisified = promisify(get);
var promise = get_promisified('some_url');
promise.then(function (data) {
// corresponds to the resolve function
console.log('successful operation: ', data);
}, function (error) {
console.log(error);
});
Verified Code:
imageView.setImageResource(R.drawable.ic_arrow_up);
boolean up = true;
if (!up) {
up = true;
imageView.startAnimation(animate(up));
} else {
up = false;
imageView.startAnimation(animate(up));
}
private Animation animate(boolean up) {
Animation anim = AnimationUtils.loadAnimation(this, up ? R.anim.rotate_up : R.anim.rotate_down);
anim.setInterpolator(new LinearInterpolator()); // for smooth animation
return anim;
}
drawable/ic_arrow_up.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#3d3d3d"
android:pathData="M7.41,15.41L12,10.83l4.59,4.58L18,14l-6,-6 -6,6z"/>
</vector>
anim/rotate_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:fillEnabled="true">
<rotate
android:duration="200"
android:fromDegrees="-180"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="0" />
</set>
anim/rotate_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:fillEnabled="true">
<rotate
android:duration="200"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="180" />
</set>
I am using Debian but this solution should work fine with Ubuntu.
You have to add a line in the neo4j-service script.
Here is what I have done :
nano /etc/init.d/neo4j-service
Add « ulimit –n 40000 » just before the start-stop-daemon line in the do_start section
Note that I am using version 2.0 Enterprise edition. Hope this will help you.
what you are trying to do is more a segmentedbutton than an imagebutton list.
here http://blog.bookworm.at/2010/10/segmented-controls-in-android.html is an example on how to do so. The basic idea is to customize RadioButton instead of ImageButton, since the RadioButton will have the checked state you need
If you read the docs (http://momentjs.com/docs/#/displaying/) you can find this format:
moment("2015-01-16T12:00:00").format("hh:mm:ss a")
See JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/
It is also interesting to compare the file of the current working revision with the same file of another revision.
You can do as follows:
$ svn diff -r34 file
This code works very fast. It comes from here
Option Explicit
Private Const clOneMask = 16515072 '000000 111111 111111 111111
Private Const clTwoMask = 258048 '111111 000000 111111 111111
Private Const clThreeMask = 4032 '111111 111111 000000 111111
Private Const clFourMask = 63 '111111 111111 111111 000000
Private Const clHighMask = 16711680 '11111111 00000000 00000000
Private Const clMidMask = 65280 '00000000 11111111 00000000
Private Const clLowMask = 255 '00000000 00000000 11111111
Private Const cl2Exp18 = 262144 '2 to the 18th power
Private Const cl2Exp12 = 4096 '2 to the 12th
Private Const cl2Exp6 = 64 '2 to the 6th
Private Const cl2Exp8 = 256 '2 to the 8th
Private Const cl2Exp16 = 65536 '2 to the 16th
Public Function Encode64(sString As String) As String
Dim bTrans(63) As Byte, lPowers8(255) As Long, lPowers16(255) As Long, bOut() As Byte, bIn() As Byte
Dim lChar As Long, lTrip As Long, iPad As Integer, lLen As Long, lTemp As Long, lPos As Long, lOutSize As Long
For lTemp = 0 To 63 'Fill the translation table.
Select Case lTemp
Case 0 To 25
bTrans(lTemp) = 65 + lTemp 'A - Z
Case 26 To 51
bTrans(lTemp) = 71 + lTemp 'a - z
Case 52 To 61
bTrans(lTemp) = lTemp - 4 '1 - 0
Case 62
bTrans(lTemp) = 43 'Chr(43) = "+"
Case 63
bTrans(lTemp) = 47 'Chr(47) = "/"
End Select
Next lTemp
For lTemp = 0 To 255 'Fill the 2^8 and 2^16 lookup tables.
lPowers8(lTemp) = lTemp * cl2Exp8
lPowers16(lTemp) = lTemp * cl2Exp16
Next lTemp
iPad = Len(sString) Mod 3 'See if the length is divisible by 3
If iPad Then 'If not, figure out the end pad and resize the input.
iPad = 3 - iPad
sString = sString & String(iPad, Chr(0))
End If
bIn = StrConv(sString, vbFromUnicode) 'Load the input string.
lLen = ((UBound(bIn) + 1) \ 3) * 4 'Length of resulting string.
lTemp = lLen \ 72 'Added space for vbCrLfs.
lOutSize = ((lTemp * 2) + lLen) - 1 'Calculate the size of the output buffer.
ReDim bOut(lOutSize) 'Make the output buffer.
lLen = 0 'Reusing this one, so reset it.
For lChar = LBound(bIn) To UBound(bIn) Step 3
lTrip = lPowers16(bIn(lChar)) + lPowers8(bIn(lChar + 1)) + bIn(lChar + 2) 'Combine the 3 bytes
lTemp = lTrip And clOneMask 'Mask for the first 6 bits
bOut(lPos) = bTrans(lTemp \ cl2Exp18) 'Shift it down to the low 6 bits and get the value
lTemp = lTrip And clTwoMask 'Mask for the second set.
bOut(lPos + 1) = bTrans(lTemp \ cl2Exp12) 'Shift it down and translate.
lTemp = lTrip And clThreeMask 'Mask for the third set.
bOut(lPos + 2) = bTrans(lTemp \ cl2Exp6) 'Shift it down and translate.
bOut(lPos + 3) = bTrans(lTrip And clFourMask) 'Mask for the low set.
If lLen = 68 Then 'Ready for a newline
bOut(lPos + 4) = 13 'Chr(13) = vbCr
bOut(lPos + 5) = 10 'Chr(10) = vbLf
lLen = 0 'Reset the counter
lPos = lPos + 6
Else
lLen = lLen + 4
lPos = lPos + 4
End If
Next lChar
If bOut(lOutSize) = 10 Then lOutSize = lOutSize - 2 'Shift the padding chars down if it ends with CrLf.
If iPad = 1 Then 'Add the padding chars if any.
bOut(lOutSize) = 61 'Chr(61) = "="
ElseIf iPad = 2 Then
bOut(lOutSize) = 61
bOut(lOutSize - 1) = 61
End If
Encode64 = StrConv(bOut, vbUnicode) 'Convert back to a string and return it.
End Function
Public Function Decode64(sString As String) As String
Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
Dim lTemp As Long
sString = Replace(sString, vbCr, vbNullString) 'Get rid of the vbCrLfs. These could be in...
sString = Replace(sString, vbLf, vbNullString) 'either order.
lTemp = Len(sString) Mod 4 'Test for valid input.
If lTemp Then
Call Err.Raise(vbObjectError, "MyDecode", "Input string is not valid Base64.")
End If
If InStrRev(sString, "==") Then 'InStrRev is faster when you know it's at the end.
iPad = 2 'Note: These translate to 0, so you can leave them...
ElseIf InStrRev(sString, "=") Then 'in the string and just resize the output.
iPad = 1
End If
For lTemp = 0 To 255 'Fill the translation table.
Select Case lTemp
Case 65 To 90
bTrans(lTemp) = lTemp - 65 'A - Z
Case 97 To 122
bTrans(lTemp) = lTemp - 71 'a - z
Case 48 To 57
bTrans(lTemp) = lTemp + 4 '1 - 0
Case 43
bTrans(lTemp) = 62 'Chr(43) = "+"
Case 47
bTrans(lTemp) = 63 'Chr(47) = "/"
End Select
Next lTemp
For lTemp = 0 To 63 'Fill the 2^6, 2^12, and 2^18 lookup tables.
lPowers6(lTemp) = lTemp * cl2Exp6
lPowers12(lTemp) = lTemp * cl2Exp12
lPowers18(lTemp) = lTemp * cl2Exp18
Next lTemp
bIn = StrConv(sString, vbFromUnicode) 'Load the input byte array.
ReDim bOut((((UBound(bIn) + 1) \ 4) * 3) - 1) 'Prepare the output buffer.
For lChar = 0 To UBound(bIn) Step 4
lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3)) 'Rebuild the bits.
lTemp = lQuad And clHighMask 'Mask for the first byte
bOut(lPos) = lTemp \ cl2Exp16 'Shift it down
lTemp = lQuad And clMidMask 'Mask for the second byte
bOut(lPos + 1) = lTemp \ cl2Exp8 'Shift it down
bOut(lPos + 2) = lQuad And clLowMask 'Mask for the third byte
lPos = lPos + 3
Next lChar
sOut = StrConv(bOut, vbUnicode) 'Convert back to a string.
If iPad Then sOut = Left$(sOut, Len(sOut) - iPad) 'Chop off any extra bytes.
Decode64 = sOut
End Function
My experience with larger files sizes has been that java.nio
is faster than java.io
. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:
The buffer size. The algorithm you basically have is
My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.
Don't perform java benchmarks that read and write to the same disk.
If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.
Don't use a buffer if you don't need to.
Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.
Like other have said, use FileChannel.transferTo()
or FileChannel.transferFrom()
. The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.
The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:
Use production data and environments
Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.
My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.
What are you running on? It matters.
You need:
li.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);
Program code:
namespace Test
{
class Program
{
class Myclass
{
public string name { get; set; }
public decimal age { get; set; }
}
static void Main(string[] args)
{
var list = new List<Myclass> { new Myclass{name = "di", age = 0}, new Myclass{name = "marks", age = 0}, new Myclass{name = "grade", age = 0}};
list.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);
list.ForEach(i => Console.WriteLine(i.name + ":" + i.age));
}
}
}
Output:
di:10
marks:0
grade:0
Combining two of the previous results, we have:
int(round(some_float))
This converts a float to an integer fairly dependably.
In Spring boot, /META-INF/resources/
, /resources/
, static/
and public/
directories are available to serve static contents.
So you can create a static/
or public/
directory under resources/
directory and put your static contents there. And they will be accessible by: http://localhost:8080/your-file.ext
. (assuming the server.port
is 8080)
You can customize these directories using spring.resources.static-locations
in the application.properties
.
For example:
spring.resources.static-locations=classpath:/custom/
Now you can use custom/
folder under resources/
to serve static files.
Update:
This is also possible using java config:
@Configuration
public class StaticConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/custom/");
}
}
This confugration maps contents of custom
directory to the http://localhost:8080/static/**
url.
Since the question is how to replace ALL whitespaces
UPDATE `table`
SET `col_name` = REPLACE
(REPLACE(REPLACE(`col_name`, ' ', ''), '\t', ''), '\n', '');
For me it was the virus scanner not liking the fact I have in my exe filename multiple periods.
i.e
project.class.console.exe <- won't run
console.exe <- will run
Hope it helps.
In C++
using namespace std;
string my_string {"Hello world"};
string element_to_be_found {"Hello"};
if(my_string.find(element_to_be_found)!=string::npos)
std::cout<<"Element Found"<<std::endl;
or in a better way we can have like this
Let's say your primary key is an Integer and object you save is "ticket", then you can get it like this. When you save the object, id is always returned
//unboxing will occur here so that id here will be value type not the reference type. Now you can check id for 0 in case of save failure. like below:
int id = (Integer) session.save(ticket);
if(id==0)
your session.save call was not success.
else '
your call to session.save was successful.
The query below demonstrates use of the package and some of the information you can get.
select sys_context ( 'USERENV', 'DB_NAME' ) db_name,
sys_context ( 'USERENV', 'SESSION_USER' ) user_name,
sys_context ( 'USERENV', 'SERVER_HOST' ) db_host,
sys_context ( 'USERENV', 'HOST' ) user_host
from dual
NOTE: The parameter ‘SERVER_HOST’ is available in 10G only.
Any Oracle User that can connect to the database can run a query against “dual”. No special permissions are required and SYS_CONTEXT provides a greater range of application-specific information than “sys.v$instance”.
Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:
Mouse.OverrideCursor = Cursors.Wait;
try
{
// do stuff
}
finally
{
Mouse.OverrideCursor = null;
}
This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.
I suggest using PhantomJS. For more information, you may visit the Phantom Official Website.
As far as I know PhantomJS works only with Firefox...
After downloading PhantomJs.exe you need to import it to your project as you can see in the picture below PhantomJS.
I have placed mine inside: common ? Library ? phantomjs.exe
Now all you have to do inside your Selenium code is to change the line
browser = webdriver.Firefox()
To something like
import os
path2phantom = os.getcwd() + "\common\Library\phantomjs.exe"
browser = webdriver.PhantomJS(path2phantom)
The path to PhantomJS may be different... change as you like :)
This hack worked for me, and I'm pretty sure it will work for u too ;)
As aix mentioned - strings in Python are immutable (you cannot change them inplace).
What you are trying to do can be done in many ways:
# Copy the string
foo = 'Hello'
bar = foo
# Create a new string by joining all characters of the old string
new_string = ''.join(c for c in oldstring)
# Slice and copy
new_string = oldstring[:]
There are three major categories of cloud service models:
Software as a service (SaaS)
SaaS is a software that is centrally hosted and managed for the end customer. It's usually based on a multi-tenant architecture (a single version of the application is used for all customers) and typically is licensed through a monthly or annual subscription.
Example Office 365, Dropbox, Dynamics CRM Online are perfect examples of SaaS software, subscribers pay a monthly or annual subscription fee, and they get Exchange as a Service (online and/or desktop Outlook) or Storage as a Service (OneDrive and Dropbox).
Platform as a service (PaaS)
With PaaS, you deploy your application into an application-hosting environment (designed for building, testing, and deploying software applications) provided by the cloud service vendor. Developers have multiple ways to deploy their applications without knowing anything about what's happening in the background to supporting it.
Example Web Apps feature in Azure App Service and Azure Cloud Services (web and worker roles) are an example of PaaS.
Infrastructure as a service (IaaS)
An IaaS cloud vendor runs and manages server farms running virtualization software, enabling you to create VMs (running Windows or Linux) that run on the vendor’s infrastructure and install anything you want on it. Developers don’t have control over the hardware or virtualization software, but they have control over almost everything else. In fact, unlike PaaS, you are completely responsible for it.
References
Book: Architecting the Cloud: Design Decisions for Cloud Computing Service Models (SaaS, PaaS, and IaaS)
The answer from ast1 is very simple and useful. It works for me, thank you so much. I just want to poin it out here, so people who need this answer can find it easily. So, here is my code from registering local and remote (push) notification.
//1. In Appdelegate: didFinishLaunchingWithOptions add these line of codes
let mynotif = UNUserNotificationCenter.current()
mynotif.requestAuthorization(options: [.alert, .sound, .badge]) {(granted, error) in }//register and ask user's permission for local notification
//2. Add these functions at the bottom of your AppDelegate before the last "}"
func application(_ application: UIApplication, didRegister notificationSettings: UNNotificationSettings) {
application.registerForRemoteNotifications()//register for push notif after users granted their permission for showing notification
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device Token: \(tokenString)")//print device token in debugger console
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")//print error in debugger console
}
Do a git add -A
from the top of the working copy, take a look at git status
and/or git diff --cached
to review what you're about to do, then git commit
the result.
Ensure you run Visual Studio as an administrator.
You can directly use time.Unix function of time which converts the unix time stamp to UTC
package main
import (
"fmt"
"time"
)
func main() {
unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc
unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format
fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}
Output
unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z
Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd
This worked for me
$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");
It's probably worth noting that Powershell v3 and up, contains a cmdlet called Invoke-WebRequest that has some curl-ish capabilities. The New-WebServiceProxy and Invoke-RestMethod cmdlets are probably worth mentioning too.
I'm not sure they will fit your needs or not, but although I'm not a Windows guy, I have to say I find the object approach PS takes, a lot easier to work with than utilities such as curl, wget etc. They may be worth taking a look at
^\w{0,10}$ # allows words of up to 10 characters.
^\w{5,}$ # allows words of more than 4 characters.
^\w{5,10}$ # allows words of between 5 and 10 characters.
I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:
$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');
Looking at the phpmailer code in more detail this is the offending line:
public function SetFrom($address, $name = '',$auto=1) {
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (!self::ValidateAddress($address)) {
$this->SetError($this->Lang('invalid_address').': '. $address);
if ($this->exceptions) {
throw new phpmailerException($this->Lang('invalid_address').': '.$address);
}
echo $this->Lang('invalid_address').': '.$address;
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto) {
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
if (empty($this->Sender)) {
$this->Sender = $address;
}
}
return true;
}
Specifically this line:
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
Thanks for your help everyone!
I don't have found any solution on Internet, so I have implemented one.
The Autofilter code with criteria is then
iColNumber = 1
Dim aFilterValueArray() As Variant
Call ConstructFilterValueArray(aFilterValueArray, iColNumber, Array("A", "B", "C"))
ActiveSheet.range(sRange).AutoFilter Field:=iColNumber _
, Criteria1:=aFilterValueArray _
, Operator:=xlFilterValues
In fact, the ConstructFilterValueArray() method (not function) get all distinct values that it found in a specific column and remove all values present in last argument.
The VBA code of this method is
'************************************************************
'* ConstructFilterValueArray()
'************************************************************
Sub ConstructFilterValueArray(a() As Variant, iCol As Integer, aRemoveArray As Variant)
Dim aValue As New Collection
Call GetDistinctColumnValue(aValue, iCol)
Call RemoveValueList(aValue, aRemoveArray)
Call CollectionToArray(a, aValue)
End Sub
'************************************************************
'* GetDistinctColumnValue()
'************************************************************
Sub GetDistinctColumnValue(ByRef aValue As Collection, iCol As Integer)
Dim sValue As String
iEmptyValueCount = 0
iLastRow = ActiveSheet.UsedRange.Rows.Count
Dim oSheet: Set oSheet = Sheets("X")
Sheets("Data")
.range(Cells(1, iCol), Cells(iLastRow, iCol)) _
.AdvancedFilter Action:=xlFilterCopy _
, CopyToRange:=oSheet.range("A1") _
, Unique:=True
iRow = 2
Do While True
sValue = Trim(oSheet.Cells(iRow, 1))
If sValue = "" Then
If iEmptyValueCount > 0 Then
Exit Do
End If
iEmptyValueCount = iEmptyValueCount + 1
End If
aValue.Add sValue
iRow = iRow + 1
Loop
End Sub
'************************************************************
'* RemoveValueList()
'************************************************************
Sub RemoveValueList(ByRef aValue As Collection, aRemoveArray As Variant)
For i = LBound(aRemoveArray) To UBound(aRemoveArray)
sValue = aRemoveArray(i)
iMax = aValue.Count
For j = iMax To 0 Step -1
If aValue(j) = sValue Then
aValue.Remove (j)
Exit For
End If
Next j
Next i
End Sub
'************************************************************
'* CollectionToArray()
'************************************************************
Sub CollectionToArray(a() As Variant, c As Collection)
iSize = c.Count - 1
ReDim a(iSize)
For i = 0 To iSize
a(i) = c.Item(i + 1)
Next
End Sub
This code can certainly be improved in returning an Array of String but working with Array in VBA is not easy.
CAUTION: this code work only if you define a sheet named X because CopyToRange parameter used in AdvancedFilter() need an Excel Range !
It's a shame that Microfsoft doesn't have implemented this solution in adding simply a new enum as xlNotFilterValues ! ... or xlRegexMatch !
Looks like you are missing a leading slash. Perhaps try:
Scanner s = new Scanner(new File("/home/me/java/ex.txt"));
(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)
This the simplest way to assign an async
arrow function expression to a named variable:
const foo = async () => {
// do something
}
(Note that this is not strictly equivalent to async function foo() { }
. Besides the differences between the function
keyword and an arrow expression, the function in this answer is not "hoisted to the top".)
Just a note on this question:
I had this exact error in my React Native app when trying to build to android. All you should have to do is $ npm i
.
Adding this since this was not mentioned.
SELECT * FROM `la_schedule` WHERE date(start_date) > date('2012-11-18');
Because that's what actually works for me. Adding date() function on both comparison values.
Use PHP basename()
(PHP 4, PHP 5)
var_dump(basename('test.php', '.php'));
Outputs: string(4) "test"
It should be mentioned that since it is entirely possible to run DLL's just as any other executable, it has long been considered a security issue. As such, there have been a number of security improvements and registry hacks (sorry no longer have ref-links) that prevents running DLL's from regular user space without extra privileges.
As a good example. I recall making these hacks, but since I no longer remember what exactly I did. I can no longer run any DLLs from normal user shell environment, even though starting various Win apps from GUI works just fine.
That said, one should definitely read "Dynamic-Link Library Security" and "Best Practices to Prevent DLL Hijacking".
This should handle cases of clicking on [x] or ALT+F4
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
Environment.Exit(0);
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
}
You can use a middleware to set the default Content-Type, and set Content-Type differently for particular APIs. Here is an example:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const server = app.listen(port);
server.timeout = 1000 * 60 * 10; // 10 minutes
// Use middleware to set the default Content-Type
app.use(function (req, res, next) {
res.header('Content-Type', 'application/json');
next();
});
app.get('/api/endpoint1', (req, res) => {
res.send(JSON.stringify({value: 1}));
})
app.get('/api/endpoint2', (req, res) => {
// Set Content-Type differently for this particular API
res.set({'Content-Type': 'application/xml'});
res.send(`<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>`);
})
You can do something like this to extract the value you want from JavaScript instead of an attribute:
<a href='#' class='click'>
<span style='display:none;'>value for JavaScript</span>some text
</a>
The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.
This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):
See:
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
I had this problem, and I solved it. There was an attribute in the <%@ Page
tag named MaintainScrollPositionOnPostback
and after removing it, the error disapeared.
I added it before to prevent scrolling after each postback.
Use generic types !
class DataExtraction<T>
{
DateRangeReport dateRange;
List<Predicate> predicates;
List<string> cids;
public DataExtraction( DateRangeReport dateRange,
List<Predicate> predicates,
List<string> cids)
{
this.dateRange = dateRange;
this.predicates = predicates;
this.cids = cids;
}
}
And call it like this :
DataExtraction<AdPerformanceRow> extractor = new DataExtraction<AdPerformanceRow>(dates, predicates , cids);
Rhino.js
implements const
in addition to what was mentioned above.
From all the answers above, Björn's answer seems to be the most elegant and short. I personally used this approach many times. MAX or MIN function will do the job equally well. Complete PL/SQL follows, just the where clause should be specified.
declare v_column my_table.column%TYPE;
begin
select MIN(column) into v_column from my_table where ...;
DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;
If you have the product's ID you can use that to create a product object:
$_product = wc_get_product( $product_id );
Then from the object you can run any of WooCommerce's product methods.
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Update
Please review the Codex article on how to write your own shortcode.
Integrating the WooCommerce product data might look something like this:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Your shortcode would then look like [woocommerce_price id="99"]
You can select dropdown option value by name
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
2020 Update: An updated version of the function provided by many in this thread but now for C# 7.3 onwards:
Now you can restrict generic methods to enums types so you can write a single method extension to use it with all your enums like this:
The generic extension method:
public static string ATexto<T>(this T enumeración) where T : struct, Enum {
var tipo = enumeración.GetType();
return tipo.GetMember(enumeración.ToString())
.Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == tipo).First()
.GetCustomAttribute<DisplayAttribute>()?.Name ?? enumeración.ToString();
}
The enum:
public enum TipoImpuesto {
IVA, INC, [Display(Name = "IVA e INC")]IVAeINC, [Display(Name = "No aplica")]NoAplica };
How to use it:
var tipoImpuesto = TipoImpuesto.IVAeINC;
var textoTipoImpuesto = tipoImpuesto.ATexto(); // Prints "IVA e INC".
Bonus, Enums with Flags: If you are dealing with normal enums the function above is enough, but if any of your enums can take multiple values with the use of flags then you will need to modify it like this (This code uses C#8 features):
public static string ATexto<T>(this T enumeración) where T : struct, Enum {
var tipo = enumeración.GetType();
var textoDirecto = enumeración.ToString();
string obtenerTexto(string textoDirecto) => tipo.GetMember(textoDirecto)
.Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == tipo)
.First().GetCustomAttribute<DisplayAttribute>()?.Name ?? textoDirecto;
if (textoDirecto.Contains(", ")) {
var texto = new StringBuilder();
foreach (var textoDirectoAux in textoDirecto.Split(", ")) {
texto.Append($"{obtenerTexto(textoDirectoAux)}, ");
}
return texto.ToString()[0..^2];
} else {
return obtenerTexto(textoDirecto);
}
}
The enum with flags:
[Flags] public enum TipoContribuyente {
[Display(Name = "Común")] Común = 1,
[Display(Name = "Gran Contribuyente")] GranContribuyente = 2,
Autorretenedor = 4,
[Display(Name = "Retenedor de IVA")] RetenedorIVA = 8,
[Display(Name = "Régimen Simple")] RégimenSimple = 16 }
How to use it:
var tipoContribuyente = TipoContribuyente.RetenedorIVA | TipoContribuyente.GranContribuyente;
var textoAux = tipoContribuyente.ATexto(); // Prints "Gran Contribuyente, Retenedor de IVA".
From the mysql
man page:
You can execute SQL statements in a script file (batch file) like this:
shell> mysql db_name < script.sql > output.tab
Put the query in script.sql
and run it.
If you want it to be more generic and independent, you can use cookie. Iframe content can set a cookie. With jquery.cookie and a timer (or in this case javascript timer), you can check if the cookie is set each second or so.
//token should be a unique random value which is also sent to ifame to get set
iframeLoadCheckTimer = window.setInterval(function () {
cookieValue = $.cookie('iframeToken');
if (cookieValue == token)
{
window.clearInterval(iframeLoadCheckTimer );
$.cookie('iframeToken', null, {
expires: 1,
path: '/'
});
}
}, 1000);
Additionally, in order for ForeColor to be obeyed on a TextBox marked ReadOnly, you must explicitly set the BackColor. If you want to have it still use the default BackColor, you have to make the set explicit, as the designer is too smart for its own good here. It is sufficient to set the BackColor to its current value. I do this in the Load event for the form, like so:
private void FormFoo_Load(...) {
txtFoo.BackColor = txtFoo.BackColor;
}
You can split the string into characters and filter it.
<?php
function filter_alphanum($string) {
$characters = str_split($string);
$alphaNumeric = array_filter($characters,"ctype_alnum");
return join($alphaNumeric);
}
$res = filter_alphanum("a!bc!#123");
print_r($res); // abc123
?>
I use this one:
import { Directive, ElementRef, HostListener, Input, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[ngModel][onlyNumber]',
host: {
"(input)": 'onInputChange($event)'
}
})
export class OnlyNumberDirective {
@Input() onlyNumber: boolean;
@Output() ngModelChange: EventEmitter<any> = new EventEmitter()
constructor(public el: ElementRef) {
}
public onInputChange($event){
if ($event.target.value == '-') {
return;
}
if ($event.target.value && $event.target.value.endsWith('.')) {
return;
}
$event.target.value = this.parseNumber($event.target.value);
$event.target.dispatchEvent(new Event('input'));
}
@HostListener('blur', ['$event'])
public onBlur(event: Event) {
if (!this.onlyNumber) {
return;
}
this.el.nativeElement.value = this.parseNumber(this.el.nativeElement.value);
this.el.nativeElement.dispatchEvent(new Event('input'));
}
private parseNumber(input: any): any {
let trimmed = input.replace(/[^0-9\.-]+/g, '');
let parsedNumber = parseFloat(trimmed);
return !isNaN(parsedNumber) ? parsedNumber : '';
}
}
and usage is following
<input onlyNumbers="true" ... />
This is case, when object are better - because you can set up your object to hold x and y , set up defaults etc.
Approach with array is near to create object ( In fact, object is bunch of parameters and functions which will work over object, and function taking array will work over some bunch ov parameters )
Cerainly you can always do some tricks to set null or something like this as default
Firstly name
isn't a valid attribute of an option
element. Instead you could use a data
parameter, like this:
<option value="foo" data-name="bar">Foo Bar</option>
The main issue you have is that the JS is looking at the name
attribute of the select
element, not the chosen option. Try this:
$('#band_type_choices').on('change', function() {
$('.checkboxlist').hide();
$('#checkboxlist_' + $('option:selected', this).data("name")).css("display", "block");
});
Note the option:selected
selector within the context of the select
which raised the change event.
you can use the query options {raw: true}
to return the raw result. Your query should like follows:
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
})
also if you have associations with include
that gets flattened. So, we can use another parameter nest:true
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw: true,
nest: true,
})
Watch that your file name doesn't have :
in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt
and then scp no-colons.txt server:
then don't forget to mv
back on the server. Just in case this was an issue.
Consider using HashSet<T>
Class for the sake of lookup performance:
This method is an O(1) operation.
For example:
class PrinterInstaller
{
private static readonly HashSet<string> PrinterNames = new HashSet<string>
{
"jupiter", "neptune", "pangea", "mercury", "sonic"
};
public void Setup(string printerName)
{
if (!PrinterNames.Contains(printerName))
{
throw new ArgumentException("Unknown printer name", "printerName");
}
// ...
}
}
Probably you should use something like this
npm ci
Instead of using npm install
if you don't want to change the version of your package.
According to the official documentation, both npm install
and npm ci
install the dependencies which are needed for the project.
The main difference is,
npm install
does install the packages takingpackge.json
as a reference. Where in the case ofnpm ci
, it does install the packages takingpackage-lock.json
as a reference, making sure every time the exact package is installed.
npm install -g npm@4
This will install the latest version on the major release 4, no no need to specify version number. Replace 4 with whatever major release you want.
If you are wondering how to get your domain to appear as
www.mydomain.com
instead of redirecting thewww
request tomydomain.com
, try this:
CNAME file on gh-pages branch will have one line:
www.mydomain.com
(instead of mydomain.com
)
No matter your preference on redirection (in other words, no matter what is in your CNAME file on the gs-pages branch), with your DNS provider, you should set it up like this:
A @ 192.30.252.154
A @ 192.30.252.153
CNAME www username.github.io
Kotlin way
editText.filters = arrayOf(InputFilter.LengthFilter(maxLength))
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
The short version
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://almondmendoza.com/android-applications/")));
should work as well...
A generic way to copy arbitrary files is to utilize Maven Wagon transport abstraction. It can handle various destinations via protocols like file
, HTTP
, FTP
, SCP
or WebDAV
.
There are a few plugins that provide facilities to copy files through the use of Wagon
. Most notable are:
There is the deploy-file
goal. It it quite inflexible but can get the job done:
mvn deploy:deploy-file -Dfile=/path/to/your/file.ext -DgroupId=foo
-DartifactId=bar -Dversion=1.0 -Durl=<url> -DgeneratePom=false
Significant disadvantage to using Maven Deploy Plugin
is that it is designated to work with Maven repositories. It assumes particular structure and metadata. You can see that the file is placed under foo/bar/1.0/file-1.0.ext
and checksum files are created. There is no way around this.
Use the upload-single
goal:
mvn org.codehaus.mojo:wagon-maven-plugin:upload-single
-Dwagon.fromFile=/path/to/your/file.ext -Dwagon.url=<url>
The use of Wagon Maven Plugin
for copying is straightforward and seems to be the most versatile.
In the examples above <url>
can be of any supported protocol. See the list of existing Wagon Providers. For example
file:///copy/to
SSH
: scp://host:22/copy/to
The examples above pass plugin parameters in the command line. Alternatively, plugins can be configured directly in POM
. Then the invocation will simply be like mvn deploy:deploy-file@configured-execution-id
. Or it can be bound to particular build phase.
Please note that for protocols like SCP
to work you will need to define an extension in your POM
:
<build>
[...]
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh</artifactId>
<version>2.12</version>
</extension>
</extensions>
If the destination you are copying to requires authentication, credentials can be provided via Server
settings. repositoryId
/serverId
passed to the plugins must match the server defined in the settings.
select
CONCAT(CAST(CREATEDATE AS DATE),' ',datepart(hour,createdate),':',ROUNd(CAST((CAST((CAST(DATEPART(MINUTE,CREATEDATE) AS DECIMAL (18,4)))/5 AS INT)) AS DECIMAL (18,4))/12*60,2)) AS '5MINDATE'
,count(something)
from TABLE
group by CONCAT(CAST(CREATEDATE AS DATE),' ',datepart(hour,createdate),':',ROUNd(CAST((CAST((CAST(DATEPART(MINUTE,CREATEDATE) AS DECIMAL (18,4)))/5 AS INT)) AS DECIMAL (18,4))/12*60,2))
This is a supplement answer related to the OP:
An easy and reliable solution to add Javadocs comments in Eclipse:
To use this tool, right-click on class and click on JAutodoc.
This will do the job:
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
Read about request objects that your views receive: https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects
Also your hidden field needs a reliable name and then a value:
<input type="hidden" name="title" value="{{ source.title }}">
Then in a view:
request.POST.get("title", "")
I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as
KAPACITOR_BASE_URL: http://kapacitor:9092
In above http://[**kapacitor**]:9092
would not resolve to http://172.20.0.2:9092
I resolved the static IPs issues using subnetting configurations.
version: "3.3"
networks:
frontend:
ipam:
config:
- subnet: 172.20.0.0/24
services:
db:
image: postgres:9.4.4
networks:
frontend:
ipv4_address: 172.20.0.5
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:latest
networks:
frontend:
ipv4_address: 172.20.0.6
ports:
- "6379"
influxdb:
image: influxdb:latest
ports:
- "8086:8086"
- "8083:8083"
volumes:
- ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
- ../influxdb/inxdb:/var/lib/influxdb
networks:
frontend:
ipv4_address: 172.20.0.4
environment:
INFLUXDB_HTTP_AUTH_ENABLED: "false"
INFLUXDB_ADMIN_ENABLED: "true"
INFLUXDB_USERNAME: "db_username"
INFLUXDB_PASSWORD: "12345678"
INFLUXDB_DB: db_customers
kapacitor:
image: kapacitor:latest
ports:
- "9092:9092"
networks:
frontend:
ipv4_address: 172.20.0.2
depends_on:
- influxdb
volumes:
- ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
- ../kapacitor/kapdb:/var/lib/kapacitor
environment:
KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086
web:
build: .
environment:
RAILS_ENV: $RAILS_ENV
command: bundle exec rails s -b 0.0.0.0
ports:
- "3000:3000"
networks:
frontend:
ipv4_address: 172.20.0.3
links:
- db
- kapacitor
depends_on:
- db
volumes:
- .:/var/app/current
environment:
DATABASE_URL: postgres://postgres@db
DATABASE_USERNAME: postgres
DATABASE_PASSWORD: postgres
INFLUX_URL: http://influxdb:8086
INFLUX_USER: db_username
INFLUX_PWD: 12345678
KAPACITOR_BASE_URL: http://172.20.0.2:9092
KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000
volumes:
postgres_data:
A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.
For example, If I do this:
Integer myInteger = null;
int n = myInteger.intValue();
The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.
What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!
Go to Header and select Content-Type
= application/json
then go to body and select raw
and then pass an array.
You could also use Three20 Library that contains a styleable PageControl and dozens of other helpful UI Controls and Abstractions.
Can you add an A tag to the row?
<tr><td>
<a href="./link.htm"></a>
</td></tr>
Is this what you're asking?
When root permissions are required for the destination file, use |sudo tee
instead of >
:
cat << 'EOF' |sudo tee /tmp/yourprotectedfilehere
The variable $FOO will *not* be interpreted.
EOF
cat << "EOF" |sudo tee /tmp/yourprotectedfilehere
The variable $FOO *will* be interpreted.
EOF