Maybe it's a coincidence that the column order you want happens to have column names in descending alphabetical order. Since that's the case you could just do:
df<-df[,order(colnames(df),decreasing=TRUE)]
That's what I use when I have large files with many columns.
SELECT name, salary
FROM EMPLOYEES
WHERE salary = (
SELECT DISTINCT salary
FROM EMPLOYEES
ORDER BY salary DESC
LIMIT 1 , 1 )
This is the best way I have found :
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Let's first dynamically add a fragment into a frame container
getSupportFragmentManager().beginTransaction().
replace(R.id.flContainer, new DemoFragment(), "SOMETAG").
commit();
// Now later we can lookup the fragment by tag
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentByTag("SOMETAG");
}
}
}
.contextmenu method :-
Try as follows
<div id="wrap">Right click</div>
<script>
$('#wrap').contextmenu(function() {
alert("Right click");
});
</script>
.mousedown method:-
$('#wrap').mousedown(function(event) {
if(event.which == 3){
alert('Right Mouse button pressed.');
}
});
Case-statements automatically fall through if you don't specify otherwise (by writing break). Therefor you can write
switch(myvar)
{
case 2:
case 5:
{
//your code
break;
}
// etc... }
<script type="text/javascript">
window.open ('YourNewPage.htm','_self',false)
</script>
see reference: http://www.w3schools.com/jsref/met_win_open.asp
You can do this without additional tools in VBScript:
Do Until WScript.StdIn.AtEndOfStream
WScript.StdOut.WriteLine WScript.StdIn.ReadLine
Loop
Put the above lines in a file unix2dos.vbs
and run it like this:
cscript //NoLogo unix2dos.vbs <C:\path\to\input.txt >C:\path\to\output.txt
or like this:
type C:\path\to\input.txt | cscript //NoLogo unix2dos.vbs >C:\path\to\output.txt
You can also do it in PowerShell:
(Get-Content "C:\path\to\input.txt") -replace "`n", "`r`n" |
Set-Content "C:\path\to\output.txt"
which could be further simplified to this:
(Get-Content "C:\path\to\input.txt") | Set-Content "C:\path\to\output.txt"
The above statement works without an explicit replacement, because Get-Content
implicitly splits input files at any kind of linebreak (CR, LF, and CR-LF), and Set-Content
joins the input array with Windows linebreaks (CR-LF) before writing it to a file.
As an unordered collection type, set([8, 1, 6])
is equivalent to set([1, 6, 8])
.
While it might be nicer to display the set contents in sorted order, that would make the repr()
call more expensive.
Internally, the set
type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.
To produce the repr()
output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.
Alpine uses the command adduser
and addgroup
for creating users and groups (rather than useradd
and usergroup
).
FROM alpine:latest
# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Tell docker that all future commands should run as the appuser user
USER appuser
The flags for adduser
are:
Usage: adduser [OPTIONS] USER [GROUP] Create new user, or add USER to GROUP -h DIR Home directory -g GECOS GECOS field -s SHELL Login shell -G GRP Group -S Create a system user -D Don't assign a password -H Don't create home directory -u UID User id -k SKEL Skeleton directory (/etc/skel)
Example for Apache Commons Lang:
import org.apache.commons.lang.SystemUtils;
Float version = SystemUtils.JAVA_VERSION_FLOAT;
if (version < 1.4f) {
// legacy
} else if (SystemUtils.IS_JAVA_1_5) {
// 1.5 specific code
} else if (SystemUtils.isJavaVersionAtLeast(1.6f)) {
// 1.6 compatible code
} else {
// dodgy clause to catch 1.4 :)
}
Followed this.
I have solved it with adding some key in info.plist. The steps I followed are:
Opened my Projects info.plist
file
Added a Key called NSAppTransportSecurity
as a Dictionary
.
NSAllowsArbitraryLoads
as Boolean
and set its value to YES
as like following image.
Clean the Project and Now Everything is Running fine as like before.
Ref Link.
jQuery has a toggleClass function:
<button class="switch">Click me</button>
<div class="text-block collapsed pressed">some text</div>
<script>
$('.switch').on('click', function(e) {
$('.text-block').toggleClass("collapsed pressed"); //you can list several class names
e.preventDefault();
});
</script>
<script type="text/javascript">
var IdAry=['reports1'];
window.onload=function() {
for (var zxc0=0;zxc0<IdAry.length;zxc0++){
var el=document.getElementById(IdAry[zxc0]);
if (el){
el.onmouseover=function() {
changeText(this,'hide','show')
}
el.onmouseout=function() {
changeText(this,'show','hide');
}
}
}
}
function changeText(obj,cl1,cl2) {
obj.getElementsByTagName('SPAN')[0].className=cl1;
obj.getElementsByTagName('SPAN')[1].className=cl2;
}
</script>
ur html should look like this
<p id="reports1">
<span id="span1">Test Content</span>
<span class="hide">
<br /> <br /> This is the content that appears when u hover on the it
</span>
</p>
It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:
List<String> lines = Files.readAllLines(Paths.get("src/test/resources/foo.txt"));
lines.forEach(System.out::println);
Let me present to you a glorious but terrifying hack:
import types
def _obj():
return lambda: None
def LET(bindings, body, env=None):
'''Introduce local bindings.
ex: LET(('a', 1,
'b', 2),
lambda o: [o.a, o.b])
gives: [1, 2]
Bindings down the chain can depend on
the ones above them through a lambda.
ex: LET(('a', 1,
'b', lambda o: o.a + 1),
lambda o: o.b)
gives: 2
'''
if len(bindings) == 0:
return body(env)
env = env or _obj()
k, v = bindings[:2]
if isinstance(v, types.FunctionType):
v = v(env)
setattr(env, k, v)
return LET(bindings[2:], body, env)
You can now use this LET
form as such:
map(lambda x: LET(('y', x + 1,
'z', x - 1),
lambda o: o.y * o.z),
[1, 2, 3])
which gives: [0, 3, 8]
See, if you are creating an intent within a listiner in some method
override onClick (View v).
then call the context through this view as well:
v.getContext ()
There will not even need SetFlags ...
Moving my comment as an answer, as requested by @lycono
If you need to do this with root privileges, do it this way:
sudo sh -c 'echo "some data for the file" >> fileName'
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
All in all, I'd say that MD5 in addition to the file name is absolutely safe. SHA-256 would just be slower and harder to handle because of its size.
You could also use something less secure than MD5 without any problem. If nobody tries to hack your file integrity this is safe, too.
The problem in your case is the ItemSerializer is missing the method handledType() which needs to be overridden from JsonSerializer
public class ItemSerializer extends JsonSerializer<Item> {
@Override
public void serialize(Item value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeNumberField("itemNr", value.itemNr);
jgen.writeNumberField("createdBy", value.user.id);
jgen.writeEndObject();
}
@Override
public Class<Item> handledType()
{
return Item.class;
}
}
Hence you are getting the explicit error that handledType() is not defined
Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType()
Hope it helps someone. Thanks for reading my answer.
For Windows Use this class
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
This worked for me when I got the same error message...
mvn install deploy
Edit:
use jquery plugin: jquery.sizes.js
$('img').margin() or $('img').padding()
return:
{bottom: 10 ,left: 4 ,top: 0 ,right: 5}
get value:
$('img').margin().top
I had the same problem and it kept me up for days. At the end, I realised that my URL pointing to the app was wrong altogether. example:
URL: 'http://api.example.com/'
URL: 'https://api.example.com/'.
If it's http or https verify.
Check the redirecting URL and make sure it's the same thing you're passing along.
If your DBMS supports the notation, you need a separate set of parentheses for each row:
INSERT INTO Data(Col1) VALUES ('Hello'), ('World');
The cross-referenced question shows examples for inserting into two columns.
Alternatively, every SQL DBMS supports the notation using separate statements, one for each row to be inserted:
INSERT INTO Data (Col1) VALUES ('Hello');
INSERT INTO Data (Col1) VALUES ('World');
if you want to encode or decode an array from or to JSON you can use these functions
$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);
json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string
with json_decode you can take the results from the API and only output what you want, for example:
echo $myArray['payload']['ign'];
FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.
Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).
Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.
Here is working code that defines a subroutine make_3d_array
to allocate a multidimensional 3D array with N1
, N2
and N3
elements in each dimension, and then populates it with random numbers. You can use the notation A[i][j][k]
to access its elements.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Method to allocate a 2D array of floats
float*** make_3d_array(int nx, int ny, int nz) {
float*** arr;
int i,j;
arr = (float ***) malloc(nx*sizeof(float**));
for (i = 0; i < nx; i++) {
arr[i] = (float **) malloc(ny*sizeof(float*));
for(j = 0; j < ny; j++) {
arr[i][j] = (float *) malloc(nz * sizeof(float));
}
}
return arr;
}
int main(int argc, char *argv[])
{
int i, j, k;
size_t N1=10,N2=20,N3=5;
// allocates 3D array
float ***ran = make_3d_array(N1, N2, N3);
// initialize pseudo-random number generator
srand(time(NULL));
// populates the array with random numbers
for (i = 0; i < N1; i++){
for (j=0; j<N2; j++) {
for (k=0; k<N3; k++) {
ran[i][j][k] = ((float)rand()/(float)(RAND_MAX));
}
}
}
// prints values
for (i=0; i<N1; i++) {
for (j=0; j<N2; j++) {
for (k=0; k<N3; k++) {
printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]);
}
}
}
free(ran);
}
find /dir -type f -follow -print
-type f
means it will display real files (not symlinks)
-follow
means it will follow your directory symlinks
-print
will cause it to display the filenames.
If you want a ls type display, you can do the following
find /dir -type f -follow -print|xargs ls -l
Works on Django 3
I found I believe good way, I have the base.html in root folder, and all other html files in App folders, I settings.py
import os
# This settings are to allow store templates,static and media files in root folder
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# This is default path from Django, must be added
#AFTER our BASE_DIR otherwise DB will be broken.
BASE_DIR = Path(__file__).resolve().parent.parent
# add your apps to Installed apps
INSTALLED_APPS = [
'main',
'weblogin',
..........
]
# Now add TEMPLATE_DIR to 'DIRS' where in TEMPLATES like bellow
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR, BASE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# On end of Settings.py put this refferences to Static and Media files
STATICFILES_DIRS = [STATIC_DIR,]
STATIC_URL = '/static/'
MEDIA_ROOT = [MEDIA_DIR,]
MEDIA_URL = '/media/'
If you have problem with Database, please check if you put the original BASE_DIR bellow the new BASE_DIR otherwise change
# Original
'NAME': BASE_DIR / 'db.sqlite3',
# to
'NAME': os.path.join(BASE_DIR,'db.sqlite3'),
Django now will be able to find the HTML and Static files both in the App folders and in Root folder without need of adding the name of App folder in front of the file.
Struture:
-DjangoProject
-static(css,JS ...)
-templates(base.html, ....)
-other django files like (manage.py, ....)
-App1
-templates(index1.html, other html files can extend now base.html too)
-other App1 files
-App2
-templates(index2.html, other html files can extend now base.html too)
-other App2 files
I think that there isn't a official naming convention to JSON, but you can follow some industry leaders to see how it is working.
Google, which is one of the biggest IT company of the world, has a JSON style guide: https://google.github.io/styleguide/jsoncstyleguide.xml
Taking advantage, you can find other styles guide, which Google defines, here: https://github.com/google/styleguide
Another option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.
>>> n = 5 #length of list
>>> list = [None] * n #populate list, length n with n entries "None"
>>> print(list)
[None, None, None, None, None]
>>> list.append(1) #append 1 to right side of list
>>> list = list[-n:] #redefine list as the last n elements of list
>>> print(list)
[None, None, None, None, 1]
>>> list.append(1) #append 1 to right side of list
>>> list = list[-n:] #redefine list as the last n elements of list
>>> print(list)
[None, None, None, 1, 1]
>>> list.append(1) #append 1 to right side of list
>>> list = list[-n:] #redefine list as the last n elements of list
>>> print(list)
[None, None, 1, 1, 1]
or with really nothing in the list to begin with:
>>> n = 5 #length of list
>>> list = [] # create list
>>> print(list)
[]
>>> list.append(1) #append 1 to right side of list
>>> list = list[-n:] #redefine list as the last n elements of list
>>> print(list)
[1]
on the 4th iteration of append:
>>> list.append(1) #append 1 to right side of list
>>> list = list[-n:] #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1]
5 and all subsequent:
>>> list.append(1) #append 1 to right side of list
>>> list = list[-n:] #redefine list as the last n elements of list
>>> print(list)
[1,1,1,1,1]
As mentioned if-else
would be better in this case, where you will be handling a range:
if(number >= 1 && number <= 4)
{
//do something;
}
else if(number >= 5 && number <= 9)
{
//do something else;
}
It's a very bad idea to directly display any text on an irregular and ever changing background. No matter what you do, some of the time the text will be hard to read.
The best design would be to have the labels on a constant background with the images changing behind that.
You can set the labels background color from clear to white and set the from alpha to 50.0 you get a nice translucent effect. The only problem is that the label's background is a stark rectangle.
To get a label with a background with rounded corners you can use a button with user interaction disabled but the user might mistake that for a button.
The best method would be to create image of the label background you want and then put that in an imageview and put the label with the default transparent background onto of that.
Plain UIViews do not have an image background. Instead, you should make a UIImageView your main view and then rotate the images though its image property. If you set the UIImageView's mode to "Scale to fit" it will scale any image to fit the bounds of the view.
Change the database.php file from
$db['default']['dbdriver'] = 'mysql';
to
$db['default']['dbdriver'] = 'mysqli';
It should be
var app = angular.module("MesaViewer", []);
This is the syntax you need to define a module and you need the array to show it has no dependencies.
You use the
angular.module("MesaViewer");
syntax when you are referencing a module you've already defined.
Change that import to
from matplotlib.pyplot import *
Note that this style of imports (from X import *
) is generally discouraged. I would recommend using the following instead:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
There are more than a few gateways out there, but I am not aware of a reliable gateway that is free. Most gateways like PayPal will provide you APIs that will allow you to process credit cards, as well as do things like void, charge, or refund.
The other thing you need to worry about is the coming of PCI compliance which basically says if you are not compliant, you (or the company you work for) will be liable by your Merchant Bank and/or Card Vendor for not being compliant by July of 2010. This will impose large fines on you and possibly revoke the ability for you to process credit cards.
All that being said companies like PayPal have a PHP SDK:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_download_sdks
Authorize.Net:
http://developer.authorize.net/samplecode/
Those are two of the more popular ones for the United States.
For PCI Info see:
You can change the color directly in XML. Use buttonTint
for the box: (as of API level 23)
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="@color/CHECK_COLOR" />
You can also do this using appCompatCheckbox v7
for older API levels:
<android.support.v7.widget.AppCompatCheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:buttonTint="@color/COLOR_HERE" />
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
A portable solution could use getc
.
#include <stdio.h>
char buffer[MAX_FILE_SIZE];
size_t i;
for (i = 0; i < MAX_FILE_SIZE; ++i)
{
int c = getc(fp);
if (c == EOF)
{
buffer[i] = 0x00;
break;
}
buffer[i] = c;
}
If you don't want to have a MAX_FILE_SIZE
macro or if it is a big number (such that buffer
would be to big to fit on the stack), use dynamic allocation.
BalusC's list is solid. One additional way this field frequently appears empty is when the user is behind a proxy server. This is similar to being behind a firewall but is slightly different so I wanted to mention it for the sake of completeness.
To completely remove the ul
default style:
list-style-type: none;
margin: 0;
margin-block-start: 0;
margin-block-end: 0;
margin-inline-start: 0;
margin-inline-end: 0;
padding-inline-start: 0;
Using Pygrok, you can define abstracted extensions to the Regular Expression syntax.
The custom patterns can be included in your regex in the format %{PATTERN_NAME}
.
You can also create a label for that pattern, by separating with a colon: %s{PATTERN_NAME:matched_string}
. If the pattern matches, the value will be returned as part of the resulting dictionary (e.g. result.get('matched_string')
)
For example:
from pygrok import Grok
input_string = 'monkey 2010-07-10 love banana'
date_pattern = '%{YEAR:year}-%{MONTHNUM:month}-%{MONTHDAY:day}'
grok = Grok(date_pattern)
print(grok.match(input_string))
The resulting value will be a dictionary:
{'month': '07', 'day': '10', 'year': '2010'}
If the date_pattern does not exist in the input_string, the return value will be None
. By contrast, if your pattern does not have any labels, it will return an empty dictionary {}
References:
You should use this example with AUTHID CURRENT_USER :
CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
AUTHID CURRENT_USER
IS
SEQ_NAME VARCHAR2 (100);
FINAL_QUERY VARCHAR2 (100);
COUNT_NUMBER NUMBER := 0;
cur_id NUMBER;
BEGIN
SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;
SELECT COUNT (*)
INTO COUNT_NUMBER
FROM USER_SEQUENCES
WHERE SEQUENCE_NAME = SEQ_NAME;
DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);
IF COUNT_NUMBER = 0
THEN
--DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
-- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
-- ELSE
SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
INTO FINAL_QUERY
FROM DUAL;
DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
cur_id := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
DBMS_SQL.CLOSE_CURSOR (cur_id);
-- EXECUTE IMMEDIATE FINAL_QUERY;
END IF;
COMMIT;
END;
/
I don't think the Chrome Developer tools pretty print XHR content. See: Viewing HTML response from Ajax call through Chrome Developer tools?
private void StudentForm_Load(object sender, EventArgs e)
{
string q = @"SELECT [BatchID] FROM [Batch]"; //BatchID column name of Batch table
SqlDataReader reader = DB.Query(q);
while (reader.Read())
{
cbsb.Items.Add(reader["BatchID"].ToString()); //cbsb is the combobox name
}
}
Use something like the following on the server side:
http.createServer(function (request, response) {
if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
// handle async request
var u = url.parse(request.url, true); //not needed
response.writeHead(200, {'content-type':'text/json'})
response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10
} else {
// handle sync request (by server index.html)
if (request.url == '/') {
response.writeHead(200, {'content-type': 'text/html'})
util.pump(fs.createReadStream('index.html'), response)
}
else
{
// 404 error
}
}
}).listen(31337)
Using asp.net, I believe you can do it this way :
myTextBox.Attributes.Add("readonly","readonly")
Simple:
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0" /
>
Cheers!
Running in Debug Mode
When you're developing and debugging an application, you will typically run with the debug attribute in the web.config file set to true and your DLLs compiled in debug mode. However, before you deploy your application to test or to production, you should compile your components in release mode and set the debug attribute to false.
ASP.NET works differently on many levels when running in debug mode. In fact, when you are running in debug mode, the GC will allow your objects to remain alive longer (until the end of the scope) so you will always see higher memory usage when running in debug mode.
Another often unrealized side-effect of running in debug mode is that client scripts served via the webresource.axd and scriptresource.axd handlers will not be cached. That means that each client request will have to download any scripts (such as ASP.NET AJAX scripts) instead of taking advantage of client-side caching. This can lead to a substantial performance hit.
Included page:
<!-- opening and closing tags of included page -->
<ui:composition ...>
</ui:composition>
Including page:
<!--the inclusion line in the including page with the content-->
<ui:include src="yourFile.xhtml"/>
ui:composition
as shown above.ui:include
in the including xhtml file as also shown above.I had a similar problem after starting a new IntelliJ project. I found that the "module compile output path" for my module was not properly specified. When I assigned the path in the module's "compile output path" to the proper location, the problem was solved. The compile output path is assigned in the Project settings. Under Modules, select the module involved and select the Paths tab...
Paths tab in the Project Settings | Modules dialog
...I sent the compiler output to a folder named "output" that is present in the parent Project folder.
It is not possible to find the number of elements in an array unless it is a character array. Consider the below example:
int main()
{
int arr[100]={1,2,3,4,5};
int size = sizeof(arr)/sizeof(arr[0]);
printf("%d", size);
return 1;
}
The above value gives us value 100 even if the number of elements is five. If it is a character array, you can search linearly for the null string at the end of the array and increase the counter as you go through.
As far as I know there is not an easy way to do this since Javascript/JQuery does not have access to the local filesystem. There are some new features in html 5 that allows you to check certain meta data such as file size but I'm not sure if you can actually get the image dimensions.
Here is an article I found regarding the html 5 features, and a work around for IE that involves using an ActiveX control. http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html
I cobbled together a 'dynamic' struct class today, had a look tonight and someone has written something similar with better handling of constructor parameters, it might be worth a look:
http://code.activestate.com/recipes/577160-php-struct-port/
One of the comments on this page mentions an interesting thing in PHP - apparently you're able to cast an array as an object, which lets you refer to array elements using the arrow notation, as you would with a Struct pointer in C. The comment's example was as follows:
$z = array('foo' => 1, 'bar' => true, 'baz' => array(1,2,3));
//accessing values as properties
$y = (object)$z;
echo $y->foo;
I haven't tried this myself yet, but it may be that you could get the desired notation by just casting - if that's all you're after. These are of course 'dynamic' data structures, just syntactic sugar for accessing key/value pairs in a hash.
If you're actually looking for something more statically typed, then ASpencer's answer is the droid you're looking for (as Obi-Wan might say.)
When you a declare a static
variable at file scope, then that variable is only available in that particular file (technically, the *translation unit, but let's not complicate this too much). For example:
a.cpp
static int x = 7;
void printax()
{
cout << "from a.cpp: x=" << x << endl;
}
b.cpp
static int x = 9;
void printbx()
{
cout << "from b.cpp: x=" << x << endl;
}
main.cpp:
int main(int, char **)
{
printax(); // Will print 7
printbx(); // Will print 9
return 0;
}
For a local variable, static
means that the variable will be zero-initialized and retain its value between calls:
unsigned int powersoftwo()
{
static unsigned lastpow;
if(lastpow == 0)
lastpow = 1;
else
lastpow *= 2;
return lastpow;
}
int main(int, char **)
{
for(int i = 0; i != 10; i++)
cout << "2^" << i << " = " << powersoftwo() << endl;
}
For class variables, it means that there is only a single instance of that variable that is shared among all members of that class. Depending on permissions, the variable can be accessed from outside the class using its fully qualified name.
class Test
{
private:
static char *xxx;
public:
static int yyy;
public:
Test()
{
cout << this << "The static class variable xxx is at address "
<< static_cast<void *>(xxx) << endl;
cout << this << "The static class variable yyy is at address "
<< static_cast<void *>(&y) << endl;
}
};
// Necessary for static class variables.
char *Test::xxx = "I'm Triple X!";
int Test::yyy = 0;
int main(int, char **)
{
Test t1;
Test t2;
Test::yyy = 666;
Test t3;
};
Marking a non-class function as static
makes the function only accessible from that file and inaccessible from other files.
a.cpp
static void printfilename()
{ // this is the printfilename from a.cpp -
// it can't be accessed from any other file
cout << "this is a.cpp" << endl;
}
b.cpp
static void printfilename()
{ // this is the printfilename from b.cpp -
// it can't be accessed from any other file
cout << "this is b.cpp" << endl;
}
For class member functions, marking them as static
means that the function doesn't need to be called on a particular instance of an object (i.e. it doesn't have a this
pointer).
class Test
{
private:
static int count;
public:
static int GetTestCount()
{
return count;
};
Test()
{
cout << this << "Created an instance of Test" << endl;
count++;
}
~Test()
{
cout << this << "Destroyed an instance of Test" << endl;
count--;
}
};
int Test::count = 0;
int main(int, char **)
{
Test *arr[10] = { NULL };
for(int i = 0; i != 10; i++)
arr[i] = new Test();
cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;
// now, delete them all except the first and last!
for(int i = 1; i != 9; i++)
delete arr[i];
cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;
delete arr[0];
cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;
delete arr[9];
cout << "There are " << Test::GetTestCount() << " instances of the Test class!" << endl;
return 0;
}
You can print in simple way.
Use below to print 2D array
int[][] array = new int[rows][columns];
System.out.println(Arrays.deepToString(array));
Use below to print 1D array
int[] array = new int[size];
System.out.println(Arrays.toString(array));
we can add attribute width directly to th
eg:
<ng-container matColumnDef="position" >
<th mat-header-cell *matHeaderCellDef width ="20%"> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
I personally avoid else
blocks when possible. See the Anti-if Campaign
Also, they don't charge 'extra' for the line, you know :p
"Simple is better than complex" & "Readability is king"
delta = 1 if (A > B) else -1
return A + delta
You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.
This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks
, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks
will create by default a priority of 7.
Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.
/*
Copyright © 2017 Jesse Nicholson
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();
public void EnsureStarupTaskExists()
{
try
{
m_runAtStartupLock.EnterWriteLock();
using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
{
// Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);
// Create a new task definition and assign properties
using(var td = ts.NewTask())
{
td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
// This is not normally necessary. RealTime is the highest priority that
// there is.
td.Settings.Priority = ProcessPriorityClass.RealTime;
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.StopIfGoingOnBatteries = false;
td.Settings.WakeToRun = false;
td.Settings.AllowDemandStart = false;
td.Settings.IdleSettings.RestartOnIdle = false;
td.Settings.IdleSettings.StopOnIdleEnd = false;
td.Settings.RestartCount = 0;
td.Settings.AllowHardTerminate = false;
td.Settings.Hidden = true;
td.Settings.Volatile = false;
td.Settings.Enabled = true;
td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
td.RegistrationInfo.Description = "Runs the content filter at startup.";
// Create a trigger that will fire the task at this time every other day
var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
logonTrigger.Enabled = true;
logonTrigger.Repetition.StopAtDurationEnd = false;
logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
td.Triggers.Add(logonTrigger);
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
}
}
}
finally
{
m_runAtStartupLock.ExitWriteLock();
}
}
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
both works similar but "===" even do case statements
"test" == "test" #=> true
"test" === "test" #=> true
here the difference
String === "test" #=> true
String == "test" #=> false
If you are filtering by common date this will return it:
dfs = [df1, df2, df3]
checker = dfs[-1]
check = set(checker.loc[:, 0])
for df in dfs[:-1]:
check = check.intersection(set(df.loc[:, 0]))
print(checker[checker.loc[:, 0].isin(check)])
Try this:
Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help +extension name Enable extension -extension name Disable extension
textBox1.Text = "Line1\r\r\Line2";
Solved the problem.
John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:
def gen():
return (something for something in get_some_stuff())
print gen()[:2] # generators don't support indexing or slicing
print [5,6] + gen() # generators can't be added to lists
Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.
Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.
atoi can do that for you
Example:
char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234
I faced similar exception. Check if all columns has header names( from select query in database) with exactly matching property names in model class.
ng g c --dry-run so you can see what you are about to do before you actually do it will save some frustration. Just shows you what it is going to do without actually doing it.
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
BigDecimal
, not double
The Answer by adatapost is right about using String::split
but wrong about using double
to represent your longitude-latitude values. The float
/Float
and double
/Double
types use floating-point technology which trades away accuracy for speed of execution.
Instead use BigDecimal
to correctly represent your lat-long values.
Also, best to let a library such as Apache Commons CSV perform the chore of reading and writing CSV or Tab-delimited files.
Here is a complete example app using that Commons CSV library. This app writes then reads a data file. It uses String::split
for the writing. And the app uses BigDecimal
objects to represent your lat-long values.
package work.basil.example;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class LatLong
{
//----------| Write |-----------------------------
public void write ( final Path path )
{
List < String > inputs =
List.of(
"28.515046280572285,77.38258838653564" ,
"28.51430151808072,77.38336086273193" ,
"28.513566177802456,77.38413333892822" ,
"28.512830832397192,77.38490581512451" ,
"28.51208605426073,77.3856782913208" ,
"28.511341270865113,77.38645076751709" );
// Use try-with-resources syntax to auto-close the `CSVPrinter`.
try ( final CSVPrinter printer = CSVFormat.RFC4180.withHeader( "latitude" , "longitude" ).print( path , StandardCharsets.UTF_8 ) ; )
{
for ( String input : inputs )
{
String[] fields = input.split( "," );
printer.printRecord( fields[ 0 ] , fields[ 1 ] );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Read |-----------------------------
public void read ( Path path )
{
// TODO: Add a check for valid file existing.
try
{
// Read CSV file.
BufferedReader reader = Files.newBufferedReader( path );
Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
for ( CSVRecord record : records )
{
BigDecimal latitude = new BigDecimal( record.get( "latitude" ) );
BigDecimal longitude = new BigDecimal( record.get( "longitude" ) );
System.out.println( "lat: " + latitude + " | long: " + longitude );
}
} catch ( IOException e )
{
e.printStackTrace();
}
}
//----------| Main |-----------------------------
public static void main ( String[] args )
{
LatLong app = new LatLong();
// Write
Path pathOutput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.write( pathOutput );
System.out.println( "Writing file: " + pathOutput );
// Read
Path pathInput = Paths.get( "/Users/basilbourque/lat-long.csv" );
app.read( pathInput );
System.out.println( "Done writing & reading lat-long data file. " + Instant.now() );
}
}
img {
filter: blur(var(--blur));
}
I'm guessing Laravel can't determine the plural form of the word you used for your table name.
Just specify your table in the model as such:
class Cotizacion extends Model{
public $table = "cotizacion";
Yes, this is a 'new style' object. It was a feature introduced in python2.2.
New style objects have a different object model to classic objects, and some things won't work properly with old style objects, for instance, super()
, @property
and descriptors. See this article for a good description of what a new style class is.
SO link for a description of the differences: What is the difference between old style and new style classes in Python?
Update: 19 -11-2019
The below answer is no more relevant to present day.
So for any one looking for answers you should look at the documentation linked below
https://developer.android.com/training/articles/user-data-ids
Old Answer - Not relevant now. You check this blog in the link below
http://android-developers.blogspot.in/2011/03/identifying-app-installations.html
ANDROID_ID
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
The above is from the link @ Is there a unique Android device ID?
More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.
ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.
The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.
You get the imei number of the device using the below
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
Add this is manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
first of all: as far as i know placing dialog inside a tabview is a bad practice... you better take it out...
and now to your question:
sorry, took me some time to get what exactly you wanted to implement,
did at my web app myself just now, and it works
as I sayed before place the p:dialog out side the `p:tabView ,
leave the p:dialog as you initially suggested :
<p:dialog modal="true" widgetVar="dlg">
<h:panelGrid id="display">
<h:outputText value="Name:" />
<h:outputText value="#{instrumentBean.selectedInstrument.name}" />
</h:panelGrid>
</p:dialog>
and the p:commandlink should look like this (all i did is to change the update attribute)
<p:commandLink update="display" oncomplete="dlg.show()">
<f:setPropertyActionListener value="#{lndInstrument}"
target="#{instrumentBean.selectedInstrument}" />
<h:outputText value="#{lndInstrument.name}" />
</p:commandLink>
the same works in my web app, and if it does not work for you , then i guess there is something wrong in your java bean code...
his example will tell you how to pass input value to parent on submit button.
First define eventBus as new Vue.
//main.js
import Vue from 'vue';
export const eventBus = new Vue();
Pass your input value via Emit.
//Sender Page
import { eventBus } from "../main";
methods: {
//passing data via eventbus
resetSegmentbtn: function(InputValue) {
eventBus.$emit("resetAllSegment", InputValue);
}
}
//Receiver Page
import { eventBus } from "../main";
created() {
eventBus.$on("resetAllSegment", data => {
console.log(data);//fetching data
});
}
If you wanna do with a button click and not the other way. You can do it by adding location.href
to your button. Here is how I'm using
<button class="btn btn-lg btn-primary" id="submit" onclick="location.href ='/dashboard'" >Go To Dashboard</button>
The button above uses bootstrap classes for styling. Without styling, the simplest code would be
<button onclick="location.href ='/dashboard'" >Go To Dashboard</button>
The /dashboard
is my JSP page, If you are using extension too then used /dashboard.jsp
These are some tips to make your cells Bold
, Big font
, Italic
Let's say I have columns from A
to L
A1
- is your starting cell
L1
- is your last cell
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setSize(16);
$objPHPExcel->getActiveSheet()->getStyle('A1:L1')->getFont()->setItalic(true);
Why not just try loading all the files in the folder? If OpenCV can't open it, oh well. Move on to the next. cv2.imread()
returns None
if the image can't be opened. Kind of weird that it doesn't raise an exception.
import cv2
import os
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
img = cv2.imread(os.path.join(folder,filename))
if img is not None:
images.append(img)
return images
I would do something like,
Main
var getPage = get_page
func get_page (...
func downloader() {
dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
content := getPage(BASE_URL)
links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
matches := links_regexp.FindAllStringSubmatch(content, -1)
for _, match := range matches{
go serie_dl(match[1], match[2])
}
}
Test
func TestDownloader (t *testing.T) {
origGetPage := getPage
getPage = mock_get_page
defer func() {getPage = origGatePage}()
// The rest to be written
}
// define mock_get_page and rest of the codes
func mock_get_page (....
And I would avoid _
in golang. Better use camelCase
I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.
CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG
You can find details about the parameters at this link.
Hope it helps!
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
As for what programming languages, any browser-based or server-based language is likely to be used. Javascript, PHP, ASP, AJAX, Perl, Java, SQL.
Let's say you need to implement a new programming language and BCL designed specifically for operating in the cloud (it won't be used on client machines ever). It should be optimized for cloud computing; easy to learn, fast, efficient, powerful, modern.
The biggest way i’ve seen cloud hosting products help out developers is the ability to launch and increase the size of a server, without having any kind of delay. Developers are able to create the application in a completely customized environment, and then expand it into a production machine with a significant hassle. If things don’t work as wanted, they can then destroy that machine with relative ease.
Most of the Cloud Computing Providers used JAVA and C-Sharp, to make cloud server.
"SP25 work on Visual Studio 2019" is an exaggeration. It is extremely unreliable and should be avoided at all costs. I currently have to maintain a second development environment with V2015 for report development.
As far as I know, there's a good library called localeplanet
for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)
Here's the website of library: http://www.localeplanet.com/
Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/
The common part of all those articles/libraries is that they use a i18n
class and a get
method (in some ways also defining an smaller function name like _
) for retrieving/converting the key
to the value
. In my explaining the key
means that string you want to translate and the value
means translated string.
Then, you just need a JSON document to store key
's and value
's.
For example:
var _ = document.webL10n.get;
alert(_('test'));
And here the JSON:
{ test: "blah blah" }
I believe using current popular libraries solutions is a good approach.
The best way to get good control over the colorbar position is to give it its own axis. Like so:
# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)
# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8])
cb = plt.colorbar(ax1, cax = cbaxes)
The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.
The height of list view items are adjusted based on its contents. In first image, no content. so height is very minimum. In second image, height is increased based on the size of the text. Because, you specified android:layout_height="wrap_content".
One other really good reason to use a bitmask vs individual bools is as a web developer, when integrating one website to another, we frequently need to send parameters or flags in the querystring. As long as all of your flags are binary, it makes it much simpler to use a single value as a bitmask than send multiple values as bools. I know there are otherways to send data (GET, POST, etc.), but a simple parameter on the querystring is most of the time sufficient for nonsensitive items. Try to send 128 bool values on a querystring to communicate with an external site. This also gives the added ability of not pushing the limit on url querystrings in browsers
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}
It should be pretty obvious from your question that you're actually just asking about the difference between git merge
and git rebase
.
So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:
- o - o - o - H - A - B - C (master)
\
P - Q - R (origin/master)
If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:
- o - o - o - H - A - B - C - X (master)
\ /
P - Q - R --- (origin/master)
If on the other hand you did the appropriate rebase, you'd end up with this:
- o - o - o - H - P - Q - R - A' - B' - C' (master)
|
(origin/master)
The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R
), instead of where you originally committed (H
). You should never use the rebase approach if someone else has already pulled from your master branch.
Finally, note that you can actually set up git pull
for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase
to true. You can also do this for a single pull using git pull --rebase
.
Old question, but alternatively:
virtualenv --python=python3.5 .venv
source .venv/bin/activate
while running:
lenli = len(li)
for i, elem in enumerate(li):
thiselem = elem
nextelem = li[(i+1)%lenli] # This line is vital
The slicing problem is serious because it can result in memory corruption, and it is very difficult to guarantee a program does not suffer from it. To design it out of the language, classes that support inheritance should be accessible by reference only (not by value). The D programming language has this property.
Consider class A, and class B derived from A. Memory corruption can happen if the A part has a pointer p, and a B instance that points p to B's additional data. Then, when the additional data gets sliced off, p is pointing to garbage.
I too have been through this pain - if the query is dynamically generated (e.g. Hibernate Criteria) then I couldn't find a practical way to do it.
The good news for me was that I was only investigating union to solve a performance problem when using an 'or' in an Oracle database.
The solution Patrick posted (combining the results programmatically using a set) while ugly (especially since I wanted to do results paging as well) was adequate for me.
Lengthy But "Works With No Surprises & No Installations"
This script handles filenames with spaces, quotes, other unusual characters and Unicode, works on case insensitive filesystems and most Unix-y environments that have bash and awk installed (i.e. almost all). It also reports collisions if any (leaving the filename in uppercase) and of course renames both files & directories and works recursively. Finally it's highly adaptable: you can tweak the find command to target the files/dirs you wish and you can tweak awk to do other name manipulations. Note that by "handles Unicode" I mean that it will indeed convert their case (not ignore them like answers that use tr
).
# adapt the following command _IF_ you want to deal with specific files/dirs
find . -depth -mindepth 1 -exec bash -c '
for file do
# adapt the awk command if you wish to rename to something other than lowercase
newname=$(dirname "$file")/$(basename "$file" | awk "{print tolower(\$0)}")
if [ "$file" != "$newname" ] ; then
# the extra step with the temp filename is for case-insensitive filesystems
if [ ! -e "$newname" ] && [ ! -e "$newname.lcrnm.tmp" ] ; then
mv -T "$file" "$newname.lcrnm.tmp" && mv -T "$newname.lcrnm.tmp" "$newname"
else
echo "ERROR: Name already exists: $newname"
fi
fi
done
' sh {} +
References
My script is based on these excellent answers:
https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names
I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange=""
attribute to the input tag:
<input type='file' onchange='getFilename(this)'/>
function getFileName(elm) {
var fn = $(elm).val();
....
}
EDIT:
function getFileName(elm) {
var fn = $(elm).val();
var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
alert(filename);
}
I've tried many times.
And at last I just put autoindex on;
in http
but outside of server
, and it's OK.
I had the same issue. It turns out I added incorrect variables to the my.cnf file. Once I removed them and restarted mysql started with no issue.
Typically it because of upgrading JRE.
It changes symlinks into C:\ProgramData\Oracle\Java\javapath\
Intall JDK - it will fix this.
Image provides an abstract access to an arbitrary image , it defines a set of methods that can loggically be applied upon any implementation of Image. Its not bounded to any particular image format or implementation . Bitmap is a specific implementation to the image abstract class which encapsulate windows GDI bitmap object. Bitmap is just a specific implementation to the Image abstract class which relay on the GDI bitmap Object.
You could for example , Create your own implementation to the Image abstract , by inheriting from the Image class and implementing the abstract methods.
Anyway , this is just a simple basic use of OOP , it shouldn't be hard to catch.
1 - Create a folder in your google drive;
2 - Make this folder public (on share property)
3 - use something like this as your image src:
https://drive.google.com/thumbnail?id=${imageId}&sz=w${width || 200}-h${height || 200}
The field's value is:
"- DE-HEB 20% - DTopTen 1.2%"
SELECT ....
SUBSTRING_INDEX(SUBSTRING_INDEX(DesctosAplicados, 'DE-HEB ', -1), '-', 1) DE-HEB ,
SUBSTRING_INDEX(SUBSTRING_INDEX(DesctosAplicados, 'DTopTen ', -1), '-', 1) DTopTen ,
FROM TABLA
Result is:
DE-HEB DTopTEn
20% 1.2%
Find your location in the Google Earth program, and click the icon "View in Google Maps". The URL bar in your browser will show the URL you need.
First method
For Windows 7 and above users, Windows PowerShell give you this option. Users with windows version less than 7 can download PowerShell online and install it.
Steps:
type PowerShell in search area and click on "Windows PowerShell"
If you have a .bat (batch) file go to step 3 OR copy your commands to a file and save it with .bat extension (e.g. file.bat)
run the .bat file with following command
PS (location)> <path to bat file>/file.bat | Tee-Object -file log.txt
This will generate a log.txt file with all command prompt output in it. Advantage is that you can also the output on command prompt.
Second method
You can use file redirection (>, >>) as suggest by Bali C above.
I will recommend first method if you have lots of commands to run or a script to run. I will recommend last method if there is only few commands to run.
Just to add that if your truth value can vary, for instance if it is an input from different programming languages or from different types, a more robust method would be:
flag = value in ['True','true',1,'T','t','1'] # this can be as long as you want to support
And a more performant variant would be (set lookup is O(1)):
TRUTHS = set(['True','true',1,'T','t','1'])
flag = value in truths
Bootstrap 4+ has made changes to the utility classes for this. From the documentation:
Added
.float-{sm,md,lg,xl}-{left,right,none}
classes for responsive floats and removed.pull-left
and.pull-right
since they’re redundant to.float-left
and.float-right
.
So use the .float-right
(or a size equivalent such as .float-lg-right
) instead of .pull-right
for your right alignment if you're using a newer Bootstrap version.
Another method, if eval is safe & fast :
eval(["10","20","30","40","50"].join("+"))
string connectString = "Data Source=(local);" + "Integrated Security=true";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
Console.WriteLine("builder.InitialCatalog = " + builder.InitialCatalog);
Not sure if this is still extant but I'm guessing you need something like
((field Like "AA*") AND (field Not Like "BB*"))
I found a mathematical way to get this job done
Github repo - https://github.com/gayanSandamal/easy-php-image-resizer
Live example - https://plugins.nayague.com/easy-php-image-resizer/
<?php
//path for the image
$source_url = '2018-04-01-1522613288.PNG';
//separate the file name and the extention
$source_url_parts = pathinfo($source_url);
$filename = $source_url_parts['filename'];
$extension = $source_url_parts['extension'];
//define the quality from 1 to 100
$quality = 10;
//detect the width and the height of original image
list($width, $height) = getimagesize($source_url);
$width;
$height;
//define any width that you want as the output. mine is 200px.
$after_width = 200;
//resize only when the original image is larger than expected with.
//this helps you to avoid from unwanted resizing.
if ($width > $after_width) {
//get the reduced width
$reduced_width = ($width - $after_width);
//now convert the reduced width to a percentage and round it to 2 decimal places
$reduced_radio = round(($reduced_width / $width) * 100, 2);
//ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places
$reduced_height = round(($height / 100) * $reduced_radio, 2);
//reduce the calculated height from the original height
$after_height = $height - $reduced_height;
//Now detect the file extension
//if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG'
if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') {
//then return the image as a jpeg image for the next step
$img = imagecreatefromjpeg($source_url);
} elseif ($extension == 'png' || $extension == 'PNG') {
//then return the image as a png image for the next step
$img = imagecreatefrompng($source_url);
} else {
//show an error message if the file extension is not available
echo 'image extension is not supporting';
}
//HERE YOU GO :)
//Let's do the resize thing
//imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]);
$imgResized = imagescale($img, $after_width, $after_height, $quality);
//now save the resized image with a suffix called "-resized" and with its extension.
imagejpeg($imgResized, $filename . '-resized.'.$extension);
//Finally frees any memory associated with image
//**NOTE THAT THIS WONT DELETE THE IMAGE
imagedestroy($img);
imagedestroy($imgResized);
}
?>
I've just found a seriously easy way to do this using seq:
UPDATE: This works on the BSD seq
that comes with OS X. YMMV with other versions
seq -f "#" -s '' 10
Will print '#' 10 times, like this:
##########
-f "#"
sets the format string to ignore the numbers and just print #
for each one.-s ''
sets the separator to an empty string to remove the newlines that seq inserts between each number-f
and -s
seem to be important.EDIT: Here it is in a handy function...
repeat () {
seq -f $1 -s '' $2; echo
}
Which you can call like this...
repeat "#" 10
NOTE: If you're repeating #
then the quotes are important!
What kind of data?
data: $('#myForm').serialize() + "&moredata=" + morevalue
The "data" parameter is just a URL encoded string. You can append to it however you like. See the API here.
You can try something like this....
Dim cbTime
Set cbTime = ActiveSheet.CheckBoxes.Add(100, 100, 50, 15)
With cbTime
.Name = "cbTime"
.Characters.Text = "Time"
End With
If ActiveSheet.CheckBoxes("cbTime").Value = 1 Then 'or just cbTime.Value
'checked
Else
'unchecked
End If
I restore my files using the SHA id, What i do is git checkout <sha hash id> <file name>
I followed the below steps and it worked for me.
Step1: Edit eclipse.ini by adding javaw.exe path and remove --launcher.appendVmargs line. Below shows the original and edited file
Orginal eclipse.ini openFile --launcher.appendVmargs -vmargs -Dosgi.requiredJavaVersion=1.8
After editing eclipse.ini: openFile -vm C:/ProgramFiles/Java/javapath/javaw.exe -vmargs -Dosgi.requiredJavaVersion=1.8
Step2: Copied the org.eclipse.equinox.launcher_1.5.700.v20200207-2156.jar to eclipse installation folder . You can find the .jar location in eclipse.ini eg : C:\Users\Username.p2\pool\plugins
You can also refine Hash::each
so it will support recursive enumeration. Here is my version of Hash::each
(Hash::each_pair
) with block and enumerator support:
module HashRecursive
refine Hash do
def each(recursive=false, &block)
if recursive
Enumerator.new do |yielder|
self.map do |key, value|
value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
yielder << [[key], value]
end
end.entries.each(&block)
else
super(&block)
end
end
alias_method(:each_pair, :each)
end
end
using HashRecursive
Here are usage examples of Hash::each
with and without recursive
flag:
hash = {
:a => {
:b => {
:c => 1,
:d => [2, 3, 4]
},
:e => 5
},
:f => 6
}
p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2
p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6
hash.each do |key, value|
puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6
hash.each(true) do |key, value|
puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6
hash.each_pair(recursive=true) do |key, value|
puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6
Here is example from the question itself:
hash = {
1 => ["a", "b"],
2 => ["c"],
3 => ["a", "d", "f", "g"],
4 => ["q"]
}
hash.each(recursive=false) do |key, value|
puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]
Also take a look at my recursive version of Hash::merge
(Hash::merge!
) here.
From Quick-R
par() # view current settings
opar <- par() # make a copy of current settings
par(col.lab="red") # red x and y labels
hist(mtcars$mpg) # create a plot with these new settings
par(opar) # restore original settings
Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.
You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n
indicating one line.
So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n
, perform your operation on the line and proceed to read the next line into the buffer.
Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...
EDIT
import serial
ser = serial.Serial(
port='COM5',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
#this will store the line
line = []
while True:
for c in ser.read():
line.append(c)
if c == '\n':
print("Line: " + ''.join(line))
line = []
break
ser.close()
Have a look at CONVERT. The 3rd parameter is the date time style you want to convert to.
e.g.
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) -- dd/MM/yyyy format
surely you can do this with worksheet formulas, avoiding VBA entirely:
so for this value in say, column AV S:1 P:0 K:1 Q:1
you put this formula in column BC:
=MID(AV:AV,FIND("S",AV:AV)+2,1)
then these formulas in columns BD, BE...
=MID(AV:AV,FIND("P",AV:AV)+2,1)
=MID(AV:AV,FIND("K",AV:AV)+2,1)
=MID(AV:AV,FIND("Q",AV:AV)+2,1)
so these formulas look for the values S:1, P:1 etc in column AV. If the FIND
function returns an error, then 0 is returned by the formula, else 1 (like an IF, THEN, ELSE
Then you would just copy down the formulas for all the rows in column AV.
HTH Philip
Fast:
SELECT TOP (1) CASE
WHEN **NOT_NULL_COLUMN** IS NULL
THEN 'empty table'
ELSE 'not empty table'
END AS info
FROM **TABLE_NAME**
In your XML, you had used Textview, But in Java Code you had used EditText instead of TextView. If you change it into TextView you can set Text to to your TextView Object.
text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("TEST");
hope it will work.
SHIFTV puts you in select lines mode. Then "*y yanks the currently selected lines to the *
register which is the clipboard. There are quite a few different registers, for different purposes. See the section on selection and drop registers
for details on the differences between *
and +
registers on Windows and Linux.
Suppose you want to insert a particular line of text (not an empty line):
@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1
@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /p L=
IF %%i==%insertat% ECHO(!TL!
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
You have to go to its parent and remove it from there in javascript.
"Javascript won't let an element commit suicide, but it does permit infanticide"..:)
try this,
var element=document.getElementsByName(val))
element.parentNode.removeChild(element.options[0]); // to remove first option
This worked for me in ASP.NET Core MVC.
<script type="text/javascript">
var ar = @Html.Raw(Json.Serialize(Model.Addresses));
</script>
The answer as well as other answers are correct. I am going to add to those answers with a solution that I think will be helpful. I think this comes up often in programming. One thing to note is that for Collections (Lists, Sets, etc.) the main issue is adding to the Collection. That is where things break down. Even removing is OK.
In most cases, we can use Collection<? extends T>
rather then Collection<T>
and that should be the first choice. However, I am finding cases where it is not easy to do that. It is up for debate as to whether that is always the best thing to do. I am presenting here a class DownCastCollection that can take convert a Collection<? extends T>
to a Collection<T>
(we can define similar classes for List, Set, NavigableSet,..) to be used when using the standard approach is very inconvenient. Below is an example of how to use it (we could also use Collection<? extends Object>
in this case, but I am keeping it simple to illustrate using DownCastCollection.
/**Could use Collection<? extends Object> and that is the better choice.
* But I am doing this to illustrate how to use DownCastCollection. **/
public static void print(Collection<Object> col){
for(Object obj : col){
System.out.println(obj);
}
}
public static void main(String[] args){
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList("a","b","c"));
print(new DownCastCollection<Object>(list));
}
Now the class:
import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class DownCastCollection<E> extends AbstractCollection<E> implements Collection<E> {
private Collection<? extends E> delegate;
public DownCastCollection(Collection<? extends E> delegate) {
super();
this.delegate = delegate;
}
@Override
public int size() {
return delegate ==null ? 0 : delegate.size();
}
@Override
public boolean isEmpty() {
return delegate==null || delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
if(isEmpty()) return false;
return delegate.contains(o);
}
private class MyIterator implements Iterator<E>{
Iterator<? extends E> delegateIterator;
protected MyIterator() {
super();
this.delegateIterator = delegate == null ? null :delegate.iterator();
}
@Override
public boolean hasNext() {
return delegateIterator != null && delegateIterator.hasNext();
}
@Override
public E next() {
if(!hasNext()) throw new NoSuchElementException("The iterator is empty");
return delegateIterator.next();
}
@Override
public void remove() {
delegateIterator.remove();
}
}
@Override
public Iterator<E> iterator() {
return new MyIterator();
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
if(delegate == null) return false;
return delegate.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
if(delegate==null) return false;
return delegate.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
if(delegate == null) return false;
return delegate.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
if(delegate == null) return false;
return delegate.retainAll(c);
}
@Override
public void clear() {
if(delegate == null) return;
delegate.clear();
}
}
Another solution, you can solve your problem using replaceAll
with some regex ^.{1}
(regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
1 select ename as name, 2 sal as salary, 3 dept,deptno, 4 from (TABLE_NAME or SUBQUERY) 5 emp, emp2, dept 6 where 7 emp.deptno = dept.deptno and 8 emp2.deptno = emp.deptno 9* order by dept.dname from (TABLE_NAME or SUBQUERY) * ERROR at line 4: ORA-00936: missing expression` select ename as name, sal as salary, dept,deptno, from (TABLE_NAME or SUBQUERY) emp, emp2, dept where emp.deptno = dept.deptno and emp2.deptno = emp.deptno order by dept.dname`
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
If someone is using column names like "key"
or "value"
, then you still see the same error that your mysql query syntax is bad. This should fix:
.where("`key` LIKE ?", "%#{key}%")
It is possible to have static
class variables, but probably not worth the effort.
Here's a proof-of-concept written in Python 3 -- if any of the exact details are wrong the code can be tweaked to match just about whatever you mean by a static variable
:
class Static:
def __init__(self, value, doc=None):
self.deleted = False
self.value = value
self.__doc__ = doc
def __get__(self, inst, cls=None):
if self.deleted:
raise AttributeError('Attribute not set')
return self.value
def __set__(self, inst, value):
self.deleted = False
self.value = value
def __delete__(self, inst):
self.deleted = True
class StaticType(type):
def __delattr__(cls, name):
obj = cls.__dict__.get(name)
if isinstance(obj, Static):
obj.__delete__(name)
else:
super(StaticType, cls).__delattr__(name)
def __getattribute__(cls, *args):
obj = super(StaticType, cls).__getattribute__(*args)
if isinstance(obj, Static):
obj = obj.__get__(cls, cls.__class__)
return obj
def __setattr__(cls, name, val):
# check if object already exists
obj = cls.__dict__.get(name)
if isinstance(obj, Static):
obj.__set__(name, val)
else:
super(StaticType, cls).__setattr__(name, val)
and in use:
class MyStatic(metaclass=StaticType):
"""
Testing static vars
"""
a = Static(9)
b = Static(12)
c = 3
class YourStatic(MyStatic):
d = Static('woo hoo')
e = Static('doo wop')
and some tests:
ms1 = MyStatic()
ms2 = MyStatic()
ms3 = MyStatic()
assert ms1.a == ms2.a == ms3.a == MyStatic.a
assert ms1.b == ms2.b == ms3.b == MyStatic.b
assert ms1.c == ms2.c == ms3.c == MyStatic.c
ms1.a = 77
assert ms1.a == ms2.a == ms3.a == MyStatic.a
ms2.b = 99
assert ms1.b == ms2.b == ms3.b == MyStatic.b
MyStatic.a = 101
assert ms1.a == ms2.a == ms3.a == MyStatic.a
MyStatic.b = 139
assert ms1.b == ms2.b == ms3.b == MyStatic.b
del MyStatic.b
for inst in (ms1, ms2, ms3):
try:
getattr(inst, 'b')
except AttributeError:
pass
else:
print('AttributeError not raised on %r' % attr)
ms1.c = 13
ms2.c = 17
ms3.c = 19
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
MyStatic.c = 43
assert ms1.c == 13
assert ms2.c == 17
assert ms3.c == 19
ys1 = YourStatic()
ys2 = YourStatic()
ys3 = YourStatic()
MyStatic.b = 'burgler'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
assert ys1.d == ys2.d == ys3.d == YourStatic.d
assert ys1.e == ys2.e == ys3.e == YourStatic.e
ys1.a = 'blah'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
ys2.b = 'kelp'
assert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b
ys1.d = 'fee'
assert ys1.d == ys2.d == ys3.d == YourStatic.d
ys2.e = 'fie'
assert ys1.e == ys2.e == ys3.e == YourStatic.e
MyStatic.a = 'aargh'
assert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a
My problem was I was creating the route first
// ...
router.get('/post/data', myController.postHandler);
// ...
and registering the middleware after the route
app.use(bodyParser.json());
//etc
due to app structure & copy and pasting the project together from examples.
Once I fixed the order to register middleware before the route, it all worked.
MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.
While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.
I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.
MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.
your data grid needs to be bound to a sortable list in the first place.
Create this event handler:
void MakeColumnsSortable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
//Add this as an event on DataBindingComplete
DataGridView dataGridView = sender as DataGridView;
if (dataGridView == null)
{
var ex = new InvalidOperationException("This event is for a DataGridView type senders only.");
ex.Data.Add("Sender type", sender.GetType().Name);
throw ex;
}
foreach (DataGridViewColumn column in dataGridView.Columns)
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
And initialize the event of each of your datragrids like this:
dataGridView1.DataBindingComplete += MakeColumnsSortable_DataBindingComplete;
The problem I had can't be made out from the info I have provided:
<p>
tags. I changed the <p>
to <span>
and it works fine.
products = [{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}];
change to
products = '[{"name":"Pizza","price":"10","quantity":"7"}, {"name":"Cerveja","price":"12","quantity":"5"}, {"name":"Hamburguer","price":"10","quantity":"2"}, {"name":"Fraldas","price":"6","quantity":"2"}]';
Executing the command: Devenv.exe /ResetSettings like :
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>devenv.exe /ResetSettings , resolved my issue :D
For more: https://msdn.microsoft.com/en-us/library/ms241273.aspx
Check out the COPY command of Postgres:
This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.
2.2 configuration syntax was
Order deny,allow
Deny from all
2.4 configuration now is
Require all denied
Thus, this 2.2 syntax
order deny,allow
deny from all
allow from 127.0.0.1
Would ne now written
Require local
Here's an example if:
ifeq ($(strip $(OS)),Linux)
PYTHON = /usr/bin/python
FIND = /usr/bin/find
endif
Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.
For two strings concat is faster, in other cases StringBuilder is a better choice, see my explanation in concatenation operator (+) vs concat()
You can pass the event as argument to the function and then prevent the default behaviour.
var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(event){
event.preventDefault();
alert('it works!');
}
return <form onSubmit={this.doSomething}>
<button>Click me</button>
</form>;
}
});
You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.
This is can done in this way:
add hash in the url of next_page : example.com#hashkey
$( document ).ready(function() {
##get hash code at next page
var hashcode = window.location.hash;
## move page to any specific position of next page(let that is div with id "hashcode")
$('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');
});
here it's the solution for if there have any assigned values inside the string.xml file.
<string name="styled_welcome_message"><![CDATA[We are <b> %1$s </b> glad to see you.]]></string>
set in to TextView:
textView?.setText(HtmlCompat.fromHtml(getString(R.string.styled_welcome_message, "sample"), HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE)
You will either need LESS or SASS for the same..
But here is another alternative which I believe will work out in CSS3..
http://css3.bradshawenterprises.com/blog/css-variables/
Example :
:root {
-webkit-var-beautifulColor: rgba(255,40,100, 0.8);
-moz-var-beautifulColor: rgba(255,40,100, 0.8);
-ms-var-beautifulColor: rgba(255,40,100, 0.8);
-o-var-beautifulColor: rgba(255,40,100, 0.8);
var-beautifulColor: rgba(255,40,100, 0.8);
}
.example1 h1 {
color: -webkit-var(beautifulColor);
color: -moz-var(beautifulColor);
color: -ms-var(beautifulColor);
color: -o-var(beautifulColor);
color: var(beautifulColor);
}
For Linux Run this command
date -d '06/12/2012 07:21:22' +"%s"
For mac OSX run this command
date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"
To convert $date
from dd-mm-yyyy hh:mm:ss
to a proper MySQL datetime
I go like this:
$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s');
Did you check the small Mousetrap library?
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.
Try this:
<iframe name="iframe1" src="target.html"></iframe>
<a href="link.html" target="iframe1">link</a>
The "target" attribute should open in the iframe.
@rckoenes already showed you how to correctly get your data from the JSON string.
To the question you asked: EXC_BAD_ACCESS
almost always comes when you try to access an object after it has been [auto-]released. This is not specific to JSON [de-]serialization but, rather, just has to do with you getting an object and then accessing it after it's been released. The fact that it came via JSON doesn't matter.
There are many-many pages describing how to debug this -- you want to Google (or SO) obj-c zombie objects
and, in particular, NSZombieEnabled
, which will prove invaluable to you in helping determine the source of your zombie objects. ("Zombie" is what it's called when you release an object but keep a pointer to it and try to reference it later.)
You can also try this way:
<?php
echo "<script>console.log('$variableName')</script>";
?>
Regshot deserves a mention here. It scans and takes a snapshot of all registry settings, then you run it again at a later time to compare with the original snapshot, and it shows you all the keys and values that have changed.
Using script tags:
<script>...</script>
block containing your multiline text into head
tag;get your multiline text as is... (watch out for text encoding: UTF-8, ASCII)
<script>
// pure javascript
var text = document.getElementById("mySoapMessage").innerHTML ;
// using JQuery's document ready for safety
$(document).ready(function() {
var text = $("#mySoapMessage").html();
});
</script>
<script id="mySoapMessage" type="text/plain">
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="...">
<soapenv:Header/>
<soapenv:Body>
<typ:getConvocadosElement>
...
</typ:getConvocadosElement>
</soapenv:Body>
</soapenv:Envelope>
<!-- this comment will be present on your string -->
//uh-oh, javascript comments... SOAP request will fail
</script>
A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here
e.g
<script>
//look no global needed:)
$(document).ready(function(){
// Get the initial value
var $el = $('#myInputElement');
$el.data('oldVal', $el.val() );
$el.change(function(){
//store new value
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
})
.focus(function(){
// Get the value when input gains focus
var oldValue = $(this).data('oldVal');
});
});
</script>
<input id="myInputElement" type="text">
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
It's method syntax (which I find easier to read) but this might do it
Updated post comment
Use .FirstOrDefault()
instead of .First()
With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment
var groupByReference = context.Measurements
.GroupBy(m => m.Reference)
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
// Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
// .ThenBy(x => x.Avg)
.Take(numOfEntries)
.ToList();
I found "sort" does not always do what I expected. eg, I have a directory as below, and the "sort" give me a very strange result:
>>> os.listdir(pathon)
['2', '3', '4', '5', '403', '404', '407', '408', '410', '411', '412', '413', '414', '415', '416', '472']
>>> sorted([ f for f in os.listdir(pathon)])
['2', '3', '4', '403', '404', '407', '408', '410', '411', '412', '413', '414', '415', '416', '472', '5']
It seems it compares the first character first, if that is the biggest, it would be the last one.
Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ()
.
The file content:
528(smbw)
529(smbt)
530(smbn)
10115(smbs)
The command:
awk -F"[()]" '{print $2}' filename
result:
smbw
smbt
smbn
smbs
Using awk to just print the text between []
:
Use awk -F'[][]'
but awk -F'[[]]'
will not work.
http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html
The behaviour should depend on how the browser is set up to handle various MIME types. In this case the MIME type is application/pdf. If you want to force the browser to download the file you can try forcing a different MIME type on the PDF files. I recommend against this as it should be the users choice what will happen when they open a PDF file.
function DeleteJob() {
if (confirm("Do you really want to delete selected job/s?"))
window.location.href = "/{controller}/{action}/{params}";
else
return false;
}
Even without looking at assembly, the most obvious reason is that /= 2
is probably optimized as >>=1
and many processors have a very quick shift operation. But even if a processor doesn't have a shift operation, the integer division is faster than floating point division.
Edit: your milage may vary on the "integer division is faster than floating point division" statement above. The comments below reveal that the modern processors have prioritized optimizing fp division over integer division. So if someone were looking for the most likely reason for the speedup which this thread's question asks about, then compiler optimizing /=2
as >>=1
would be the best 1st place to look.
On an unrelated note, if n
is odd, the expression n*3+1
will always be even. So there is no need to check. You can change that branch to
{
n = (n*3+1) >> 1;
count += 2;
}
So the whole statement would then be
if (n & 1)
{
n = (n*3 + 1) >> 1;
count += 2;
}
else
{
n >>= 1;
++count;
}
(More than 10 years later ...)
Procedural generation only means that code is used to generate the data instead of it being hand made. For example if you want to generate a forest with various trees you are not going to design each tree by hand, thus coding is more efficient to generate the variations. It could be the generation of the tree graphics, size, structure, placement ...
In general there is some kind of interation with a few rules, in addition to that you can add some randomness and logic of your own, combine all of these techniques ... Anything somewhat chaotic but not too chaotic can yield interesting results.
Here are a few notable techniques:
A few games famous for their procedural generation:
Video tutorial about Procedural Landmass Generation.
Conference on procedural content generation for games, has a lot of videos on the topic: everythingprocedural
Have fun.
I have tested almost all methods given here in this page for my Angular app. Only I found solution via
that inserts spaces i.e.
Angular Material
add
in the placeholder
, like
<input matInput type="text" placeholder=" Email">
Non Angular Material
Add padding
to your input
field, like below. Click Run Code Snippet
to see demo
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container m-3 d-flex flex-column align-items-center justify-content-around" style="height:100px;">
<input type="text" class="pl-0" placeholder="Email with no Padding" style="width:240px;">
<input type="text" class="pl-3" placeholder="Email with 1 rem padding" style="width:240px;">
</div>
_x000D_
If you are Clion/anyOtherJetBrainsIDE user, and yourFile.exe cause this problem, just delete it and let the app create and link it with libs from a scratch. It helps.
On Windows:
Find : Ctrl+F
Find And Replace In Single Class: Ctrl+R
Find And Replace In Whole Project: Ctrl+Shift+R
on OS X ,it is similar, just replace Ctrl with Command
One technique, suggested by this article, would be to do this:
<img style="background:url(thumbnail1.jpg)" src="magnifying_glass.png" />
If you are using the Spring Boot Maven Plugin, run:
mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar
(https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html)
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
Another mode is: If your editor HAS NO BLOCK comment option,
DONE
it WORKS with ANY editor
For react:
import 'react-app-polyfill/ie11';
import 'core-js/es5';
import 'core-js/es6';
import 'core-js/es7';
Issue resolve for - includes(), find(), and so on..
To complete @thecatontheflat answer I would recommend to also wrap your action inside of a try … catch
block. This will prevent your JSON endpoint from breaking on exceptions. Here's the skeleton I use:
public function someAction()
{
try {
// Your logic here...
return new JsonResponse([
'success' => true,
'data' => [] // Your data here
]);
} catch (\Exception $exception) {
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
}
This way your endpoint will behave consistently even in case of errors and you will be able to treat them right on a client side.
iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// "e@uu$`a"
iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@uu$`a"
iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// PHP Notice: iconv(): Detected an illegal character
iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@u$`a"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', Transliterator::create('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC')->transliterate('é@ùµ$`à'))
// "e@uu$`a" -> same as PHP 7.2
I prefer this solution;
head -$(gcalctool -s $(cat file | wc -l)-N) file
where N is the number of lines to remove.
(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)
Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:
iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT
Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).
SELECT DISTINCT a.StoreID
FROM tableName a
LEFT JOIN tableName b
ON a.StoreID = b.StoreID AND b.ClientID = 5
WHERE b.StoreID IS NULL
OUTPUT
+---------+
¦ STOREID ¦
¦---------¦
¦ 3 ¦
+---------+
This error occurs because you are using a normal string as a path. You can use one of the three following solutions to fix your problem:
1: Just put r
before your normal string it converts normal string to raw string:
pandas.read_csv(r"C:\Users\DeePak\Desktop\myac.csv")
2:
pandas.read_csv("C:/Users/DeePak/Desktop/myac.csv")
3:
pandas.read_csv("C:\\Users\\DeePak\\Desktop\\myac.csv")
You can try this code:
cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )
You can see the documentation
Install these 2 packages
<packages>
<package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
<package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>
Helper function
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelToCsv
{
public class ExcelFileHelper
{
public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
{
using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
IExcelDataReader reader = null;
if (excelFilePath.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (excelFilePath.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
if (reader == null)
return false;
var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
UseHeaderRow = false
}
});
var csvContent = string.Empty;
int row_no = 0;
while (row_no < ds.Tables[0].Rows.Count)
{
var arr = new List<string>();
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
}
row_no++;
csvContent += string.Join(",", arr) + "\n";
}
StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
csv.Write(csvContent);
csv.Close();
return true;
}
}
}
}
Usage :
var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);
I have the problem anyway with -lm added
gcc -Wall -lm mtest.c -o mtest.o
mtest.c: In function 'f1':
mtest.c:6:12: warning: unused variable 'res' [-Wunused-variable]
/tmp/cc925Nmf.o: In function `f1':
mtest.c:(.text+0x19): undefined reference to `sin'
collect2: ld returned 1 exit status
I discovered recently that it does not work if you first specify -lm. The order matters:
gcc mtest.c -o mtest.o -lm
Just link without problems
So you must specify the libraries after.
Specify the ax
argument to matplotlib.pyplot.colorbar()
, e.g.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
for i in range(2):
for j in range(2):
data = np.array([[i, j], [i+0.5, j+0.5]])
im = ax[i, j].imshow(data)
plt.colorbar(im, ax=ax[i, j])
plt.show()
The canvas
DOM element has .height
and .width
properties that correspond to the height="…"
and width="…"
attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 800;
canvas.height = 600;
Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height);
to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.
Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height
and style.width
CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:
// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width = 400;
canvas.height = 300;
canvas.style.width = '800px';
canvas.style.height = '600px';
See this live example of a canvas that is zoomed in by 4x.
var c = document.getElementsByTagName('canvas')[0];_x000D_
var ctx = c.getContext('2d');_x000D_
ctx.lineWidth = 1;_x000D_
ctx.strokeStyle = '#f00';_x000D_
ctx.fillStyle = '#eff';_x000D_
_x000D_
ctx.fillRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.fillRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.fillRect( 70, 10, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );_x000D_
_x000D_
ctx.strokeStyle = '#fff';_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );
_x000D_
body { background:#eee; margin:1em; text-align:center }_x000D_
canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
_x000D_
<canvas width="100" height="40"></canvas>_x000D_
<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
_x000D_
With ASP.NET project with C# 4.5 I've solved such problem by installing ASP.NET extension in Web Platform Installer
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print(m.start(), m.group())
Try accessing the placeholder attribute of the input and change its value like the following:
$('#some_input_id').attr('placeholder','New Text Here');
Can also clear the placeholder if required like:
$('#some_input_id').attr('placeholder','');
Check if password you are using is correct one by running below command
keytool -keypasswd -new temp123 -keystore awsdemo-keystore.jks -storepass temp123 -alias movie-service -keypass changeit
If you are getting below error then your password is wrong
keytool error: java.security.UnrecoverableKeyException: Cannot recover key
This helped me: I created a new maven project which was working fine in my old workspace, but gave above errors in the new workspace. I had to do the following: - Open old workspace on Eclipse - open Preferences tab - Search Maven in filter - Copy the path for settings.xml from User Settings - User Settings - Switch to new workspace - Update the preferences - Maven - User Settings - User Settings path
After the build is completed, all errors are resolved.
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
A CustomValidator would also work here:
<asp:CustomValidator runat="server"
ID="valDateRange"
ControlToValidate="txtDatecompleted"
onservervalidate="valDateRange_ServerValidate"
ErrorMessage="enter valid date" />
Code-behind:
protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
if you're hosting behind a server, and still facing issues: try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/
The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).
For my sanity check I was using Remy Sharp's demo: https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html
and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):
"User denied Geolocation"
I made the following change to get more detailed error message:
function error(msg) {
var s = document.querySelector('#status');
msg = msg.message ? msg.message : msg; //add this line
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :
"The current location cannot be determined"
You have to execute this line of code
sock_name = socket.gethostname()
And then you can use the name to find the addr :
print(socket.gethostbyname(sock_name))