ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?
Yes Fiddler is an option for me:
CustomRules.js
).OnBeforeResponse
Add the following lines:
oSession.oResponse.headers.Remove("X-Frame-Options");
oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers().disable()
...;
}
}
What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80>
and https <VirtualHost *:443>
virtual host blocks:
ServerName your-app.com
ServerAlias www.your-app.com
Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"
The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options
header so we need to first always remove the default value, in my case it was DENY
, and then with the next rule we set it to the desired value, in my case SAMEORIGIN
. Of course you can use the Header set X-Frame-Options ALLOW-FROM ...
rule as well.
The only question that has a bunch of answers. WElcome to the guide i wish i had when i was scrambling for this to make it work at 10:30 at night on the deadline day... FB does some weird things with canvas apps, and well, you've been warned. If youa re still here and you have a Rails app that will appear behind a Facebook Canvas, then you will need:
Gemfile:
gem "rack-facebook-signed-request", :git => 'git://github.com/cmer/rack-facebook-signed-request.git'
config/facebook.yml
facebook:
key: "123123123123"
secret: "123123123123123123secret12312"
config/application.rb
config.middleware.use Rack::Facebook::SignedRequest, app_id: "123123123123", secret: "123123123123123123secret12312", inject_facebook: false
config/initializers/omniauth.rb
OmniAuth.config.logger = Rails.logger
SERVICES = YAML.load(File.open("#{::Rails.root}/config/oauth.yml").read)
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, SERVICES['facebook']['key'], SERVICES['facebook']['secret'], iframe: true
end
application_controller.rb
before_filter :add_xframe
def add_xframe
headers['X-Frame-Options'] = 'GOFORIT'
end
You need a controller to call from Facebook's canvas settings, i used /canvas/
and made the route go the main SiteController
for this app:
class SiteController < ApplicationController
def index
@user = User.new
end
def canvas
redirect_to '/auth/failure' if request.params['error'] == 'access_denied'
url = params['code'] ? "/auth/facebook?signed_request=#{params['signed_request']}&state=canvas" : "/login"
redirect_to url
end
def login
end
end
login.html.erb
<% content_for :javascript do %>
var oauth_url = 'https://www.facebook.com/dialog/oauth/';
oauth_url += '?client_id=471466299609256';
oauth_url += '&redirect_uri=' + encodeURIComponent('https://apps.facebook.com/wellbeingtracker/');
oauth_url += '&scope=email,status_update,publish_stream';
console.log(oauth_url);
top.location.href = oauth_url;
<% end %>
Sources
This is also a new browser security feature to prevent phishing and other security threats. For chrome, you can download an extension to prevent the browser from denying the request. I encountered this issue while working on WordPress locally.
I use this extension https://chrome.google.com/webstore/detail/ignore-x-frame-headers/gleekbfjekiniecknbkamfmkohkpodhe
<v-layout justify-center>
<v-card-actions>
<v-btn primary>
<span>SignUp</span>
</v-btn>`enter code here`
</v-card-actions>
</v-layout>
From Java 1.5 it's always a good Idea to consider java.util.concurrent package. They are the state of the art locking mechanism in java right now. The synchronize mechanism is more heavyweight that the java.util.concurrent classes.
The example would look something like this:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Sample {
private final Lock lock = new ReentrantLock();
private String message = null;
public void newmsg(String msg) {
lock.lock();
try {
message = msg;
} finally {
lock.unlock();
}
}
public String getmsg() {
lock.lock();
try {
String temp = message;
message = null;
return temp;
} finally {
lock.unlock();
}
}
}
In my case, I use in component file:
import {formatDate} from '@angular/common';
// Use your preferred locale
import localeFr from '@angular/common/locales/fr';
import { registerLocaleData } from '@angular/common';
// ....
displayDate: string;
registerLocaleData(localeFr, 'fr');
this.displayDate = formatDate(new Date(), 'EEEE d MMMM yyyy', 'fr');
And in the component HTML file
<h1> {{ displayDate }} </h1>
It works fine for me ;-)
You can even try below option:
<a href="javascript:show_more_menu();">More >>></a>
BOTHER
appears to be available from <asm/termios.h>
on Linux. Pulling the definition from there is going to be wildly non-portable, but I assume this API is non-portable anyway, so it's probably no big loss.
you can use WMI module to do this on windows, though it's a lot clunkier than you unix folks are used to; import WMI
takes a long time and there's intermediate pain to get at the process.
Original sass
is ruby syntax-like, similar to ruby, jade etc...
In those syntaxes, we don't use {}
, instead we go with white spaces, also no usage of ;
...
In scss
syntaxes are more like CSS
, but with getting more options like: nesting, declaring, etc, similar to less
and other pre-processing CSS
...
They basically do the same thing, but I put couple of lines of each to see the syntax difference, look at the {}
, ;
, and spaces
:
SASS:
$width: 100px
$color: green
div
width: $width
background-color: $color
SCSS:
$width: 100px;
$color: green;
div {
width: $width;
background-color: $color;
}
I had this problem with getting "command not found" after install but I was installed into /usr/local as described in the solution above.
My problem seemed to be caused by me running the install with sudo. I did the following.
make sure you have correct path to extension folder
extension_dir = "ext"
by default it is commented with ; character
Check the errorlevel
in an if
statement, and then exit /b
(exit the batch file only, not the entire cmd.exe process) for values other than 0.
same-executable-over-and-over.exe /with different "parameters"
if %errorlevel% neq 0 exit /b %errorlevel%
If you want the value of the errorlevel to propagate outside of your batch file
if %errorlevel% neq 0 exit /b %errorlevel%
but if this is inside a for
it gets a bit tricky. You'll need something more like:
setlocal enabledelayedexpansion
for %%f in (C:\Windows\*) do (
same-executable-over-and-over.exe /with different "parameters"
if !errorlevel! neq 0 exit /b !errorlevel!
)
Edit: You have to check the error after each command. There's no global "on error goto" type of construct in cmd.exe/command.com batch. I've also updated my code per CodeMonkey, although I've never encountered a negative errorlevel in any of my batch-hacking on XP or Vista.
Just this!
$(function () {
$('#date').datetimepicker({
format: 'H:m',
});
});
i use v4 and work well!!
you can use localStorage for storing the json data:
the example is given below:-
let JSONDatas = [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"}
]
localStorage.setItem("datas", JSON.stringify(JSONDatas));
let data = JSON.parse(localStorage.getItem("datas"));
console.log(data);
This is what you need!
function onGeneratedRow(columnsResult)
{
var jsonData = {};
columnsResult.forEach(function(column)
{
var columnName = column.metadata.colName;
jsonData[columnName] = column.value;
});
viewData.employees.push(jsonData);
}
Use this as a sql query in your phpMyAdmin
SELECT CONCAT('ALTER TABLE ',table_schema,'.',table_name,' engine=InnoDB;')
FROM information_schema.tables
WHERE engine = 'MyISAM';
I have used this before and I think in order to make sure credential persist and in a best secure way is
ConfigurationManager
classSecureString
classCryptography
namespace.This link will be of great help I hope : Click here
package sn;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
final String username = "[email protected]";//
final String password = "0000000";
try{
Session session = Session.getDefaultInstance(props,
new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]",false));
msg.setSubject("Hello");
msg.setText("How are you");
msg.setSentDate(new Date());
Transport.send(msg);
System.out.println("Message sent.");
}catch (MessagingException e){
System.out.println("Erreur d'envoi, cause: " + e);
}
}
}
Warning: This may be a bit off topic, but oh well... ;)
I don't know what the original posters reason was for wanting the stack trace as string in the first place. When the stack trace should end up in an SLF4J/Logback LOG, but no exception was or should be thrown here's what I do:
public void remove(List<String> ids) {
if(ids == null || ids.isEmpty()) {
LOG.warn(
"An empty list (or null) was passed to {}.remove(List). " +
"Clearly, this call is unneccessary, the caller should " +
"avoid making it. A stacktrace follows.",
getClass().getName(),
new Throwable ("Stacktrace")
);
return;
}
// actual work, remove stuff
}
I like it because it does not require an external library (other than your logging backend, which will be in place most of the time anyway, of course).
Try it
<?php
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>
<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);
alert(count.length);
</script>
I solved the problem like this
public static String getUrlParameterValue(String url, String paramName) {
String value = "";
List<NameValuePair> result = null;
try {
result = URLEncodedUtils.parse(new URI(url), UTF_8);
value = result.stream().filter(pair -> pair.getName().equals(paramName)).findFirst().get().getValue();
System.out.println("--------------> \n" + paramName + " : " + value + "\n");
} catch (URISyntaxException e) {
e.printStackTrace();
}
return value;
}
Don't put quotes around the name of the file that you are trying to open; start "myfile.txt"
opens a new command prompt with the title myfile.txt
, while start myfile.txt
opens myfile.txt
in Notepad. There's no easy solution in the case where you want to start a console application with a space in its file name, but for other applications, start "" "my file.txt"
works.
sed -i "" -e $'4 a\\n''Project_Name=sowstest' start
You can try SQLBackupAndFTP. It will create scripts to create all the objects in your database and INSERT statements for all the rows in your tables. In any database you can run this script file and the entire database will be re-created.
Use DATE_FORMAT()
SELECT
DATE_FORMAT(NOW(), '%d %m %Y') AS your_date;
There are various alternative answers at this previous question - which admittedly was targeting an integer array as the source, but received generalised answers.
you can find it by running the following command
mysql --help
it will give you the mysql installed directory and all commands for mysql.
Here is my attempt. It has some common 'stupidity' checks built in, making sure you don't try to set or get a member which isn't available.
You could move those 'property_exists' checks to __set and __get respectively and call them directly within magic().
<?php
class Foo {
public $Name;
public function magic($member, $value = NULL) {
if ($value != NULL) {
if (!property_exists($this, $member)) {
trigger_error('Undefined property via magic(): ' .
$member, E_USER_ERROR);
return NULL;
}
$this->$member = $value;
} else {
if (!property_exists($this, $member)) {
trigger_error('Undefined property via magic(): ' .
$member, E_USER_ERROR);
return NULL;
}
return $this->$member;
}
}
};
$f = new Foo();
$f->magic("Name", "Something");
echo $f->magic("Name") , "\n";
// error
$f->magic("Fame", "Something");
echo $f->magic("Fame") , "\n";
?>
@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.
movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
var url:String = "http://site";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}
source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/
Use (keyup.enter)
.
Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter
pseudo-event.
Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern
it will create 0 byte file and not write anything:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false"/>
<param name="maxFileSize" value="1GB"/>
<param name="maxBackupIndex" value="2"/>
<param name="file" value="/tmp/bd.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<logger name="com.example.mypackage" additivity="false">
<level value="debug"/>
<appender-ref ref="bdfile"/>
</logger>
<root>
<priority value="info"/>
<appender-ref ref="bdfile"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration>
To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 tr
from rule one and add it to rule two.
table.rule1 tr td {
background-color: #ff0000;
}
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.
Don't forget to implement Serializable in every class your object will use like a list of objects. Else your app will crash.
Example:
public class City implements Serializable {
private List<House> house;
public List<House> getHouse() {
return house;
}
public void setHouse(List<House> house) {
this.house = house;
}}
Then House needs to implements Serializable as so :
public class House implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}}
Then you can use:
Bundle bundle = new Bundle();
bundle.putSerializable("city", city);
intent.putExtras(bundle);
And retreive it with:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
City city = (City)bundle.getSerializable("city");
If you want authentication try domainname\administrator as the username.
If you don't want authentication then remove all the tickboxes in the authenticated access section of the direcory security > edit window.
If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.
However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service
. The documentation says the following about Services:
A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.
These seems appropriate for your requirements.
its too late but i hope your issue will be solve quickly with this code. nothing to do more just put your code in below scrollview.
<HorizontalScrollView
android:id="@+id/scrollView"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
//xml code
</ScrollView>
</HorizontalScrollView>
You can also add --disable-session-crashed-bubble to eliminate the errors that come up after a crash or improper shutdown.
Alright so after trying every solution out there to solve this exact issues on a wordpress blog, I might have done something either really stupid or genius... With no idea why there's an increase in Mysql connections, I used the php script below in my header to kill all sleeping processes..
So every visitor to my site helps in killing the sleeping processes..
<?php
$result = mysql_query("SHOW processlist");
while ($myrow = mysql_fetch_assoc($result)) {
if ($myrow['Command'] == "Sleep") {
mysql_query("KILL {$myrow['Id']}");}
}
?>
Since I prefer to list required arguments before optional, I hack around it via:
parser = argparse.ArgumentParser()
parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
return parser.parse_args()
and this outputs:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
--optional_arg OPTIONAL_ARG
I can live without 'help' showing up in the optional arguments group.
Java 8:
int[] intArr = Arrays.stream(integerList).mapToInt(i->i).toArray();
cursor are used because in sub query we can fetch record row by row so we use cursor to fetch records
Example of cursor:
DECLARE @eName varchar(50), @job varchar(50)
DECLARE MynewCursor CURSOR -- Declare cursor name
FOR
Select eName, job FROM emp where deptno =10
OPEN MynewCursor -- open the cursor
FETCH NEXT FROM MynewCursor
INTO @eName, @job
PRINT @eName + ' ' + @job -- print the name
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM MynewCursor
INTO @ename, @job
PRINT @eName +' ' + @job -- print the name
END
CLOSE MynewCursor
DEALLOCATE MynewCursor
OUTPUT:
ROHIT PRG
jayesh PRG
Rocky prg
Rocky prg
Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
Builtin types that don't have constructors in the built-in namespace (e.g. functions, generators, methods) are in the types
module. You can use types.FunctionType
in an isinstance
call:
>>> import types
>>> types.FunctionType
<class 'function'>
>>> def f(): pass
>>> isinstance(f, types.FunctionType)
True
>>> isinstance(lambda x : None, types.FunctionType)
True
Note that this uses a very specific notion of "function" that is usually not what you need. For example, it rejects zip
(technically a class):
>>> type(zip), isinstance(zip, types.FunctionType)
(<class 'type'>, False)
open
(built-in functions have a different type):
>>> type(open), isinstance(open, types.FunctionType)
(<class 'builtin_function_or_method'>, False)
and random.shuffle
(technically a method of a hidden random.Random
instance):
>>> type(random.shuffle), isinstance(random.shuffle, types.FunctionType)
(<class 'method'>, False)
If you're doing something specific to types.FunctionType
instances, like decompiling their bytecode or inspecting closure variables, use types.FunctionType
, but if you just need an object to be callable like a function, use callable
.
I'm writing an updated answer for Python 3 to this question.
How is
__eq__
handled in Python and in what order?a == b
It is generally understood, but not always the case, that a == b
invokes a.__eq__(b)
, or type(a).__eq__(a, b)
.
Explicitly, the order of evaluation is:
b
's type is a strict subclass (not the same type) of a
's type and has an __eq__
, call it and return the value if the comparison is implemented,a
has __eq__
, call it and return it if the comparison is implemented,__eq__
and it has it, then call and return it if the comparison is implemented,is
.We know if a comparison isn't implemented if the method returns NotImplemented
.
(In Python 2, there was a __cmp__
method that was looked for, but it was deprecated and removed in Python 3.)
Let's test the first check's behavior for ourselves by letting B subclass A, which shows that the accepted answer is wrong on this count:
class A:
value = 3
def __eq__(self, other):
print('A __eq__ called')
return self.value == other.value
class B(A):
value = 4
def __eq__(self, other):
print('B __eq__ called')
return self.value == other.value
a, b = A(), B()
a == b
which only prints B __eq__ called
before returning False
.
The other answers here seem incomplete and out of date, so I'm going to update the information and show you how how you could look this up for yourself.
This is handled at the C level.
We need to look at two different bits of code here - the default __eq__
for objects of class object
, and the code that looks up and calls the __eq__
method regardless of whether it uses the default __eq__
or a custom one.
__eq__
Looking __eq__
up in the relevant C api docs shows us that __eq__
is handled by tp_richcompare
- which in the "object"
type definition in cpython/Objects/typeobject.c
is defined in object_richcompare
for case Py_EQ:
.
case Py_EQ:
/* Return NotImplemented instead of False, so if two
objects are compared, both get a chance at the
comparison. See issue #1393. */
res = (self == other) ? Py_True : Py_NotImplemented;
Py_INCREF(res);
break;
So here, if self == other
we return True
, else we return the NotImplemented
object. This is the default behavior for any subclass of object that does not implement its own __eq__
method.
__eq__
gets calledThen we find the C API docs, the PyObject_RichCompare function, which calls do_richcompare
.
Then we see that the tp_richcompare
function, created for the "object"
C definition is called by do_richcompare
, so let's look at that a little more closely.
The first check in this function is for the conditions the objects being compared:
__eq__
method,then call the other's method with the arguments swapped, returning the value if implemented. If that method isn't implemented, we continue...
if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
(f = Py_TYPE(w)->tp_richcompare) != NULL) {
checked_reverse_op = 1;
res = (*f)(w, v, _Py_SwappedOp[op]);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
Next we see if we can lookup the __eq__
method from the first type and call it.
As long as the result is not NotImplemented, that is, it is implemented, we return it.
if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
res = (*f)(v, w, op);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
Else if we didn't try the other type's method and it's there, we then try it, and if the comparison is implemented, we return it.
if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
res = (*f)(w, v, _Py_SwappedOp[op]);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
}
Finally, we get a fallback in case it isn't implemented for either one's type.
The fallback checks for the identity of the object, that is, whether it is the same object at the same place in memory - this is the same check as for self is other
:
/* If neither object implements it, provide a sensible default
for == and !=, but raise an exception for ordering. */
switch (op) {
case Py_EQ:
res = (v == w) ? Py_True : Py_False;
break;
In a comparison, we respect the subclass implementation of comparison first.
Then we attempt the comparison with the first object's implementation, then with the second's if it wasn't called.
Finally we use a test for identity for comparison for equality.
The Underscore library also provides a "delay" function:
_.delay(function(msg) { console.log(msg); }, 5000, 'Hello');
How are you calling the start function?
This should work (new is the key)
var o = new Request(destination, stay_open);
o.start();
If you directly call it like Request.prototype.start()
, this
will refer to the global context (window
in browsers).
Also, if this
is undefined, it results in an error. The if expression does not evaluate to false.
Update: this
object is not set based on declaration, but by invocation. What it means is that if you assign the function property to a variable like x = o.start
and call x()
, this
inside start no longer refers to o
. This is what happens when you do setTimeout
. To make it work, do this instead:
var o = new Request(...);
setTimeout(function() { o.start(); }, 1000);
Doing
SET FOREIGN_KEY_CHECKS=0;
before the Operation can also do the trick.
import React, { Component } from 'react';
This is a spelling error, you need to type React
instead of react
.
Another way that this can unfold, and just did for me, is if you have a build error that Eclipse doesn't tell you about. If compiling the unit test fails then there is no .class file and you will get the ClassNotFoundException.
In my case there was a missing 3rd party jar file. When I ran the test I got a pop-up window that said "Errors exist in required project(s)". I work with a huge project and I always get that message because some of the source is not available to eclipse (long story). Also it doesn't say what the errors are. So I click "Continue" and then I get the exception.
Once I realized what was going on it was easy to fix by adding the missing jar to the classpath under Run -> Debug Configurations...
I'm not sure how to best detect or prevent this from happening except to be aware of this possibility when something goes wrong and to review your most recent changes for what might have gone wrong.
Drawing text in plain OpenGL isn't a straigth-forward task. You should probably have a look at libraries for doing this (either by using a library or as an example implementation).
Some good starting points could be GLFont, OpenGL Font Survey and NeHe Tutorial for Bitmap Fonts (Windows).
Note that bitmaps are not the only way of achieving text in OpenGL as mentioned in the font survey.
This sounds like a scenario where zeroMQ would be a good fit. It's a messaging framework that's similar to using TCP or Unix sockets, but it's much more robust (http://zguide.zeromq.org/py:all)
There's a library that uses zeroMQ to provide a RPC framework that works pretty well. It's called zeroRPC (http://www.zerorpc.io/). Here's the hello world.
Python "Hello x" server:
import zerorpc
class HelloRPC(object):
'''pass the method a name, it replies "Hello name!"'''
def hello(self, name):
return "Hello, {0}!".format(name)
def main():
s = zerorpc.Server(HelloRPC())
s.bind("tcp://*:4242")
s.run()
if __name__ == "__main__" : main()
And the node.js client:
var zerorpc = require("zerorpc");
var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
//calls the method on the python object
client.invoke("hello", "World", function(error, reply, streaming) {
if(error){
console.log("ERROR: ", error);
}
console.log(reply);
});
Or vice-versa, node.js server:
var zerorpc = require("zerorpc");
var server = new zerorpc.Server({
hello: function(name, reply) {
reply(null, "Hello, " + name, false);
}
});
server.bind("tcp://0.0.0.0:4242");
And the python client
import zerorpc, sys
c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
name = sys.argv[1] if len(sys.argv) > 1 else "dude"
print c.hello(name)
Time complexity is O(E+V)
instead of O(2E+V)
because if the time complexity is n^2+2n+7 then it is written as O(n^2).
Hence, O(2E+V) is written as O(E+V)
because difference between n^2 and n matters but not between n and 2n.
Having had a similar problem with data from 1800 to now, this worked for me:
data2$date=as.character(data2$date)
lct <- Sys.getlocale("LC_TIME");
Sys.setlocale("LC_TIME","C")
data2$date<- as.Date(data2$date, format = "%Y %m %d") # and it works
Add any file in the documentation which will include your content, for example toc.h:
@ mainpage Manual SDK
<hr/>
@ section pageTOC Content
-# @ref Description
-# @ref License
-# @ref Item
...
And in your Doxyfile
:
INPUT = toc.h \
Example (in Russian):
We will be looking at two approaches to achieve this. With and without using jQuery.
You need to add a keyup function to both of your password and confirm password fields. The reason being that the text equality should be checked even if the password
field changes. Thanks @kdjernigan for pointing that out
In this way, when you type in the field you will know if the password is same or not:
$('#password, #confirm_password').on('keyup', function () {
if ($('#password').val() == $('#confirm_password').val()) {
$('#message').html('Matching').css('color', 'green');
} else
$('#message').html('Not Matching').css('color', 'red');
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
<input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
<span id='message'></span>
</label>
_x000D_
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/
We will use the onkeyup event of javascript on both the fields to achieve the same effect.
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'matching';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'not matching';
}
}
_x000D_
<label>password :
<input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onkeyup='check();' />
<span id='message'></span>
</label>
_x000D_
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/
If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate
to perform this operation, I would suggest the use of np.column_stack:
In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
[2, 5],
[3, 6]])
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
This is how I did it in 2021
Let us say I have a csv sales.csv
which has the following data in it:
sales.csv:
Order Name,Price,Qty
oil,200,2
butter,180,10
and to add more rows I can load them in a data frame and append it to the csv like this:
import pandas
data = [
['matchstick', '60', '11'],
['cookies', '10', '120']
]
dataframe = pandas.DataFrame(data)
dataframe.to_csv("sales.csv", index=False, mode='a', header=False)
and the output will be:
Order Name,Price,Qty
oil,200,2
butter,180,10
matchstick,60,11
cookies,10,120
all of above answers would help you but you have to add three ports in the firewall of PC on which SQL Server is installed.
Add new TCP Local port in Windows firewall at port no. 1434
Add new program for SQL Server and select sql server.exe Path: C:\ProgramFiles\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn\sqlservr.exe
Add new program for SQL Browser and select sqlbrowser.exe Path: C:\ProgramFiles\Microsoft SQL Server\90\Shared\sqlbrowser.exe
The following will do.
unsigned int x = 1;
printf ("%d", (int) (((char *)&x)[0]));
And setting &x
to char *
will enable you to access the individual bytes of the integer, and the ordering of bytes will depend on the endianness of the system.
Four little additions to the accepted solution:
Complete solution that seems to work for most browsers:
CSS
html.noscroll {
position: fixed;
overflow-y: scroll;
width: 100%;
}
Disable scroll
if ($(document).height() > $(window).height()) {
var scrollTop = ($('html').scrollTop()) ? $('html').scrollTop() : $('body').scrollTop(); // Works for Chrome, Firefox, IE...
$('html').addClass('noscroll').css('top',-scrollTop);
}
Enable scroll
var scrollTop = parseInt($('html').css('top'));
$('html').removeClass('noscroll');
$('html,body').scrollTop(-scrollTop);
Thanks to Fabrizio and Dejan for putting me on the right track and to Brodingo for the solution to the double scroll bar
Your problem may have been due to a deficiency in an earlier version of Swift or of the Xcode Beta. Working with Xcode Version 6.0 (6A279r) on August 21, 2014, your code works as expected with this output:
column: 0 row: 0 value:1.0 column: 0 row: 1 value:4.0 column: 0 row: 2 value:7.0 column: 1 row: 0 value:2.0 column: 1 row: 1 value:5.0 column: 1 row: 2 value:8.0 column: 2 row: 0 value:3.0 column: 2 row: 1 value:6.0 column: 2 row: 2 value:9.0
I just copied and pasted your code into a Swift playground and defined two constants:
let NumColumns = 3, NumRows = 3
Nice question/answers.
Just want to point out that C pointers and arrays are not the same, although in this case the difference is not essential.
Consider the following declarations:
int a[10];
int* p = a;
In a.out
, the symbol a
is at an address that's the beginning of the array, and symbol p
is at an address where a pointer is stored, and the value of the pointer at that memory location is the beginning of the array.
The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.
Additionally, it is supported in Python 2.7, as explained in this comment:
PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.
From a question I asked not long ago:
Conditional operator cannot cast implicitly?
Given:
Bool aBoolValue;
Where aBoolValue
is assigned either True or False;
The following will not compile:
Byte aByteValue = aBoolValue ? 1 : 0;
But this would:
Int anIntValue = aBoolValue ? 1 : 0;
The answer provided is pretty good too.
<ProgressBar
android:minHeight="20dip"
android:maxHeight="20dip"/>
I use Xcode 7 and Swift 2. Last, I had made:
class ViewController: UIViewController{ var time: NSTimer //error this here }
Then I fix: class ViewController: UIViewController {
var time: NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
//self.movetoHome()
time = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(ViewController.movetoHome), userInfo: nil, repeats: false)
//performSegueWithIdentifier("MoveToHome", sender: self)
//presentViewController(<#T##viewControllerToPresent: UIViewController##UIViewController#>, animated: <#T##Bool#>, completion: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>)
}
func movetoHome(){
performSegueWithIdentifier("MoveToHome", sender: self)
}
}
The problem is you are not linking to the jQuery UI library (which is where datepicker resides):
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<div class="demo">
<p>Date: <input type="text" id="datepicker"></p>
</div><!-- End demo -->
</body>
</HTML>
As an alternative to using ExpectedException
attribute, I sometimes define two helpful methods for my test classes:
AssertThrowsException()
takes a delegate and asserts that it throws the expected exception with the expected message.
AssertDoesNotThrowException()
takes the same delegate and asserts that it does not throw an exception.
This pairing can be very useful when you want to test that an exception is thrown in one case, but not the other.
Using them my unit test code might look like this:
ExceptionThrower callStartOp = delegate(){ testObj.StartOperation(); };
// Check exception is thrown correctly...
AssertThrowsException(callStartOp, typeof(InvalidOperationException), "StartOperation() called when not ready.");
testObj.Ready = true;
// Check exception is now not thrown...
AssertDoesNotThrowException(callStartOp);
Nice and neat huh?
My AssertThrowsException()
and AssertDoesNotThrowException()
methods are defined on a common base class as follows:
protected delegate void ExceptionThrower();
/// <summary>
/// Asserts that calling a method results in an exception of the stated type with the stated message.
/// </summary>
/// <param name="exceptionThrowingFunc">Delegate that calls the method to be tested.</param>
/// <param name="expectedExceptionType">The expected type of the exception, e.g. typeof(FormatException).</param>
/// <param name="expectedExceptionMessage">The expected exception message (or fragment of the whole message)</param>
protected void AssertThrowsException(ExceptionThrower exceptionThrowingFunc, Type expectedExceptionType, string expectedExceptionMessage)
{
try
{
exceptionThrowingFunc();
Assert.Fail("Call did not raise any exception, but one was expected.");
}
catch (NUnit.Framework.AssertionException)
{
// Ignore and rethrow NUnit exception
throw;
}
catch (Exception ex)
{
Assert.IsInstanceOfType(expectedExceptionType, ex, "Exception raised was not the expected type.");
Assert.IsTrue(ex.Message.Contains(expectedExceptionMessage), "Exception raised did not contain expected message. Expected=\"" + expectedExceptionMessage + "\", got \"" + ex.Message + "\"");
}
}
/// <summary>
/// Asserts that calling a method does not throw an exception.
/// </summary>
/// <remarks>
/// This is typically only used in conjunction with <see cref="AssertThrowsException"/>. (e.g. once you have tested that an ExceptionThrower
/// method throws an exception then your test may fix the cause of the exception and then call this to make sure it is now fixed).
/// </remarks>
/// <param name="exceptionThrowingFunc">Delegate that calls the method to be tested.</param>
protected void AssertDoesNotThrowException(ExceptionThrower exceptionThrowingFunc)
{
try
{
exceptionThrowingFunc();
}
catch (NUnit.Framework.AssertionException)
{
// Ignore and rethrow any NUnit exception
throw;
}
catch (Exception ex)
{
Assert.Fail("Call raised an unexpected exception: " + ex.Message);
}
}
Modified code of Tapas's answer:
Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
username = oReturn("UserName")
Next
The no-js
class gets removed by a javascript script, so you can modify/display/hide things using css if js is disabled.
You are declaring button1 in main method so you can not access it in actionPerform. You should make it global in class.
JButton button1;
public static void main(String[] args) {
JFrame calcFrame = new JFrame();
calcFrame.setSize(100, 100);
calcFrame.setVisible(true);
button1 = new JButton("1");
button1.addActionListener(this);
calcFrame.add(button1);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1)
}
I found this answer to the question:
http://padcom13.blogspot.co.uk/2011/10/creating-standalone-applications-with.html
Not only do you get the dependent lib files in a lib folder, you also get a bin director with both a unix and a dos executable.
The executable ultimately calls java with a -cp argument that lists all of your dependent libs too.
The whole lot sits in an appasembly folder inside the target folder. Epic.
============= Yes I know this is an old thread, but it's still coming high on search results so I thought it might help someone like me.
[id^=product]
^=
indicates "starts with". Conversely, $=
indicates "ends with".
The symbols are actually borrowed from Regex syntax, where ^
and $
mean "start of string" and "end of string" respectively.
See the specs for full information.
I think AWK is the best and efficient command to resolve your problem. AWK is included by default in almost every Linux distribution.
echo "[email protected];[email protected]" | awk -F';' '{print $1,$2}'
will give
[email protected] [email protected]
Of course your can store each email address by redefining the awk print field.
There is a library for this purpose: https://github.com/bestiejs/platform.js#readme
Then you can use it this way
// example 1
platform.os; // 'Windows Server 2008 R2 / 7 x64'
// example 2 on an iPad
platform.os; // 'iOS 5.0'
// you can also access on the browser and some other properties
platform.name; // 'Safari'
platform.version; // '5.1'
platform.product; // 'iPad'
platform.manufacturer; // 'Apple'
platform.layout; // 'WebKit'
// or use the description to put all together
platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)'
in Xcode 8.3.2, iOS 10.3 Thats is good to now
Sample1:
let dayMoveRaw = 5
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05
Sample2:
let dayMoveRaw = 55
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55
Not sure why you'd want to, but the C# way would be
string[] newArray = new string[0];
I'm guessing that VB won't be too dissimilar to this.
If you're building an empty array so you can populate it with values later, you really should consider using
List<string>
and converting it to an array (if you really need it as an array) with
newListOfString.ToArray();
I had a slightly different problem. Instead of incrementing a local variable in the forEach, I needed to assign an object to the local variable.
I solved this by defining a private inner domain class that wraps both the list I want to iterate over (countryList) and the output I hope to get from that list (foundCountry). Then using Java 8 "forEach", I iterate over the list field, and when the object I want is found, I assign that object to the output field. So this assigns a value to a field of the local variable, not changing the local variable itself. I believe that since the local variable itself is not changed, the compiler doesn't complain. I can then use the value that I captured in the output field, outside of the list.
Domain Object:
public class Country {
private int id;
private String countryName;
public Country(int id, String countryName){
this.id = id;
this.countryName = countryName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
Wrapper object:
private class CountryFound{
private final List<Country> countryList;
private Country foundCountry;
public CountryFound(List<Country> countryList, Country foundCountry){
this.countryList = countryList;
this.foundCountry = foundCountry;
}
public List<Country> getCountryList() {
return countryList;
}
public void setCountryList(List<Country> countryList) {
this.countryList = countryList;
}
public Country getFoundCountry() {
return foundCountry;
}
public void setFoundCountry(Country foundCountry) {
this.foundCountry = foundCountry;
}
}
Iterate operation:
int id = 5;
CountryFound countryFound = new CountryFound(countryList, null);
countryFound.getCountryList().forEach(c -> {
if(c.getId() == id){
countryFound.setFoundCountry(c);
}
});
System.out.println("Country found: " + countryFound.getFoundCountry().getCountryName());
You could remove the wrapper class method "setCountryList()" and make the field "countryList" final, but I did not get compilation errors leaving these details as-is.
You can use display:inline-block
instead of float
and vertical-align:middle
with this CSS:
.col-lg-4, .col-lg-8 {
float:none;
display:inline-block;
vertical-align:middle;
margin-right:-4px;
}
The demo http://bootply.com/94402
Have a look at the android SDK system requirements Here
I'm guessing some extra RAM would help your developing experience...Also the emulator does take some time to start on even the speediest systems.
the simple answer to your question would be Triangulation. Which is essentially the concept in all GPS devices, I would give this article a read to learn more about how Google goes about doing this: http://www.computerworld.com/s/article/9127462/FAQ_How_Google_Latitude_locates_you_?taxonomyId=15&pageNumber=2.
From my understanding, they use a service similar to Skyhook, which is a location software that determines your location based on your wifi/cellphone signals. In order to achieve their accuracy, these services have large servers of databases that store location information on these cell towers and wifi access points - they actually survey metropolitan areas to keep it up to date. In order for you to achieve something similar, I would assume you'd have to use a service like Skyhook - you can use their SDK ( http://www.skyhookwireless.com/location-technology/ ).
However, if you want to do something internal (like using your own routers' locations) - then you'd likely have to create an algorithm that mimics Triangulation. You'll have to find a way to get the signal_strength
and mac_address
of the device and use that information along with the locations of your routers to come up with the location. You can probably get the information about devices hooked up to your routers by doing something similar to this ( http://www.makeuseof.com/tag/check-stealing-wifi/ ).
I have tried to compile everything that needs to be done for self-hosting icons in my answer. You need to follow these 4 simple steps.
Open the iconfont folder of the materialize repository
link- https://github.com/google/material-design-icons/tree/master/iconfont
Download these three icons files ->
MaterialIcons-Regular.woff2 - format('woff2')
MaterialIcons-Regular.woff - format('woff')
MaterialIcons-Regular.ttf - format('truetype');
Note- After Download you can rename it to whatever you like.
Now, go to your CSS and add this code
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url(MaterialIcons-Regular.eot); /* For IE6-8 */
src: local('Material Icons'),
local('MaterialIcons-Regular'),
url(MaterialIcons-Regular.woff2) format('woff2'),
url(MaterialIcons-Regular.woff) format('woff'),
url(MaterialIcons-Regular.ttf) format('truetype');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px; /* Preferred icon size */
display: inline-block;
line-height: 1;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
white-space: nowrap;
direction: ltr;
/* Support for all WebKit browsers. */
-webkit-font-smoothing: antialiased;
/* Support for Safari and Chrome. */
text-rendering: optimizeLegibility;
/* Support for Firefox. */
-moz-osx-font-smoothing: grayscale;
/* Support for IE. */
font-feature-settings: 'liga';
}
_x000D_
Note : The address provided in src:url(...) should be with respect to the 'CSS File' and not the index.html file. For example it can be src : url(../myicons/MaterialIcons-Regular.woff2)
<i class="material-icons">face</i>
_x000D_
Click here to see all the icons that can be used.
@Inject
instead of Spring’s @Autowired
to inject a bean.
@Named
instead of Spring’s @Component
to declare a bean.
Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar
is in your classpath)
If you do not want to handle separate properties for each possible argument, I suggest you'd use:
<arg line="${args}"/>
You can check if the property is not set using a specific target with an unless
attribute and inside do:
<input message="Type the desired command line arguments:" addProperty="args"/>
Putting it all together gives:
<target name="run" depends="compile, input-runargs" description="run the project">
<!-- You can use exec here, depending on your needs -->
<java classname="Main">
<arg line="${args}"/>
</java>
</target>
<target name="input-runargs" unless="args" description="prompts for command line arguments if necessary">
<input addProperty="args" message="Type the desired command line arguments:"/>
</target>
You can use it as follows:
ant
ant run
ant run -Dargs='--help'
The first two commands will prompt for the command-line arguments, whereas the latter won't.
This can be solved 100% entirely with HTML alone. Just set the href
attribute to "data:(mimetypeheader),(url)"
. For instance...
<a
href="data:video/mp4,http://www.example.com/video.mp4"
target="_blank"
download="video.mp4"
>Download Video</a>
Working example: JSFiddle Demo.
Because we use a Data URL, we are allowed to set the mimetype which indicates the type of data to download. Documentation:
Data URLs are composed of four parts: a prefix (data:), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself. (Source: MDN Web Docs: Data URLs.)
Components:
<a ...>
: The link tag.href="data:video/mp4,http://www.example.com/video.mp4"
: Here we are setting the link to the a data:
with a header preconfigured to video/mp4
. This is followed by the header mimetype. I.E., for a .txt
file, it would would be text/plain
. And then a comma separates it from the link we want to download.target="_blank"
: This indicates a new tab should be opened, it's not essential, but it helps guide the browser to the desired behavior.download
: This is the name of the file you're downloading.you export the project from Eclipse and then import the project from Android Studio, this should solve your problem, open a eclipse project without importing it from Android Studio you can cause problems, look at: (Excuse my language, I speak Spanish.) http://developer.android.com/intl/es/sdk/installing/migrate.html
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<c:set var="val" value="5"/>
<c:choose>
<c:when test="${val == '5'}">
Value is 5
</c:when>
<c:otherwise>
Value is not 5
</c:otherwise>
</c:choose>
I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.
I got it finally right with pure CSS by following these instructions:
http://tjvantoll.com/2012/11/10/creating-cross-browser-scrollable-tbody/
The first step is to set the <tbody>
to display: block so an overflow and height can be applied. From there the rows in the <thead>
need to be set to position: relative and display: block so that they’ll sit on top of the now scrollable <tbody>
.
tbody, thead { display: block; overflow-y: auto; }
Because the <thead>
is relatively positioned each table cell needs an explicit width
td:nth-child(1), th:nth-child(1) { width: 100px; }
td:nth-child(2), th:nth-child(2) { width: 100px; }
td:nth-child(3), th:nth-child(3) { width: 100px; }
But unfortunately that is not enough. When a scrollbar is present browsers allocate space for it, therefore, the <tbody>
ends up having less space available than the <thead>
. Notice the slight misalignment this creates...
The only workaround I could come up with was to set a min-width on all columns except the last one.
td:nth-child(1), th:nth-child(1) { min-width: 100px; }
td:nth-child(2), th:nth-child(2) { min-width: 100px; }
td:nth-child(3), th:nth-child(3) { width: 100px; }
Whole codepen example below:
CSS:
.fixed_headers {
width: 750px;
table-layout: fixed;
border-collapse: collapse;
}
.fixed_headers th {
text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
padding: 5px;
text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
width: 350px;
}
.fixed_headers thead {
background-color: #333333;
color: #fdfdfd;
}
.fixed_headers thead tr {
display: block;
position: relative;
}
.fixed_headers tbody {
display: block;
overflow: auto;
width: 100%;
height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
background-color: #dddddd;
}
.old_ie_wrapper {
height: 300px;
width: 750px;
overflow-x: hidden;
overflow-y: auto;
}
.old_ie_wrapper tbody {
height: auto;
}
Html:
<!-- IE < 10 does not like giving a tbody a height. The workaround here applies the scrolling to a wrapped <div>. -->
<!--[if lte IE 9]>
<div class="old_ie_wrapper">
<!--<![endif]-->
<table class="fixed_headers">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Red</td>
<td>These are red.</td>
</tr>
<tr>
<td>Pear</td>
<td>Green</td>
<td>These are green.</td>
</tr>
<tr>
<td>Grape</td>
<td>Purple / Green</td>
<td>These are purple and green.</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
<td>These are orange.</td>
</tr>
<tr>
<td>Banana</td>
<td>Yellow</td>
<td>These are yellow.</td>
</tr>
<tr>
<td>Kiwi</td>
<td>Green</td>
<td>These are green.</td>
</tr>
<tr>
<td>Plum</td>
<td>Purple</td>
<td>These are Purple</td>
</tr>
<tr>
<td>Watermelon</td>
<td>Red</td>
<td>These are red.</td>
</tr>
<tr>
<td>Tomato</td>
<td>Red</td>
<td>These are red.</td>
</tr>
<tr>
<td>Cherry</td>
<td>Red</td>
<td>These are red.</td>
</tr>
<tr>
<td>Cantelope</td>
<td>Orange</td>
<td>These are orange inside.</td>
</tr>
<tr>
<td>Honeydew</td>
<td>Green</td>
<td>These are green inside.</td>
</tr>
<tr>
<td>Papaya</td>
<td>Green</td>
<td>These are green.</td>
</tr>
<tr>
<td>Raspberry</td>
<td>Red</td>
<td>These are red.</td>
</tr>
<tr>
<td>Blueberry</td>
<td>Blue</td>
<td>These are blue.</td>
</tr>
<tr>
<td>Mango</td>
<td>Orange</td>
<td>These are orange.</td>
</tr>
<tr>
<td>Passion Fruit</td>
<td>Green</td>
<td>These are green.</td>
</tr>
</tbody>
</table>
<!--[if lte IE 9]>
</div>
<!--<![endif]-->
EDIT: Alternative solution for table width 100% (above actually is for fixed width and didn't answer the question):
HTML:
<table>
<thead>
<tr>
<th>Name</th>
<th>Color</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Red</td>
<td>These are red.</td>
</tr>
<tr>
<td>Pear</td>
<td>Green</td>
<td>These are green.</td>
</tr>
<tr>
<td>Grape</td>
<td>Purple / Green</td>
<td>These are purple and green.</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
<td>These are orange.</td>
</tr>
<tr>
<td>Banana</td>
<td>Yellow</td>
<td>These are yellow.</td>
</tr>
<tr>
<td>Kiwi</td>
<td>Green</td>
<td>These are green.</td>
</tr>
</tbody>
</table>
CSS:
table {
width: 100%;
text-align: left;
min-width: 610px;
}
tr {
height: 30px;
padding-top: 10px
}
tbody {
height: 150px;
overflow-y: auto;
overflow-x: hidden;
}
th,td,tr,thead,tbody { display: block; }
td,th { float: left; }
td:nth-child(1),
th:nth-child(1) {
width: 20%;
}
td:nth-child(2),
th:nth-child(2) {
width: 20%;
float: left;
}
td:nth-child(3),
th:nth-child(3) {
width: 59%;
float: left;
}
/* some colors */
thead {
background-color: #333333;
color: #fdfdfd;
}
table tbody tr:nth-child(even) {
background-color: #dddddd;
}
Options are:
Read through the above links before taking a call
The option I use is as follows:
columns.Bound(p => p.OrderDate).Format("{0:d}").ClientTemplate("#=formatDate(OrderDate)#");
function formatDate(OrderDate) {
var formatedOrderDate = kendo.format("{0:d}", OrderDate);
return formatedOrderDate;
}
Here is a simpler way to migrate:
Start off with a sample Android Studio project. Open android studio and create a new project (or) just download a ‘sample’ studio project here: https://github.com/AppLozic/eclipse-to-android-studio-migration. Now, open the downloaded project in Android Studio by following the below instructions.
Import eclipse project modules into Android Studio. Select File -> New -> Import Module Image title
Next, select the path of the eclipse project and import the modules. In case, if you see the message “Failed to sync Gradle project,” then click on “Install Build Tools and sync project…”
Now, remove the sample project modules by following the below simple steps:
Open settings.gradle and remove “include ‘:app’” Right click on “app” module and “Delete” it. Now, what we have is the Eclipse project open in Android studio with the Gradle build.
Here are few other links which might help you:
http://developer.android.com/sdk/installing/migrate.html Source: http://www.applozic.com/blog/migrating-project-from-eclipse-to-studio/
var eventids = GetEventIdsByEventDate(DateTime.Now);
var result = eventsdb.Where(e => eventids.Contains(e));
If you are returnning List<EventFeed>
inside the method, you should change the method return type from IEnumerable<EventFeed>
to List<EventFeed>
.
Why not use the html5 date control as it is, with other attributes that allows it work ok on browsers that support date type and still works on other browsers like firefox that is yet to support date type
<input type="date" name="input1" placeholder="YYYY-MM-DD" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" title="Enter a date in this formart YYYY-MM-DD"/>
I like and learned a lot from Lasse V. Karlsen. I modified it into the following example, which highlights pretty well the difference between shallow dictionary copies and deep copies:
import copy
my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
my_copy = copy.copy(my_dict)
my_deepcopy = copy.deepcopy(my_dict)
Now if you change
my_dict['a'][2] = 7
and do
print("my_copy a[2]: ",my_copy['a'][2],",whereas my_deepcopy a[2]: ", my_deepcopy['a'][2])
you get
>> my_copy a[2]: 7 ,whereas my_deepcopy a[2]: 3
The fix is to modify your EDMX file, using the XML editor, and change the value of ProviderManifestToken from 2012 to 2008. I found that on line 7 in my EDMX file. After saving that change, the paging SQL will be generated using the “old”, SQL Server 2008 compatible syntax.
My apologies for posting an answer on this very old thread. Posting it for the people like me, I solved this issue today.
On Ubuntu 14 and Mysql 5.5.53 this setting seems to be enabled by default. To disable it you need to add secure-file-priv = ""
to your my.cnf file under the mysqld config group. eg:-
[mysqld]
secure-file-priv = ""
This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.
As complement of this answer you can use $
to get the end matches and *
to get matches anywhere in the value name.
Matches anywhere: .col-md
, .left-col
, .col
, .tricolor
, etc.
[class*="col"]
Matches at the beginning: .col-md
, .col-sm-6
, etc.
[class^="col-"]
Matches at the ending: .left-col
, .right-col
, etc.
[class$="-col"]
Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:
import datetime
print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())
today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))
schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)
The output:
Timestamp: 2014-10-18 21:31:12
Timestamp: 2014-Oct-18 21:31:12
Date now: 2014-10-18 21:31:12.318340
Date today: 2014-10-18
Today's date is Oct, 18 2014
Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific
Maintenance: October, 18 2014 - 1 PM to 6 PM Central
Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
$('#content').toggle('show');
});
});
</script>
And the html
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
Pretty sure nobody answer your question to your exact terms, you want it for dynamic text
var newString = myString.substring( myString.indexOf( "," ) +1, myString.length );
It takes a substring from the first comma, to the end
If you see your error message it says
Building in workspace /var/lib/jenkins/workspace/AutoScript
and as per your comments you have put urltest.sh in
/var/lib/jenkins
Hence Jenkins is not able to find the file. In your build step do this thing, it will work
cd # which will point to /var/lib/jenkins
./urltest.sh # it will run your script
If it still fails try to chown the file as jenkin user may not have file permission, but I think if you do above step you will be able to run.
Assuming you have:
HashMap<Key, Value> map; // Assigned or populated somehow.
For a list of values:
List<Value> values = new ArrayList<Value>(map.values());
For a list of keys:
List<Key> keys = new ArrayList<Key>(map.keySet());
Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.
public static T DeserializeFromXml<T>(string xml)
{
T result;
XmlSerializerFactory serializerFactory = new XmlSerializerFactory();
XmlSerializer serializer =serializerFactory.CreateSerializer(typeof(T));
using (StringReader sr3 = new StringReader(xml))
{
XmlReaderSettings settings = new XmlReaderSettings()
{
CheckCharacters = false // default value is true;
};
using (XmlReader xr3 = XmlTextReader.Create(sr3, settings))
{
result = (T)serializer.Deserialize(xr3);
}
}
return result;
}
You can use the util library that comes with nodejs to get a promise from the exec command and can use that output as you need. Use restructuring to store the stdout and stderr in variables.
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function lsExample() {
const {
stdout,
stderr
} = await exec('ls');
console.log('stdout:', stdout);
console.error('stderr:', stderr);
}
lsExample();
_x000D_
Add a helper class:
public static class Redirector {
public static void RedirectTo(this Controller ct, string action) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action));
}
public static void RedirectTo(this Controller ct, string action, string controller) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller));
}
public static void RedirectTo(this Controller ct, string action, string controller, object routeValues) {
UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);
ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller, routeValues));
}
}
Then call in your action:
this.RedirectTo("Index", "Cement");
Add javascript code to any global javascript included file or layout file to intercept all ajax requests:
<script type="text/javascript">_x000D_
$(function() {_x000D_
$(document).ajaxComplete(function (event, xhr, settings) {_x000D_
var urlHeader = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
_x000D_
if (urlHeader != null && urlHeader !== undefined) {_x000D_
window.location = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
}_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
The HTML tabindex atribute is responsible for indicating if an element is reachable by keyboard navigation. When the user presses the Tab key the focus is shifted from one element to another. By using the tabindex atribute, the tab order flow is shifted.
You'll have to pass the new ordinal position to insert
using len
in this case:
In [62]:
a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]
This worked for me:
file = open('docs/my_messy_doc.pdf', 'rb')
Make sure you choose the right project intepreter in the compiler. I used the Pycharm, and I encountered the same problem. And it was solved by choose the right intepreter. Thisvideo may help you.
In my case, detach
and attach
worked:
getSupportFragmentManager()
.beginTransaction()
.detach(contentFragment)
.attach(contentFragment)
.commit();
Don't use the classes in thejava.io
package, instead use the java.nio
package . The latter has a FileLock
class. You can apply a lock to a FileChannel
.
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
/*
use channel.lock OR channel.tryLock();
*/
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Release the lock - if it is not null!
if( lock != null ) {
lock.release();
}
// Close the file
channel.close();
} catch (Exception e) {
}
To get the total size of directory or the total size of file use,
du -csh <directory or filename*> | grep total
#include <QFile>
#include <QCoreApplication>
#include <QTextStream>
int main(int argc, char *argv[])
{
// Create a new file
QFile file("out.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << "This file is generated by Qt\n";
// optional, as QFile destructor will already do it:
file.close();
//this would normally start the event loop, but is not needed for this
//minimal example:
//return app.exec();
return 0;
}
I had the following configuration in my httpd.conf that denied executing the wpadmin/setup-config.php file from wordpress. Removing the |-config part solved the problem. I think this httpd.conf is from plesk but it could be some default suggested config from wordpress, i don't know. Anyway, I could safely add it back after the setup finished.
<LocationMatch "(?i:(?:wp-config\\.bak|\\.wp-config\\.php\\.swp|(?:readme|license|changelog|-config|-sample)\\.(?:php|md|txt|htm|html)))">
Require all denied
</LocationMatch>
Unfortunately solution provided by @hakani is not two-way binding. It just handles One-way changing model from UI/FrontEnd part.
Instead the simple:
<input [(ngModel)]="checkboxFlag" type="checkbox"/>
will do two-way binding for checkbox.
Afterwards, when Model checkboxFlag is changed from Backend or UI part - voila, checkboxFlag stores actual checkbox state.
To be sure I've prepared Plunker code to present the result : https://plnkr.co/edit/OdEAPWRoqaj0T6Yp0Mfk
Just to complete this answer you should include the import { FormsModule } from '@angular/forms'
into app.module.ts
and add to imports array i.e
import { FormsModule } from '@angular/forms';
[...]
@NgModule({
imports: [
[...]
FormsModule
],
[...]
})
Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard
(or some variation of that name) which is usually symlinked to to a directory in /storage
like /storage/sdcard0
or /storage/0
sometimes the emulated storage is mounted to /sdcard
and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories.
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Since the filesystems and sdcard support varies among devices.
see similar question for more info how to access downloads folder in android?
Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard
Put the word.txt directly as a child of the project root folder and a peer of src
Project_Root
src
word.txt
Disclaimer: I'd like to explain why this works for this particular case and why it may not work for others.
Why it works:
When you use File
or any of the other FileXxx
variants, you are looking for a file on the file system relative to the "working directory". The working directory, can be described as this:
When you run from the command line
C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1
the working directory is C:\EclipseWorkspace\ProjectRoot\bin
. With your IDE (at least all the ones I've worked with), the working directory is the ProjectRoot
. So when the file is in the ProjectRoot
, then using just the file name as the relative path is valid, because it is at the root of the working directory.
Similarly, if this was your project structure ProjectRoot\src\word.txt
, then the path "src/word.txt"
would be valid.
Why it May not Work
For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin
. So in this case it will fail, as there is not bin\word.txt
Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.
That being said, you need to determine if the file is to be an embedded-resource (or just "resource" - terms which sometimes I'll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get built into the classpath. With the file in the project root, you must configure the build to include the file. But if you put the file in the src
or in some directory below, then the default build should put it into the class path.
You can access classpath resource in a number of ways. You can make use of the Class
class, which has getResourceXxx
method, from which you use to obtain classpath resources.
For example, if you changed your project structure to ProjectRoot\src\resources\word.txt
, you could use this:
InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
getResourceAsStream
returns an InputStream
, but obtains an URL under the hood. Alternatively, you could get an URL
if that's what you need. getResource()
will return an URL
For Maven users, where the directory structure is like src/main/resources
, the contents of the resources
folder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")
You could use:
^(mailto|ftp|joe)
But to be honest, StartsWith
is perfectly fine to here. You could rewrite it as follows:
string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));
You could also look at the System.Uri
class if you are parsing URIs.
It may also be that you need to run the console as an administrator. On windows 7, hold ctrl+shift when you launch the console window.
If you want a Popup that closes automatically, you should look for Toasts. But if you want a dialog that the user has to close first before proceeding, you should look for a Dialog.
For both approaches it is possible to read a text file with the text you want to display. But you could also hardcode the text or use R.String to set the text.
In my case, I was trying to call plot(x, y)
and lines(x, predict(yx.lm), col="red")
in two separate chunks in Rmarkdown file. It worked without problems when running chunk by chunk, but the corresponding document wouldn't knit. After I moved all plotting calls within one chunk, problem was resolved.
For Laravel 5.4+
'mobile_number_1' => 'required|numeric|min:0|regex:/^[789]\d{9}$/' should do the trick
If you don't need to sum a column, then use @tvashtar's answer. If you do need to sum, then you can use @joris' answer or this one which is very similar to it.
df.groupby(['job']).apply(lambda x: (x.groupby('source')
.sum()
.sort_values('count', ascending=False))
.head(3))
Try:
echo "`date` User `whoami` started the script."$'\n' >> output.log
or just:
echo $'\n' >> output.log
Check your environment variables.
In my case I had JAVA_HOME set in the System variables as well as in my User Account variables and the latter was set to a wrong version of Java. I also had the same problem with the Path variable.
After deleting JAVA_HOME from my User Account variables and removing the wrong path from the Path variable it worked correctly.
var result = decimal.ToDouble(decimal.Divide(5, 2));
Inject a script into the page you want to get the source from and message it back to the popup....
manifest.json
{
"name": "Get pages source",
"version": "1.0",
"manifest_version": 2,
"description": "Get pages source from a popup",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>
popup.js
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
window.onload = onWindowLoad;
getPagesSource.js
// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);
function DOMtoString(document_root) {
var html = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML;
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}
return html;
}
chrome.runtime.sendMessage({
action: "getSource",
source: DOMtoString(document)
});
There's the TryParse method, which returns a bool indicating if the conversion was successful.
Increase the font-size of glyphicon
to increase all icons size.
.glyphicon {
font-size: 50px;
}
To target only one icon,
.glyphicon.glyphicon-globe {
font-size: 75px;
}
Use @RequestParam
@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){
Item i = itemDao.findOne(itemid);
String itemName = i.getItemName();
String price = i.getPrice();
return i;
}
Don't ever use the solution below because when you are using their code that is something like:
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]
The browser goes to:
http://example.com
Then redirects to:
https://example.com
Then redirects to:
https://www.example.com
This is too much request to the server.
Most of the answers even accepted one has this problem.
This code has an [OR]
condition to prevent dual changes at url!
RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.example.com%{REQUEST_URI} [R=301,L]
I got this in my browser when I changed from using http://localhost to http://145.900.50.20 (where 145.900.50.20 is my local IP address) and then changed back to localhost -- it was necessary to stay with the IP address once I had changed to that once
believe there should be a way in accessing file system.
Include node.d.ts
using npm i @types/node
. And then create a new tsconfig.json
file (npx tsc --init
) and create a .ts
file as followed:
import fs from 'fs';
fs.readFileSync('foo.txt','utf8');
You can use other functions in fs
as well : https://nodejs.org/api/fs.html
Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html
This seems like the easiest (but not most robust) way to me. Simply compute the sum from row 6 to the maximum allowed row number, as specified by Excel. According to this site, the maximum is currently 1048576, so the following should work for you:
=sum(c6:c1048576)
For more robust solutions, see the other answers.
If you want to save it as .fig file, hgsave is the function in Matlab R2012a. In later versions, savefig may also work.
[function.fopen]: failed to open stream
If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :
allow_url_fopen = off
should bee this
allow_url_fopen = On
And add this line below it:
allow_url_include = off
should bee this
allow_url_include = on
Use SpecialCells to delete only the rows that are visible after autofiltering:
ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:
ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
let's suppose
x=50
y=5
then
z=$((x/y))
this will work properly . But if you want to use / operator in case statements than it can't resolve it. In that case use simple strings like div or devide or something else. See the code
Use this regex
^\w+
\w+
matches 1 to many characters.
\w
is similar to [a-zA-Z0-9_]
^
depicts the start of a string
About Your Regex
Your regex (.*)?[ ]
should be ^(.*?)[ ]
or ^(.*?)(?=[ ])
if you don't want the space
I am not quite sure if it works with ROW FORMAT serde 'com.bizo.hive.serde.csv.CSVSerde' but I guess that it should be similar to ROW FORMAT DELIMITED FIELDS TERMINATED BY ','.
In your case first row will be treated like normal row. But first field fails to be INT so all fields, for first row, will be set as NULL. You need only one intermediate step to fix it:
INSERT OVERWRITE TABLE Test
SELECT * from Test WHERE RecordId IS NOT NULL
Only one drawback is that your original csv file will be modified. I hope it helps. GL!
Yes, you either need to do this onload
or in a <script>
tag after the closing </body>
tag, when the lc
element is already found in the document's DOM tree.
I prefer an answer from Best way to print the result of a bool as 'false' or 'true' in c?, just like
printf("%s\n", "false\0true"+6*x);
@smaclell asked why reverse iteration was more efficient in in a comment to @sambo99.
Sometimes it's more efficient. Consider you have a list of people, and you want to remove or filter all customers with a credit rating < 1000;
We have the following data
"Bob" 999
"Mary" 999
"Ted" 1000
If we were to iterate forward, we'd soon get into trouble
for( int idx = 0; idx < list.Count ; idx++ )
{
if( list[idx].Rating < 1000 )
{
list.RemoveAt(idx); // whoops!
}
}
At idx = 0 we remove Bob
, which then shifts all remaining elements left. The next time through the loop idx = 1, but
list[1] is now Ted
instead of Mary
. We end up skipping Mary
by mistake. We could use a while loop, and we could introduce more variables.
Or, we just reverse iterate:
for (int idx = list.Count-1; idx >= 0; idx--)
{
if (list[idx].Rating < 1000)
{
list.RemoveAt(idx);
}
}
All the indexes to the left of the removed item stay the same, so you don't skip any items.
The same principle applies if you're given a list of indexes to remove from an array. In order to keep things straight you need to sort the list and then remove the items from highest index to lowest.
Now you can just use Linq and declare what you're doing in a straightforward manner.
list.RemoveAll(o => o.Rating < 1000);
For this case of removing a single item, it's no more efficient iterating forwards or backwards. You could also use Linq for this.
int removeIndex = list.FindIndex(o => o.Name == "Ted");
if( removeIndex != -1 )
{
list.RemoveAt(removeIndex);
}
No need to create a GD resource, as someone else suggested.
$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));
Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.
Login to virtual machine use below command to check ip address. (anyone will work)
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
Create Table as select (CTAS) is possible in Hive.
You can try out below command:
CREATE TABLE new_test
row format delimited
fields terminated by '|'
STORED AS RCFile
AS select * from source where col=1
Create table like is also possible in Hive.
Step 1: check the return code: if($content === FALSE) { // handle error here... }
Step 2: suppress the warning by putting an error control operator (i.e. @
) in front of the call to file_get_contents():
$content = @file_get_contents($site);
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
Try this:
div.topmenu-design ul
{
display:block;
width:600px; /* or whatever width value */
margin:0px auto;
}
this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
I just came across this old post. Nothing listed above actually worked for me. I tested the script below, and it worked fine on my system. Sharing here, for the benefit of others who come here after me.
Sub RunPython()
Dim objShell As Object
Dim PythonExe, PythonScript As String
Set objShell = VBA.CreateObject("Wscript.Shell")
PythonExe = """C:\your_path\Python\Python38\python.exe"""
PythonScript = "C:\your_path\from_vba.py"
objShell.Run PythonExe & PythonScript
End Sub
.btn{
font-size: 20px;
color:black;
}
Using jQuery you can do this:
var str = '<td>1</td><td>2</td>';
$('#__TABLE__').replaceWith(str);
Or in pure javascript:
var str = '<td>1</td><td>2</td>';
var tdElement = document.getElementById('__TABLE__');
var trElement = tdElement.parentNode;
trElement.removeChild(tdElement);
trElement.innerHTML = str + trElement.innerHTML;
This below command worked for me
Python version - 2.7
package - python-jenkins
command - $ pip install 'python-jenkins>=1.1.1'
I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.
Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.
In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.
I'll make some notes and corrections to your code:
def main():
# doc to define the function
# proper Python indentation
# document significant variables, especially inputs and outputs
# grade_1, grade_2, grade_3, average - id these
# year - id this
# fName, lName, ID, converted_ID
infile = open("studentinfo.txt", "r")
# you didn't 'intialize' this variable
data = infile.read()
# nor this
fName, lName, ID, year = data.split(",")
# this will produce an error if the file does not have the right number of strings
# 'year' is now a string, even though you 'initialized' it as 0
year = int(year)
# now 'year' is an integer
# a language that requires initialization would have raised an error
# over this switch in type of this variable.
# Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a comma: "))
# 'eval' ouch!
# you could have handled the input just like you did the file input.
grade_1, grade_2, grade_3 = grades
# this would work only if the user gave you an 'iterable' with 3 values
# eval() doesn't ensure that it is an iterable
# and it does not ensure that the values are numbers.
# What would happen with this user input: "'one','two','three',4"?
# Create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
# earlier you 'initialized' converted_ID
# initialization in a static typed language would have caught this typo
# pseudo-initialization in Python does not catch typos
....
Use the V$SESSION
view.
V$SESSION
displays session information for each current session.
There's no point in declaring the class as static
. Just declare its methods static
and call them from the class name as normal, like Java's Math class.
Also, even though it isn't strictly necessary to make the constructor private, it is a good idea to do so. Marking the constructor private prevents other people from creating instances of your class, then calling static methods from those instances. (These calls work exactly the same in Java, they're just misleading and hurt the readability of your code.)
I tried Coincoin's solution :
Before processing some file, I copy it as a temporary file and open it.
When I'm done, I close the application if it is still open and delete
the temporary file :
I just use a Process variable and check it afterwards :
private Process openApplication;
private void btnOpenFile_Click(object sender, EventArgs e) {
...
// copy current file to fileCache
...
// open fileCache with proper application
openApplication = System.Diagnostics.Process.Start( fileCache );
}
Later I close the application :
...
openApplication.Refresh();
// close application if it is still open
if ( !openApplication.HasExited() ) {
openApplication.Kill();
}
// delete temporary file
System.IO.File.Delete( fileCache );
It works ( so far )
I can show you with an example:
function fullName(first, last) {_x000D_
let fullName = first + " " + last;_x000D_
return fullName;_x000D_
}_x000D_
_x000D_
function fullNameStringInterpolation(first, last) {_x000D_
let fullName = `${first} ${last}`;_x000D_
return fullName;_x000D_
}_x000D_
_x000D_
console.log('Old School: ' + fullName('Carlos', 'Gutierrez'));_x000D_
_x000D_
console.log('New School: ' + fullNameStringInterpolation('Carlos', 'Gutierrez'));
_x000D_
pkill -f for whatever reason does not work for me. Whatever that does, it seems very finicky about actually grepping through what ps aux shows me clearly is there.
After an afternoon of swearing I went for putting the following in my start script:
(ps aux | grep -v -e 'grep ' | grep MainApp | tr -s " " | cut -d " " -f 2 | xargs kill -9 ) || true
When you open phpinfo() see if the thread safety is enable or not enable also see the version of php and see MSVC-- what is the number in place of -- and see the architecture these all things help u to get the suitable php driver
here a url help u to get a php driver https://s3.amazonaws.com/drivers.mongodb.org/php/index.html
Try this:
CharSequence[] charArray = {"a","b","c"};
for (int i = 0; i < charArray.length; i++){
String str = charArray.toString().join("", charArray[i]);
System.out.print(str);
}
Try my way :
robocopy.exe "Desktop\Test folder 1" "Desktop\Test folder 2" /XD "C:\Users\Steve\Desktop\Test folder 2\XXX dont touch" /MIR
Had to put /XD
before /MIR
while including the full Destination Source directly after /XD
.
Yes, you can use find_elements_by_
to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html
Example HTML:
<ul class="bar">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
You can use the find_elements_by_
like so:
parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")
If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.
I know this question is aged, still, I would like to contribute.
Applying Range.NumberFormat = "@"
just partially solve the problem:
Applying the apostroph behave better. It sets the format to text, it align data to left and if you check the format of the value in the cell using the type formula, it will return 2 meaning text
As of Ansible 2.0 there seems to be an option called strategy
on a playbook. When setting the strategy to free
, the playbook plays tasks on each host without waiting to the others. See http://docs.ansible.com/ansible/playbooks_strategies.html.
It looks something like this (taken from the above link):
- hosts: all
strategy: free
tasks:
...
Please note that I didn't check this and I'm very new to Ansible. I was just curious about doing what you described and happened to come acroess this strategy thing.
EDIT:
It seems like this is not exactly what you're trying to do. Maybe "async tasks" is more appropriate as described here: http://docs.ansible.com/ansible/playbooks_async.html.
This includes specifying async
and poll
on a task. The following is taken from the 2nd link I mentioned:
- name: simulate long running op, allow to run for 45 sec, fire and forget
command: /bin/sleep 15
async: 45
poll: 0
I guess you can specify longer async
times if your task is lengthy. You can probably define your three concurrent task this way.
Best way to fetch location is below
// put dependancy
implementation 'com.google.android.gms:play-services-location:11.0.4'
// PUT permissions in Menifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
// create a Java file as below
public class SingleShotLocationProvider {
public static interface LocationCallback {
public void onNewLocationAvailable(GPSCoordinates location);
}
// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestSingleUpdate(criteria, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}, null);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
@Override public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override public void onProviderEnabled(String provider) { }
@Override public void onProviderDisabled(String provider) { }
}, null);
}
}
}
// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
public float longitude = -1;
public float latitude = -1;
public GPSCoordinates(float theLatitude, float theLongitude) {
longitude = theLongitude;
latitude = theLatitude;
}
public GPSCoordinates(double theLatitude, double theLongitude) {
longitude = (float) theLongitude;
latitude = (float) theLatitude;
}
}
}
// FILE FINISHED
// FETCH LOCATION FROM ACTIVITY AS BELOW
public void getLocation(Context context) {
MyApplication.log(LOG_TAG, "getLocation() ");
SingleShotLocationProvider.requestSingleUpdate(context,
new SingleShotLocationProvider.LocationCallback() {
@Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates loc) {
location = loc;
MyApplication.log(LOG_TAG, "getLocation() LAT: " + location.latitude + ", LON: " + location.longitude);
}
});
}
In this code, you pass a text to Form2. Form2 shows that text in textBox1. User types new text into textBox1 and presses the submit button. Form1 grabs that text and shows it in a textbox on Form1.
public class Form2 : Form
{
private string oldText;
public Form2(string newText):this()
{
oldText = newText;
btnSubmit.DialogResult = DialogResult.OK;
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = oldText;
}
public string getText()
{
return textBox1.Text;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
}
And this is Form1 code:
public class Form1:Form
{
using (Form2 dialogForm = new Form2("old text to show in Form2"))
{
DialogResult dr = dialogForm.ShowDialog(this);
if (dr == DialogResult.OK)
{
tbSubmittedText = dialogForm.getText();
}
dialogForm.Close();
}
}
Here is one case that caught me out, using a global as a default value of a parameter.
globVar = None # initialize value of global variable
def func(param = globVar): # use globVar as default value for param
print 'param =', param, 'globVar =', globVar # display values
def test():
global globVar
globVar = 42 # change value of global
func()
test()
=========
output: param = None, globVar = 42
I had expected param to have a value of 42. Surprise. Python 2.7 evaluated the value of globVar when it first parsed the function func. Changing the value of globVar did not affect the default value assigned to param. Delaying the evaluation, as in the following, worked as I needed it to.
def func(param = eval('globVar')): # this seems to work
print 'param =', param, 'globVar =', globVar # display values
Or, if you want to be safe,
def func(param = None)):
if param == None:
param = globVar
print 'param =', param, 'globVar =', globVar # display values
Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter.
I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this...
C#
var bldr = new SqlBuilder( myCommand );
bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId);
//or
bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName);
myCommand.CommandText = bldr.ToString();
Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here...
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
public class SqlBuilder
{
private StringBuilder _rq;
private SqlCommand _cmd;
private int _seq;
public SqlBuilder(SqlCommand cmd)
{
_rq = new StringBuilder();
_cmd = cmd;
_seq = 0;
}
public SqlBuilder Append(String str)
{
_rq.Append(str);
return this;
}
public SqlBuilder Value(Object value)
{
string paramName = "@SqlBuilderParam" + _seq++;
_rq.Append(paramName);
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public SqlBuilder FuzzyValue(Object value)
{
string paramName = "@SqlBuilderParam" + _seq++;
_rq.Append("'%' + " + paramName + " + '%'");
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public override string ToString()
{
return _rq.ToString();
}
}
Maybe will be useful for somebody. I had a little bit another requirement. Having list of objects A
from 3rd party remove all which have same A.b
field for same A.id
(multiple A
object with same A.id
in list). Stream partition answer by Tagir Valeev inspired me to use custom Collector
which returns Map<A.id, List<A>>
. Simple flatMap
will do the rest.
public static <T, K, K2> Collector<T, ?, Map<K, List<T>>> groupingDistinctBy(Function<T, K> keyFunction, Function<T, K2> distinctFunction) {
return groupingBy(keyFunction, Collector.of((Supplier<Map<K2, T>>) HashMap::new,
(map, error) -> map.putIfAbsent(distinctFunction.apply(error), error),
(left, right) -> {
left.putAll(right);
return left;
}, map -> new ArrayList<>(map.values()),
Collector.Characteristics.UNORDERED)); }
You can do the following:
(SELECT
*
FROM
table1 t1
LEFT JOIN
table2 t2 ON t1.id = t2.id
WHERE
t2.id IS NULL)
UNION ALL
(SELECT
*
FROM
table1 t1
RIGHT JOIN
table2 t2 ON t1.id = t2.id
WHERE
t1.id IS NULL);
My simple solution for SQLite (and probably MySQL):
SELECT *, MAX(age) FROM mytable GROUP BY `Group`;
However it doesn't work in PostgreSQL and maybe some other platforms.
In PostgreSQL you can use DISTINCT ON clause:
SELECT DISTINCT ON ("group") * FROM "mytable" ORDER BY "group", "age" DESC;
Here is a dplyr solution:
df %>% select_if(~sum(!is.na(.)) > 0)
Update: The summarise_if()
function is superseded as of dplyr 1.0
. Here are two other solutions that use the where()
tidyselect function:
df %>%
select(
where(
~sum(!is.na(.x)) > 0
)
)
df %>%
select(
where(
~!all(is.na(.x))
)
)
I was having the same problem, but using Long type. I changed for INT and it worked for me.
CREATE TABLE lists (
id INT NOT NULL AUTO_INCREMENT,
desc varchar(30),
owner varchar(20),
visibility boolean,
PRIMARY KEY (id)
);
Personally, I quite like the C++2011 approach because it neither requires you to use sizeof()
nor to remember adjusting the array bounds if you ever change the array bounds (and you can define the relevant function in C++2003 if you want, too):
#include <iterator>
#include <vector>
int x[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(std::begin(x), std::end(x));
Obviously, with C++2011 you might want to use initializer lists anyway:
std::vector<int> v({ 1, 2, 3, 4, 5 });
Using this.props.children
is the idiomatic way to pass instantiated components to a react component
const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>
When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div
or span
):
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
If what you want to do is to pass a children-like parameter as a prop, you can do that:
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />
After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.
You could create your own:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTextField textFieldA = new HintTextField("A hint here");
final JTextField textFieldB = new HintTextField("Another hint here");
frame.add(textFieldA, BorderLayout.NORTH);
frame.add(textFieldB, BorderLayout.CENTER);
JButton btnGetText = new JButton("Get text");
btnGetText.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String message = String.format("textFieldA='%s', textFieldB='%s'",
textFieldA.getText(), textFieldB.getText());
JOptionPane.showMessageDialog(frame, message);
}
});
frame.add(btnGetText, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
class HintTextField extends JTextField implements FocusListener {
private final String hint;
private boolean showingHint;
public HintTextField(final String hint) {
super(hint);
this.hint = hint;
this.showingHint = true;
super.addFocusListener(this);
}
@Override
public void focusGained(FocusEvent e) {
if(this.getText().isEmpty()) {
super.setText("");
showingHint = false;
}
}
@Override
public void focusLost(FocusEvent e) {
if(this.getText().isEmpty()) {
super.setText(hint);
showingHint = true;
}
}
@Override
public String getText() {
return showingHint ? "" : super.getText();
}
}
If you're still on Java 1.5, replace the this.getText().isEmpty()
with this.getText().length() == 0
.
There's a few approaches for this:
Connection object is for illustration only. The DataAdapter is the key bit:
Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
Usage: If you're going to store information that you want to access on different web pages, you can use SessionState
If you want to store information that you want to access from the same page, then you can use Viewstate
Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.
The SessionState will clear in the following conditions
I had a huge problems with auto layout. We have two containers inside table cell. Second container is resized depending on Item description (0 - 1000 chars), and row should be resized based on them.
The missing ingredient was bottom constraint for description.
I've changed bottom constraint of dynamic element from = 0 to >= 0.
yourItem.style['cssProperty']
this way you can call the property string dynamically
the third parameter should be like array('selected' =>value)
No, it's not possible. If it runs on the client browser, it must be downloaded by the client browser. It's pretty trivial to use Fiddler to inspect the HTTP session and get any downloaded js files.
There are tricks you can use. One of the most obvious is to employ a javascript obfuscator.
Then again, obfuscation only prevents casual snooping, and doesnt prevent people from lifting and using your code.
You can try compiled action script in the form of a flash movie.
The easiest way to concat a static text string to a selected value is to use element.
<a>
<xsl:attribute name="href">
<xsl:value-of select="/*/properties/property[@name='report']/@value" />
<xsl:text>staticIconExample.png</xsl:text>
</xsl:attribute>
</a>
To check the size of all of the directories within a directory, you can use:
du -h --max-depth=1
You can use either "=" or "==" operators for string comparison in bash. The important factor is the spacing within the brackets. The proper method is for brackets to contain spacing within, and operators to contain spacing around. In some instances different combinations work; however, the following is intended to be a universal example.
if [ "$1" == "something" ]; then ## GOOD
if [ "$1" = "something" ]; then ## GOOD
if [ "$1"="something" ]; then ## BAD (operator spacing)
if ["$1" == "something"]; then ## BAD (bracket spacing)
Also, note double brackets are handled slightly differently compared to single brackets ...
if [[ $a == z* ]]; then # True if $a starts with a "z" (pattern matching).
if [[ $a == "z*" ]]; then # True if $a is equal to z* (literal matching).
if [ $a == z* ]; then # File globbing and word splitting take place.
if [ "$a" == "z*" ]; then # True if $a is equal to z* (literal matching).
I hope that helps!
Don't call write.close()
in writeToFile()
.
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {res.EMAIL, res.USERNAME} );
OR you can use
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {email=res.EMAIL, username=res.USERNAME} );
Explanation :
Select employee from the db as res.
Filter the employee details as per the where condition.
Select required fields from the employee object by creating an Anonymous object using new { }
var doc = new XmlDocument();
doc.Loadxml(@"c:\abc.xml");
The limit is dependent on both the server and the client used (and if applicable, also the proxy the server or the client is using).
Most web servers have a limit of 8192 bytes (8 KB), which is usually configurable somewhere in the server configuration. As to the client side matter, the HTTP 1.1 specification even warns about this. Here's an extract of chapter 3.2.1:
Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths.
The limit in Internet Explorer and Safari is about 2 KB, in Opera about 4 KB and in Firefox about 8 KB. We may thus assume that 8 KB is the maximum possible length and that 2 KB is a more affordable length to rely on at the server side and that 255 bytes is the safest length to assume that the entire URL will come in.
If the limit is exceeded in either the browser or the server, most will just truncate the characters outside the limit without any warning. Some servers however may send an HTTP 414 error.
If you need to send large data, then better use POST instead of GET. Its limit is much higher, but more dependent on the server used than the client. Usually up to around 2 GB is allowed by the average web server.
This is also configurable somewhere in the server settings. The average server will display a server-specific error/exception when the POST limit is exceeded, usually as an HTTP 500 error.
Build up a JavaScript data structure with the required information, then turn it into the json string at the end.
Based on what I think you're doing, try something like this:
var result = [];
for (var name in goals) {
if (goals.hasOwnProperty(name)) {
result.push({name: name, goals: goals[name]});
}
}
res.contentType('application/json');
res.send(JSON.stringify(result));
or something along those lines.
Not PIL, but scipy.misc.imread
might still be interesting:
import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So you can iterate over it by
for y in range(im.shape[0]):
for x in range(im.shape[1]):
color = tuple(im[y][x])
r, g, b = color
Try explicitly specify sc.textFile("file:///path to the file/")
. The error occurs when Hadoop environment is set.
SparkContext.textFile internally calls org.apache.hadoop.mapred.FileInputFormat.getSplits
, which in turn uses org.apache.hadoop.fs.getDefaultUri
if schema is absent. This method reads "fs.defaultFS" parameter of Hadoop conf. If you set HADOOP_CONF_DIR environment variable, the parameter is usually set as "hdfs://..."; otherwise "file://".
First:
lsbom -f -l -s -pf /var/db/receipts/org.nodejs.pkg.bom | while read f; do sudo rm /usr/local/${f}; done
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*
To recap, the best way (I've found) to completely uninstall node + npm is to do the following:
go to /usr/local/lib
and delete any node and node_modules
cd /usr/local/lib
sudo rm -rf node*
go to /usr/local/include
and delete any node and node_modules directory
cd /usr/local/include
sudo rm -rf node*
if you installed with brew install node
, then run brew uninstall node
in your terminal
brew uninstall node
check your Home directory for any "local" or "lib" or "include" folders, and delete any "node" or "node_modules" from there
go to /usr/local/bin and delete any node executable
cd /usr/local/bin
sudo rm -rf /usr/local/bin/npm
ls -las
You may need to do the additional instructions as well:
sudo rm -rf /usr/local/share/man/man1/node.1
sudo rm -rf /usr/local/lib/dtrace/node.d
sudo rm -rf ~/.npm
Source: tonyMtz
I solved this problem with ModelViewSet and ModelSerializer. Hope this will help community.
I also preffer to have validation and Object->JSON (and vice-versa) login in serializer itself rather than in views.
Lets understand it by example.
Say, I want to create FileUploader API. Where it will be storing fields like id, file_path, file_name, size, owner etc in database. See sample model below:
class FileUploader(models.Model):
file = models.FileField()
name = models.CharField(max_length=100) #name is filename without extension
version = models.IntegerField(default=0)
upload_date = models.DateTimeField(auto_now=True, db_index=True)
owner = models.ForeignKey('auth.User', related_name='uploaded_files')
size = models.IntegerField(default=0)
Now, For APIs this is what I want:
When I fire the GET endpoint, I want all above fields for every uploaded file.
But for user to create/upload file, why she has to worry about passing all these fields. She can just upload the file and then, I suppose, serializer can get rest of the fields from uploaded FILE.
Searilizer: Question: I created below serializer to serve my purpose. But not sure if its the right way to implement it.
class FileUploaderSerializer(serializers.ModelSerializer):
# overwrite = serializers.BooleanField()
class Meta:
model = FileUploader
fields = ('file','name','version','upload_date', 'size')
read_only_fields = ('name','version','owner','upload_date', 'size')
def validate(self, validated_data):
validated_data['owner'] = self.context['request'].user
validated_data['name'] = os.path.splitext(validated_data['file'].name)[0]
validated_data['size'] = validated_data['file'].size
#other validation logic
return validated_data
def create(self, validated_data):
return FileUploader.objects.create(**validated_data)
Viewset for reference:
class FileUploaderViewSet(viewsets.ModelViewSet):
serializer_class = FileUploaderSerializer
parser_classes = (MultiPartParser, FormParser,)
# overriding default query set
queryset = LayerFile.objects.all()
def get_queryset(self, *args, **kwargs):
qs = super(FileUploaderViewSet, self).get_queryset(*args, **kwargs)
qs = qs.filter(owner=self.request.user)
return qs