Actually looking at other areas, if you open with _blank it keeps the sessionStorage as long as you're opening the tab when the parent is open:
In this link, there's a good jsfiddle to test it. sessionStorage on new window isn't empty, when following a link with target="_blank"
sessionStorage
maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores)
localStorage
does the same thing, but persists even when the browser is closed and reopened.
I took this from Web Storage API
sesssionStorage.setObj(1,{date:Date.now(),action:'save firstObject'});
sesssionStorage.setObj(2,{date:Date.now(),action:'save 2nd object'});
//Query first object
sesssionStorage.getObj(1)
//Retrieve date created of 2nd object
new Date(sesssionStorage.getObj(1).date)
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
};
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
};
here is a quick review and with a simple and quick understanding
from teacher Beau Carnes from freecodecamp
As per Nawfal's answer, IF statements need to be in a procedure. I found this post that shows a brilliant example of using your script in a procedure while still developing and testing. Basically, you create, call then drop the procedure:
You can use an echo shortcut also instead of typing out "echo blah;" as shown below:
<form method="POST" action="<?=($_SERVER['PHP_SELF'])?>">
Microsoft now recommends using an IHttpClientFactory
with the following benefits:
HttpClient
instances. For example, a client named github could be
registered and configured to access GitHub. A default client can be
registered for general access.HttpClient
. Provides extensions for Polly-based middleware to take
advantage of delegating handlers in HttpClient
.HttpClientMessageHandler
instances. Automatic management avoids
common DNS (Domain Name System) problems that occur when manually
managing HttpClient
lifetimes.ILogger
) for all requests
sent through clients created by the factory.https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1
Setup:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
// Remaining code deleted for brevity.
POST example:
public class BasicUsageModel : PageModel
{
private readonly IHttpClientFactory _clientFactory;
public BasicUsageModel(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task CreateItemAsync(TodoItem todoItem)
{
var todoItemJson = new StringContent(
JsonSerializer.Serialize(todoItem, _jsonSerializerOptions),
Encoding.UTF8,
"application/json");
var httpClient = _clientFactory.CreateClient();
using var httpResponse =
await httpClient.PostAsync("/api/TodoItems", todoItemJson);
httpResponse.EnsureSuccessStatusCode();
}
Error is coming in your code from this statement as you said
Intent intent = new Intent(context, SendMessage.class);
This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent
android.content.Intent.Intent(Context packageContext, Class<?> cls)
You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to
Intent intent = new Intent(MainActivity.this, SendMessage.class);
Also for sending your message from this MainActivity to SendMessage class please see below code
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
startActivity(intent);
}
});
Please let me know if this helps you
EDIT:- If you are finding some issue to get the value of list do one thing declear your array list
ArrayList<ListEntry> members = new ArrayList<ListEntry>();
globally i.e. before oncreate and change your listener as below
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, members.get(position));
startActivity(intent);
}
});
So your whole code will look as
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
members.add(new ListEntry("BcxvBB","AcxvAA"));
members.add(new ListEntry("BvBB","AcxsvAA"));
members.add(new ListEntry("BcxvBB","AcxsvzAA"));
members.add(new ListEntry("Bcxadv","AcsxvAA"));
members.add(new ListEntry("BcxcxB","AcxsvAA"));
ListView lv = (ListView)findViewById(R.id.listView1);
Log.i("testTag","before start adapter");
StringArrayAdapter ad = new StringArrayAdapter (members,this);
Log.i("testTag","after start adapter");
Log.i("testTag","set adapter");
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
startActivity(intent);
}
});
}
Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.
In Windows 64, if you did this sequence correctly:
Anaconda prompt:
conda create -n tensorflow python=3.5
activate tensorflow
pip install --ignore-installed --upgrade tensorflow
Be sure you still are in tensorflow environment. The best way to make Spyder recognize your tensorflow environment is to do this:
conda install spyder
This will install a new instance of Spyder inside Tensorflow environment. Then you must install scipy, matplotlib, pandas, sklearn and other libraries. Also works for OpenCV.
Always prefer to install these libraries with "conda install" instead of "pip".
The line function implementation should be:
void addStudent(struct student person) {
}
person
is not a type but a variable, you cannot use it as the type of a function parameter.
Also, make sure your struct is defined before the prototype of the function addStudent
as the prototype uses it.
Change your HOME environment variable.
on XP, its right-click My Computer >> Properties >> Advanced >> Environment Variables >> User Variables for >> [select variable HOME] >> edit
You should be able to get it to hide/show by setting:
.style.display = 'none';
.style.display = 'inline';
You can fix IE with :
event.currentTarget.firstChild.ownerDocument.activeElement
It looks like "explicitOriginalTarget" for FF.
Antoine And J
Try this, it worked for me.
<button id="btn">Click</button>
<script>
console.log(btn)
let f;
btn.addEventListener('click', f=function(event) {
console.log('Click')
console.log(f)
this.removeEventListener('click',f)
console.log('Event removed')
})
</script>
Updated to new version:
Try this solution from here http://jsfiddle.net/EE9RG/430/
$('#sel2').select2({
multiple:true,
ajax:{}}).select2({"data":
[{"id":"2127","text":"Henry Ford"},{"id":"2199","text":"Tom Phillips"}]});
attr_accessor
is a Ruby method that makes a getter and a setter. attr_accessible
is a Rails method that allows you to pass in values to a mass assignment: new(attrs)
or update_attributes(attrs)
.
Here's a mass assignment:
Order.new({ :type => 'Corn', :quantity => 6 })
You can imagine that the order might also have a discount code, say :price_off
. If you don't tag :price_off
as attr_accessible
you stop malicious code from being able to do like so:
Order.new({ :type => 'Corn', :quantity => 6, :price_off => 30 })
Even if your form doesn't have a field for :price_off
, if it's in your model it's available by default. This means a crafted POST could still set it. Using attr_accessible
white lists those things that can be mass assigned.
With support for C++11 initializer lists it is very easy:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using Strings = vector<string>;
void foo( Strings const& strings )
{
for( string const& s : strings ) { cout << s << endl; }
}
auto main() -> int
{
foo( Strings{ "hi", "there" } );
}
Lacking that (e.g. for Visual C++ 10.0) you can do things like this:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> Strings;
void foo( Strings const& strings )
{
for( auto it = begin( strings ); it != end( strings ); ++it )
{
cout << *it << endl;
}
}
template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }
template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
v.push_back( a );
return v;
}
int main()
{
foo( r( Strings() ) << "hi" << "there" );
}
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
Use the dec argument to set ","
as the decimal point by adding:
ce <- read.table("file.txt", header = TRUE, dec = ",")
I know this doesn't really answer your question, but different View Engines have different purposes. The Spark View Engine, for example, aims to rid your views of "tag soup" by trying to make everything fluent and readable.
Your best bet would be to just look at some implementations. If it looks appealing to the intent of your solution, try it out. You can mix and match view engines in MVC, so it shouldn't be an issue if you decide to not go with a specific engine.
Think about it from the browser's point of view. For readonly the browser will send in a variable/value pair. For disabled, it won't.
Run this, then look at the URL after you hit submit:
<html>
<form action=foo.html method=get>
<input name=dis type=text disabled value="dis">
<input name=read type=text readonly value="read">
<input name=normal type=text value="normal">
<input type=submit>
</form>
</html>
The answer is quite simple. It lies in your admin rights. before compiling your java code you need to open the command prompt with run as administrator. then compile your code. no need to change anything in your code. the name of the class need to be the same as the name of the java file.. that's it!!
More clarified version of above answers:
IEnumerable<IGrouping<int, ClassA>> groups = list.GroupBy(x => x.PropertyIntOfClassA);
foreach (var groupingByClassA in groups)
{
int propertyIntOfClassA = groupingByClassA.Key;
//iterating through values
foreach (var classA in groupingByClassA)
{
int key = classA.PropertyIntOfClassA;
}
}
The CLI told you where is your mistake : delete WHAT? from student
...
Delete : How to delete/truncate tables from Hadoop-Hive?
Update : Update , SET option in Hive
I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.
Have you tried compiling from the command line?
I have the exact same version:
Probably you're thinking the warning is an error.
UPDATE
It looks like you have a Arrays.class
file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class
It's used for converting arbitrary binary data to ASCII text.
For example, e-mail attachments are sent this way.
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
Can use enumerate.
a = [1, 2, 3, 4]
b = [2, 3, 4, 5]
ab = [val * b[i] for i, val in enumerate(a)]
@victor hugo and @unwind are correct, and victor's solution is by far the simplest. However BEWARE of externals in your SVN project. If you reference external libraries, the external's revision reference (whether a tag, or HEAD, or number) will remain unchanged when you tag directories that have external references.
It is possible to create a script to handle this aspect of tagging, for a discussion on that topic, see this SO article: Tagging an SVN checkout with externals
This is a summary of what worked for me:
Define a new function (wrapped $.ajax
to simplify):
jQuery.postCORS = function(url, data, func) {
if(func == undefined) func = function(){};
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
xhrFields: { withCredentials: true },
success: function(res) { func(res) },
error: function() {
func({})
}
});
}
Usage:
$.postCORS("https://example.com/service.json",{ x : 1 },function(obj){
if(obj.ok) {
...
}
});
Also works with .done
,.fail
,etc:
$.postCORS("https://example.com/service.json",{ x : 1 }).done(function(obj){
if(obj.ok) {
...
}
}).fail(function(){
alert("Error!");
});
Server side (in this case where example.com is hosted), set these headers (added some sample code in PHP):
header('Access-Control-Allow-Origin: https://not-example.com');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 604800');
header("Content-type: application/json");
$array = array("ok" => $_POST["x"]);
echo json_encode($array);
This is the only way I know to truly POST cross-domain from JS.
JSONP converts the POST into GET which may display sensitive information at server logs.
ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121
S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ;
RemoteServerName => abcd123 ;
2121 => port number ;
ftps => command is part of ftps client software ;
Using JQuery is a prettier, shorter & smarter way to do it!
$('#selection_box_id').empty();
What about to split the string and strip words punctuation?
w in [ws.strip(',.?!') for ws in p.split()]
Or working the case:
w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]
Maybe that way:
def wsearch(word, phrase):
# Attention about punctuation and about split characters
punctuation = ',.?!'
return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]
Sample:
print(wsearch('CAr', 'I own a caR.'))
I didn't check performance...
Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock())
;
}
Note that the name sleep
for this function is misleading, since the CPU will not be sleeping at all.
Do the following :
"CREATE APPLICATION" having the same name which you want to upload before.
Click create.
After creation of the app now click on the "App releases"
Click on the "MANAGE PRODUCTION"
Click on the "CREATE RELEASE"
Here you see "Google Play App Signing" dialog.
Just click on the "OPT-OUT" button.
It will ask you to confirm it. Just click on the "confirm" button
If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.
This is not an Xcode bug, though the warning message is not helpful enough to describe the real cause.
This error message occurs when you have several files in your project that have the same name. You just have to delete or rename the files with duplicate names and the problem is solved.
I think you want to say "Are the last four characters of $file equal to .txt
?" If so, you can use the following:
if [ ${file: -4} == ".txt" ]
Note that the space between file:
and -4
is required, as the ':-' modifier means something different.
function substringBetween(s, a, b) {
var p = s.indexOf(a) + a.length;
return s.substring(p, s.indexOf(b, p));
}
// substringBetween('MyLongString:StringIWant;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;:StringIDontWant;', ':', ';') -> StringIWant
I tend to use Spring's Named JDBC Parameters so I can write a standard string like "select * from blah where colX=':someValue'"; I think that's pretty readable.
An alternative would be to supply the string in a separate .sql file and read the contents in using a utility method.
Oh, also worth having a look at Squill: https://squill.dev.java.net/docs/tutorial.html
Complete solution:
import contextlib
import subprocess
# Unix, Windows and old Macintosh end-of-line
newlines = ['\n', '\r\n', '\r']
def unbuffered(proc, stream='stdout'):
stream = getattr(proc, stream)
with contextlib.closing(stream):
while True:
out = []
last = stream.read(1)
# Don't loop forever
if last == '' and proc.poll() is not None:
break
while last not in newlines:
# Don't loop forever
if last == '' and proc.poll() is not None:
break
out.append(last)
last = stream.read(1)
out = ''.join(out)
yield out
def example():
cmd = ['ls', '-l', '/']
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
# Make all end-of-lines '\n'
universal_newlines=True,
)
for line in unbuffered(proc):
print line
example()
I was able to fix the error by simply setting the option in the 'Attach to Process' to 'Automatically determine the type of code to debug' option as shown in the attached screenshot.
Simply follow the steps below:
TRAC. Open source, Python-based
There is a syntax problem, because the right syntax to alter command is ALTER TABLE tablename CHANGE OldColumnName NewColunmName DATATYPE;
Above, Abhishek mentions the command line differences specified in two URLS:
PhoneGap: http://docs.phonegap.com/en/edge/guide_cli_index.md.html
Cordova: http://cordova.apache.org/docs/en/3.0.0/guide_cli_index.md.html#The%20Command-line%20Interface
One thing to point out is that, as of this post, the phonegap one looks to be almost the same as the cordova one, and is probably not an accurate image of the command line option differences. As such, I installed both on my system so I could look at the differences.
These are just a few of them. Hopefully they are brought more in sync sometime. If anyone has better information, please tell me.
I guess my point is that the phonegap CLI documention mentioned quite often is not really for the phonegap CLI, but for the cordova CLI, at this time. Please tell me if I am missing something. Thanks.
Now you need to implement like this
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
//
} else {
//
}
Following single line of code is enough, everything will take care by ContextCompat.getDrawable
ContextCompat.getDrawable(this, R.drawable.your_drawable_file)
I don't know why, but I had to use the following folder structure instead. I put "templates" one level up.
project/
app/
hello.py
static/
main.css
templates/
home.html
venv/
This probably indicates a misconfiguration elsewhere, but I couldn't figure out what that was and this worked.
You can invoke private method with reflection. Modifying the last bit of the posted code:
Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);
There are a couple of caveats. First, getDeclaredMethod
will only find method declared in the current Class
, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a SecurityManager
can prevent use of the setAccessible
method. So, it may need to run as a PrivilegedAction
(using AccessController
or Subject
).
Simple: enum names into a List:
List<String> NameList = Enum.GetNames(typeof(YourEnumName)).Cast<string>().ToList()
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
This is an update to this rather old question. I wanted to use the new SF Pro fonts on a website and found no fonts CDN, besides the above noted (applesocial.s3.amazonaws.com).
Clearly, this isn't an official content repository approved by Apple. Actually, I did not find ANY official fonts repository serving Apple fonts, ready to be used by web developers.
And there's a reason - if you read the license agreement that comes with downloading the new SF Pro and other fonts from https://developer.apple.com/fonts/ - it states in the first few paragraphs very clearly:
[...]you may use the Apple Font solely for creating mock-ups of user interfaces to be used in software products running on Apple’s iOS, macOS or tvOS operating systems, as applicable. The foregoing right includes the right to show the Apple Font in screen shots, images, mock-ups or other depictions, digital and/or print, of such software products running solely on iOS, macOS or tvOS.[...]
And:
Except as expressly provided for herein, you may not use the Apple Font to, create, develop, display or otherwise distribute any documentation, artwork, website content or any other work product.
Further:
Except as otherwise expressly permitted [...] (i) only one user may use the Apple Font at a time, and (ii) you may not make the Apple Font available over a network where it could be run or used by multiple computers at the same time.
No more questions for me. Apple clearly does not want their Fonts shared across the web outside their products.
best way is to create an accessor like this:
/**
* @var object $db : map to database connection.
*/
public static $db= null;
/**
* db Function for initializing variable.
* @return object
*/
public static function db(){
if( !isset(static::$db) ){
static::$db= new \Helpers\MySQL( array(
"hostname"=> "localhost",
"username"=> "root",
"password"=> "password",
"database"=> "db_name"
)
);
}
return static::$db;
}
then you can do static::db(); or self::db(); from anywhere.
From the man page:
search, -S text|/text/ Perform a substring search of formula names for text. If text is surrounded with slashes, then it is interpreted as a regular expression. If no search term is given, all available formula are displayed.
For your purposes, brew search
will suffice.
None of the above worked for me either;
But I finally found something that worked for me:
It was because I had my Build Output going to bin\Debug\ for Debug configuration and bin\Release\ for Release configuations. As soon as I changed the Build Configuation to "bin\" for All configuations (as per image below) then everything started working as it should!!!
I have no idea why separating out your builds into Release and Debug folders should cause Razor syntax to break, but it seems to be because something couldn't find the assemblies. For me the projects that were having the razor syntax issues are actually my 'razor library' projects. They are set as Application Projects however I use them as class libraries with RazorGenerator to compile my views. When I actually tried to run one of these projects directly it caused the following Configuration error:
Could not load file or assembly 'System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
This lead me to trying to change the Build Output, as I notice that for all web projects the Build Output seems to always be directly to the bin folder, unlike the default for class libraries, which have both release and debug folders.
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
Your best option is to DROP and CREATE foreign key constraints.
I didn't find examples in this post that would work for me "as-is", one would not work if foreign keys reference different schemas, the other would not work if foreign key references multiple columns. This script considers both, multiple schemas and multiple columns per foreign key.
Here is the script that generates "ADD CONSTRAINT" statements, for multiple columns it will separate them by comma (be sure to save this output before executing DROP statements):
PRINT N'-- CREATE FOREIGN KEY CONSTRAINTS --';
SET NOCOUNT ON;
SELECT '
PRINT N''Creating '+ const.const_name +'...''
GO
ALTER TABLE ' + const.parent_obj + '
ADD CONSTRAINT ' + const.const_name + ' FOREIGN KEY (
' + const.parent_col_csv + '
) REFERENCES ' + const.ref_obj + '(' + const.ref_col_csv + ')
GO'
FROM (
SELECT QUOTENAME(fk.NAME) AS [const_name]
,QUOTENAME(schParent.NAME) + '.' + QUOTENAME(OBJECT_name(fkc.parent_object_id)) AS [parent_obj]
,STUFF((
SELECT ',' + QUOTENAME(COL_NAME(fcP.parent_object_id, fcp.parent_column_id))
FROM sys.foreign_key_columns AS fcP
WHERE fcp.constraint_object_id = fk.object_id
FOR XML path('')
), 1, 1, '') AS [parent_col_csv]
,QUOTENAME(schRef.NAME) + '.' + QUOTENAME(OBJECT_NAME(fkc.referenced_object_id)) AS [ref_obj]
,STUFF((
SELECT ',' + QUOTENAME(COL_NAME(fcR.referenced_object_id, fcR.referenced_column_id))
FROM sys.foreign_key_columns AS fcR
WHERE fcR.constraint_object_id = fk.object_id
FOR XML path('')
), 1, 1, '') AS [ref_col_csv]
FROM sys.foreign_key_columns AS fkc
INNER JOIN sys.foreign_keys AS fk ON fk.object_id = fkc.constraint_object_id
INNER JOIN sys.objects AS oParent ON oParent.object_id = fkc.parent_object_id
INNER JOIN sys.schemas AS schParent ON schParent.schema_id = oParent.schema_id
INNER JOIN sys.objects AS oRef ON oRef.object_id = fkc.referenced_object_id
INNER JOIN sys.schemas AS schRef ON schRef.schema_id = oRef.schema_id
GROUP BY fkc.parent_object_id
,fkc.referenced_object_id
,fk.NAME
,fk.object_id
,schParent.NAME
,schRef.NAME
) AS const
ORDER BY const.const_name
Here is the script that generates "DROP CONSTRAINT" statements:
PRINT N'-- DROP FOREIGN KEY CONSTRAINTS --';
SET NOCOUNT ON;
SELECT '
PRINT N''Dropping ' + fk.NAME + '...''
GO
ALTER TABLE [' + sch.NAME + '].[' + OBJECT_NAME(fk.parent_object_id) + ']' + ' DROP CONSTRAINT ' + '[' + fk.NAME + ']
GO'
FROM sys.foreign_keys AS fk
INNER JOIN sys.schemas AS sch ON sch.schema_id = fk.schema_id
ORDER BY fk.NAME
"Could you suggest a simpler code main thing is uploading the file Data base entry is secondary"
^--- As per OP's request. ---^
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Change upload folder to preferred name. Presently saves to upload/
<?php
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
I think with
System.getProperty("os.name");
Checking the operating system on can manage the shell/bash scrips if such are supported. if there is need to make the code portable.
There are several usage / capabilities you might want to consider:
Require:
require
s, they are
loaded and processed one by one.ES6 Imports:
Also, the Require module system isn't standard based. It's is highly unlikely to become standard now that ES6 modules exist. In the future there will be native support for ES6 Modules in various implementations which will be advantageous in terms of performance.
<input id="uploadFile" placeholder="Choose File" disabled="disabled" />
<div class="fileUpload btn btn-primary">
<span>Your name</span>
<input id="uploadBtn" type="file" class="upload" />
</div>
JS
document.getElementById("uploadBtn").onchange = function () {
document.getElementById("uploadFile").value = this.value;
};
more http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/
-a option?
Cf. man page:
-a file
Attach the given file to the message.
Result:
Content-Type: text/html: No such file or directory
you can use ref
to call the function of the child component from the parent
in functional component, you have to use useImperativeHandle
for getting ref into a child like below
import React, { forwardRef, useRef, useImperativeHandle } from 'react';
export default function ParentFunction() {
const childRef = useRef();
return (
<div className="container">
<div>
Parent Component
</div>
<button
onClick={() => { childRef.current.showAlert() }}
>
Call Function
</button>
<Child ref={childRef}/>
</div>
)
}
const Child = forwardRef((props, ref) => {
useImperativeHandle(
ref,
() => ({
showAlert() {
alert("Child Function Called")
}
}),
)
return (
<div>Child Component</div>
)
})
Child.js
import s from './Child.css';
class Child extends Component {
getAlert() {
alert('clicked');
}
render() {
return (
<h1>Hello</h1>
);
}
}
export default Child;
Parent.js
class Parent extends Component {
render() {
onClick() {
this.refs.child.getAlert();
}
return (
<div>
<Child ref="child" />
<button onClick={this.onClick}>Click</button>
</div>
);
}
}
You must pip install pyserial
first.
In your first example, you are making a blank array, same as doing var x = []
. The 2nd example makes an array of size 3 (with all elements undefined
). The 3rd and 4th examples are the same, they both make arrays with those elements.
Be careful when using new Array()
.
var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]
The preferred way is using the []
syntax.
var x = []; // array of size 0
var y = [10] // array of size 1: [1]
var z = []; // array of size 0
z[2] = 12; // z is now size 3: [undefined, undefined, 12]
Try the below code. It is working in IE but not in FF22. If
Modal dialog found is printed in Console, then Modal dialog is identified and switched.
public class ModalDialog {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new InternetExplorerDriver();
//WebDriver driver = new FirefoxDriver();
driver.get("http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm");
String parent = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement push_to_create = wait.until(ExpectedConditions
.elementToBeClickable(By
.cssSelector("input[value='Push To Create']")));
push_to_create.click();
waitForWindow(driver);
switchToModalDialog(driver, parent);
}
public static void waitForWindow(WebDriver driver)
throws InterruptedException {
//wait until number of window handles become 2 or until 6 seconds are completed.
int timecount = 1;
do {
driver.getWindowHandles();
Thread.sleep(200);
timecount++;
if (timecount > 30) {
break;
}
} while (driver.getWindowHandles().size() != 2);
}
public static void switchToModalDialog(WebDriver driver, String parent) {
//Switch to Modal dialog
if (driver.getWindowHandles().size() == 2) {
for (String window : driver.getWindowHandles()) {
if (!window.equals(parent)) {
driver.switchTo().window(window);
System.out.println("Modal dialog found");
break;
}
}
}
}
}
Create a Directive with the show and size attributes ( you can add more also )
app.directive('loader',function(){
return {
restrict:'EA',
scope:{
show : '@',
size : '@'
},
template : '<div class="loader-container"><div class="loader" ng-if="show" ng-class="size"></div></div>'
}
})
and in html use as
<loader show="{{loader1}}" size="sm"></loader>
In the show variable pass true when any promise is running and make that false when request is completed. Active demo - Angular Loader directive example demo in JsFiddle
export
is a Bash builtin, echo
is an executable in your $PATH
. So export
is interpreted by Bash as is, without spawning a new process.
You need to get Bash to interpret your command, which you can pass as a string with the -c
option:
bash -c "export foo=bar; echo \$foo"
ALSO:
Each invocation of bash -c
starts with a fresh environment. So something like:
bash -c "export foo=bar"
bash -c "echo \$foo"
will not work. The second invocation does not remember foo
.
Instead, you need to chain commands separated by ;
in a single invocation of bash -c
:
bash -c "export foo=bar; echo \$foo"
use SqlConnectionStringBuilder
to simplify the connection
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Initial Catalog"] = "Server";
builder["Data Source"] = "db";
builder["integrated Security"] = true;
string connexionString = builder.ConnectionString;
SqlConnection connexion = new SqlConnection(connexionString);
try { connexion.Open(); return true; }
catch { return false; }
I still had some issues with other solution presented here. Finally this worked best for me:
<div class="parent">
<img class="child" src="image.png"/>
</div>
css3:
.child {
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%); /* Safari and Chrome */
-moz-transform: translate(-50%, -50%); /* Firefox */
-ms-transform: translate(-50%, -50%); /* IE 9 */
-o-transform: translate(-50%, -50%); /* Opera */
// I suppose you may like those too:
// max-width: 80%;
// max-height: 80%;
}
You can read more about that approach at this page.
For those looking for an SCSS mixin instead, including woff2:
@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
@font-face {
font-family: $family;
@if $svg == '' {
// with OTF without SVG and EOT
src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
} @else {
// traditional src inclusions
src: url('#{$path}#{$type}.eot');
src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
}
font-weight: $weight;
font-style: $style;
}
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);
$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
font-family: Inter;
font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
font-family: AmaticSC;
font-weight: 700; // default font is loaded
}
The $type
parameter is useful for stacking related families with different weights.
The @if
is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.
If you get a can't resolve error, remember to double check your fonts directory ($dir
).
Packaging an artifact as POM means that it has a very simple lifecycle
package -> install -> deploy
http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
This is useful if you are deploying a pom.xml file or a project that doesn't fit with the other packaging types.
We use pom packaging for many of our projects and bind extra phases and goals as appropriate.
For example some of our applications use:
prepare-package -> test -> package -> install -> deploy
When you mvn install the application it should add it to your locally .m2 repository. To publish elsewhere you will need to set up correct distribution management information. You may also need to use the maven builder helper plugin, if artifacts aren't automatically attached to by Maven.
To avoid caching of output you might wanna try pexpect,
child = pexpect.spawn(launchcmd,args,timeout=None)
while True:
try:
child.expect('\n')
print(child.before)
except pexpect.EOF:
break
PS : I know this question is pretty old, still providing the solution which worked for me.
PPS: got this answer from another question
I had the exact same problem when manually compiling through the command line, my solution was I didn't include the -sourcepath directory so that way all the subdirectory java files would be compiled too!
Sys.Application.add_load(LoadHandler); //This load handler solved update panel did not bind control after partial postback
function LoadHandler() {
$(document).ready(function () {
//rebind any events here for controls under update panel
});
}
If you are not having an input field, rather just want to display a string date with a proper formatting, you can simply go for:
<label ng-bind="formatDate(date) | date:'MM/dd/yyyy'"></label>
and in the js file use:
// @Function
// Description : Triggered while displaying expiry date
$scope.formatDate = function(date){
var dateOut = new Date(date);
return dateOut;
};
This will convert the date in string to a new date object in javascript and will display the date in format MM/dd/yyyy.
Output: 12/15/2014
Edit
If you are using a string date of format "2014-12-19 20:00:00" string format (passed from a PHP backend), then you should modify the code to the one in: https://stackoverflow.com/a/27616348/1904479
Adding on further
From javascript you can set the code as:
$scope.eqpCustFields[i].Value = $filter('date')(new Date(dateValue),'yyyy-MM-dd');
that is in case you already have a date with you, else you can use the following code to get the current system date:
$scope.eqpCustFields[i].Value = $filter('date')(new Date(),'yyyy-MM-dd');
For more details on date Formats, refer : https://docs.angularjs.org/api/ng/filter/date
My comments on Renaud Bompuis's answer messed up.
Actually, you can use late binding, and the reference to the 11.0 object library is not required.
The following code will work without any references:
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = True
f.Show
MsgBox "file choosen = " & f.SelectedItems.Count
Note that the above works well in the runtime also.
Use dynamic_cast
for converting pointers/references within an inheritance hierarchy.
Use static_cast
for ordinary type conversions.
Use reinterpret_cast
for low-level reinterpreting of bit patterns. Use with extreme caution.
Use const_cast
for casting away const/volatile
. Avoid this unless you are stuck using a const-incorrect API.
I recommend something along these lines, even if the image lives inside of your model.
I realize you are asking for a direct way to access it right from the view and many others have answered that and told you what is wrong with that approach so this is just another way that will load the image in an async fashion for you and I think is a better approach.
Sample Model:
[Bind(Exclude = "ID")]
public class Item
{
[Key]
[ScaffoldColumn(false)]
public int ID { get; set; }
public String Name { get; set; }
public byte[] InternalImage { get; set; } //Stored as byte array in the database.
}
Sample Method in the Controller:
public async Task<ActionResult> RenderImage(int id)
{
Item item = await db.Items.FindAsync(id);
byte[] photoBack = item.InternalImage;
return File(photoBack, "image/png");
}
View
@model YourNameSpace.Models.Item
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Item</h4>
<hr />
<dl class="dl-horizontal">
<img src="@Url.Action("RenderImage", new { id = Model.ID})" />
</dl>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
</dl>
</div>
My idea is to get max of rows count of all data.frames and next append empty matrix to every data.frame if need. This method doesn't require additional packages, only base is used. Code looks following:
list.df <- list(data.frame(a = 1:10), data.frame(a = 1:5), data.frame(a = 1:3))
max.rows <- max(unlist(lapply(list.df, nrow), use.names = F))
list.df <- lapply(list.df, function(x) {
na.count <- max.rows - nrow(x)
if (na.count > 0L) {
na.dm <- matrix(NA, na.count, ncol(x))
colnames(na.dm) <- colnames(x)
rbind(x, na.dm)
} else {
x
}
})
do.call(cbind, list.df)
# a a a
# 1 1 1 1
# 2 2 2 2
# 3 3 3 3
# 4 4 4 NA
# 5 5 5 NA
# 6 6 NA NA
# 7 7 NA NA
# 8 8 NA NA
# 9 9 NA NA
# 10 10 NA NA
The current answer did not work good for me, if the exception is not re-caught the appended message is not shown.
But doing like below both keeps the trace and shows the appended message regardless if the exception is re-caught or not.
try:
raise ValueError("Original message")
except ValueError as err:
t, v, tb = sys.exc_info()
raise t, ValueError(err.message + " Appended Info"), tb
( I used Python 2.7, have not tried it in Python 3 )
In your PHP code you have set the incorrect port, this is what the code should be
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'test_db13';
The port in your code is set to 3360
when it should be 3306
, however as this is the default port, you don't need to specify.
Just strengthening Jim's answer
Using presence one can do
class Task < ActiveRecord::Base
before_save :default_values
def default_values
self.status = status.presence || 'P'
end
end
I was running some of the answers to see what is the fastest way for a large number. So, I found that we can convert the int to an array and it can give the correct results and it is faster.
arrayint=np.array(myInt)
newList = myList / arrayint
This a comparison of all answers above
import numpy as np
import time
import random
myList = random.sample(range(1, 100000), 10000)
myInt = 10
start_time = time.time()
arrayint=np.array(myInt)
newList = myList / arrayint
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.array(myList) / myInt
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
myList[:] = [x / myInt for x in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = map(lambda x: x/myInt, myList)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = [i/myInt for i in myList]
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
start_time = time.time()
newList = np.divide(myList, myInt)
end_time = time.time()
print(newList,end_time-start_time)
Regarding this link you can make the first solution provided by krzyk permanent by executing:
echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile
source ~/.bash_profile
Container(
width: double.infinity,
child: RaisedButton(...),
),
In my case with Ubuntu 14.04.3 and Apache 2.4.7, the problem was that I copied site1.conf to make site2.conf available, and by copying, something happend and I could not a2ensite site2.conf with the error described in thread.
The solution for me, was to rename site2.conf to site2 and then again rename site2 to site2.conf. After that I was able to a2ensite site2.conf.
You can use
$window.scrollTo(x, y);
where x
is the pixel along the horizontal axis and y
is the pixel along the vertical axis.
Scroll to top
$window.scrollTo(0, 0);
Focus on element
$window.scrollTo(0, angular.element('put here your element').offsetTop);
Update:
Also you can use $anchorScroll
(Firstly read the other answers which has explained the for
in the <label></label>
tags.
Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1"
but with different ids id="r1_1" ... id="r1_2"
So this way the answer is more clear and removes the conflicts between name and ids as well.
You need different ids for different options of the radio box.
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
<label for="r1_1">button text one</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
<label for="r1_2">button text two</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
<label for="r1_3">button text three</label>
_x000D_
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.
My solution is to create a custom EditTextPreference
, used in XML like this: <com.example.EditTextPreference android:title="Example Title" />
EditTextPreference.java:-
package com.example;
import android.content.Context;
import android.util.AttributeSet;
public class EditTextPreference extends android.preference.EditTextPreference
{
public EditTextPreference(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public EditTextPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public EditTextPreference(Context context)
{
super(context, null);
}
@Override
protected void onDialogClosed(boolean positiveResult)
{
super.onDialogClosed(positiveResult);
setSummary(getSummary());
}
@Override
public CharSequence getSummary()
{
return getText();
}
}
On Windows you need to include the gl.h
header for OpenGL 1.1 support and link against OpenGL32.lib. Both are a part of the Windows SDK. In addition, you might want the following headers which you can get from http://www.opengl.org/registry .
<GL/glext.h>
- OpenGL 1.2 and above compatibility profile and extension interfaces..<GL/glcorearb.h>
- OpenGL core profile and ARB extension interfaces, as described in appendix G.2 of the OpenGL 4.3 Specification. Does not include interfaces found only in the compatibility profile.<GL/glxext.h>
- GLX 1.3 and above API and GLX extension interfaces.<GL/wglext.h>
- WGL extension interfaces.On Linux you need to link against libGL.so, which is usually a symlink to libGL.so.1, which is yet a symlink to the actual library/driver which is a part of your graphics driver. For example, on my system the actual driver library is named libGL.so.256.53, which is the version number of the nvidia driver I use. You also need to include the gl.h
header, which is usually a part of a Mesa or Xorg package. Again, you might need glext.h
and glxext.h
from http://www.opengl.org/registry . glxext.h
holds GLX extensions, the equivalent to wglext.h
on Windows.
If you want to use OpenGL 3.x or OpenGL 4.x functionality without the functionality which were moved into the GL_ARB_compatibility
extension, use the new gl3.h
header from the registry webpage. It replaces gl.h
and also glext.h
(as long as you only need core functionality).
Last but not the least, glaux.h
is not a header associated with OpenGL. I assume you've read the awful NEHE tutorials and just went along with it. Glaux is a horribly outdated Win32 library (1996) for loading uncompressed bitmaps. Use something better, like libPNG, which also supports alpha channels.
As part of the uuid spec, if you generate a uuid from random it must contain a "4" as the 13th character and a "8", "9", "a", or "b" in the 17th (source).
// this makes sure that the 13th character is "4"
u[6] = (u[6] | 0x40) & 0x4F
// this makes sure that the 17th is "8", "9", "a", or "b"
u[8] = (u[8] | 0x80) & 0xBF
You have a lot of variants for using @RequestParam
with additional optional elements, e.g.
@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr
If you don't put required = false
- param will be required by default.
defaultValue = "someValue"
- the default value to use as a fallback when the request parameter is not provided or has an empty value.
If request and method param are the same - you don't need value = "someAttr"
I was tearing my hair out because for some items, the renamed item would get renamed again (repeatedly, unless max file name length was reached). This was happening both for Get-ChildItem and piping the output of dir. I guess that the renamed files got picked up because of a change in the alphabetical ordering. I solved this problem in the following way:
Get-ChildItem -Path . -OutVariable dirs
foreach ($i in $dirs) { Rename-Item $i.name ("<MY_PREFIX>"+$i.name) }
This "locks" the results returned by Get-ChildItem in the variable $dirs and you can iterate over it without fear that ordering will change or other funny business will happen.
Dave.Gugg's tip for using -Exclude should also solve this problem, but this is a different approach; perhaps if the files being renamed already contain the pattern used in the prefix.
(Disclaimer: I'm very much a PowerShell n00b.)
You can do it directly from eclipse using the Navigator view (Window -> Show View -> Navigator). In the Navigator view select the project and open it so that you can see the file .project
. Right click -> Open. You will get a XML editor view. Edit the content of the node natures
and insert a new child nature
with org.eclipse.jdt.core.javanature
as content. Save.
Now create a file .classpath
, it will open in the XML editor. Add a node named classpath
, add a child named classpathentry
with the attributes kind
with content con
and another one named path
and content org.eclipse.jdt.launching.JRE_CONTAINER
. Save-
Much easier: copy the files .project
and .classpath
from an existing Java project and edit the node result name
to the name of this project. Maybe you have to refresh the project (F5).
You'll get the same result as with the solution of Chris Marasti-Georg.
It is ||
, for example:
select 'Mr ' || ename from emp;
The only "interesting" feature I can think of is that 'x' || null
returns 'x'
, not null
as you might perhaps expect.
I solved the same problem with these commands:
curl -O https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py
In my case, I found that "android.R.layout.account_list" was referenced instead of "R.layout.account_list". Simply remove "android." can fix the problem. Hope this help because sometimes you may overlook when you are too focusing.
This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/
It is nicely designed Fluent API.
//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
.Configure()
.CreateTask("TaskName", "C:\\Test.bat")
.RunDaily()
.RunEveryXMinutes(10)
.RunDurationFor(new TimeSpan(18, 0, 0))
.SetStartDate(new DateTime(2015, 8, 8))
.SetStartTime(new TimeSpan(8, 0, 0))
.Execute();
That would be the tempfile module.
It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.
Example:
import tempfile
print tempfile.gettempdir() # prints the current temporary directory
f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here
For completeness, here's how it searches for the temporary directory, according to the documentation:
TMPDIR
environment variable.TEMP
environment variable.TMP
environment variable.Wimp$ScrapDir
environment variable.C:\TEMP
, C:\TMP
, \TEMP
, and \TMP
, in that order./tmp
, /var/tmp
, and /usr/tmp
, in that order.In my case I was using ClassName
.
getComputedStyle( document.getElementsByClassName(this_id)) //error
It will also work without 2nd argument " "
.
Here is my complete running code :
function changeFontSize(target) {
var minmax = document.getElementById("minmax");
var computedStyle = window.getComputedStyle
? getComputedStyle(minmax) // Standards
: minmax.currentStyle; // Old IE
var fontSize;
if (computedStyle) { // This will be true on nearly all browsers
fontSize = parseFloat(computedStyle && computedStyle.fontSize);
if (target == "sizePlus") {
if(fontSize<20){
fontSize += 5;
}
} else if (target == "sizeMinus") {
if(fontSize>15){
fontSize -= 5;
}
}
minmax.style.fontSize = fontSize + "px";
}
}
onclick= "changeFontSize(this.id)"
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
The one that I like is HexEdit Quick and easy to use
The code I ended up using. I think this is the best so far:
def tail(f, n, offset=None):
"""Reads a n lines from f with an offset of offset lines. The return
value is a tuple in the form ``(lines, has_more)`` where `has_more` is
an indicator that is `True` if there are more lines in the file.
"""
avg_line_length = 74
to_read = n + (offset or 0)
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None], \
len(lines) > to_read or pos > 0
avg_line_length *= 1.3
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
It's because you haven't declared outchar
before you use it. That means that the compiler will assume it's a function returning an int
and taking an undefined number of undefined arguments.
You need to add a prototype pf the function before you use it:
void outchar(char); /* Prototype (declaration) of a function to be called */ int main(void) { ... } void outchar(char ch) { ... }
Note the declaration of the main
function differs from your code as well. It's actually a part of the official C specification, it must return an int
and must take either a void
argument or an int
and a char**
argument.
I personally think that it's more important for the code to be readable and editable than performant. Whichever one you find easier to look at and it should be the one you choose for above factors. You can write it as:
$('#box').append(
$('<div/>')
.attr("id", "newDiv1")
.addClass("newDiv purple bloated")
.append("<span/>")
.text("hello world")
);
And your first Method as:
// create an element with an object literal, defining properties
var $e = $("<div>", {id: "newDiv1", name: 'test', class: "aClass"});
$e.click(function(){ /* ... */ });
// add the element to the body
$("#box").append($e);
But as far as readability goes; the jQuery approach is my favorite. Follow this Helpful jQuery Tricks, Notes, and Best Practices
(Following is a late but complete answer)
FileReader.readAsBinaryString()
is deprecated. Don't use it! It's no longer in the W3C File API working draft:
void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);
NB: Note that File
is a kind of extended Blob
structure.
Mozilla still implements readAsBinaryString()
and describes it in MDN FileApi documentation:
void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);
The reason behind readAsBinaryString()
deprecation is in my opinion the following: the standard for JavaScript strings are DOMString
which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.
We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob
and typed arrays
(ArrayBuffer
and the not-yet-implemented but not necessary StringView
) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.
XMLHttpRequest.send()
has the following invocations options:
void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
XMLHttpRequest.sendAsBinary()
has the following invocations options:
void sendAsBinary( in DOMString body );
sendAsBinary() is NOT a standard and may not be supported in Chrome.
So you have several options:
send()
the FileReader.result
of FileReader.readAsArrayBuffer ( fileObject )
. It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.send()
the FileReader.result
of FileReader.readAsDataURL( fileObject )
. It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.sendAsBinary()
the FileReader.result
of FileReader.readAsBinaryString( fileObject )
MDN states that:
The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.
Have you configured the virtual directory as an ASP.NET application for the right framework version?
See IIS Setup
You can use move
for this. The documentation from help move
states:
Moves files and renames files and directories.
To move one or more files:
MOVE [/Y | /-Y] [drive:][path]filename1[,...] destination
To rename a directory:
MOVE [/Y | /-Y] [drive:][path]dirname1 dirname2
[drive:][path]filename1 Specifies the location and name of the file
or files you want to move.
destination Specifies the new location of the file. Destination
can consist of a drive letter and colon, a
directory name, or a combination. If you are moving
only one file, you can also include a filename if
you want to rename the file when you move it.
[drive:][path]dirname1 Specifies the directory you want to rename.
dirname2 Specifies the new name of the directory.
/Y Suppresses prompting to confirm you want to
overwrite an existing destination file.
/-Y Causes prompting to confirm you want to overwrite
an existing destination file.
The switch /Y may be present in the COPYCMD environment variable.
This may be overridden with /-Y on the command line. Default is
to prompt on overwrites unless MOVE command is being executed from
within a batch script.
See the following transcript for an example where it initially shows the qq1
and qq2
directories as having three and no files respectively. Then, we do the move
and we find that the three files have been moved from qq1
to qq2
as expected.
C:\Documents and Settings\Pax\My Documents>dir qq1
Volume in drive C is Primary
Volume Serial Number is 04F7-0E7B
Directory of C:\Documents and Settings\Pax\My Documents\qq1
20/01/2011 11:36 AM <DIR> .
20/01/2011 11:36 AM <DIR> ..
20/01/2011 11:36 AM 13 xx1
20/01/2011 11:36 AM 13 xx2
20/01/2011 11:36 AM 13 xx3
3 File(s) 39 bytes
2 Dir(s) 20,092,547,072 bytes free
C:\Documents and Settings\Pax\My Documents>dir qq2
Volume in drive C is Primary
Volume Serial Number is 04F7-0E7B
Directory of C:\Documents and Settings\Pax\My Documents\qq2
20/01/2011 11:36 AM <DIR> .
20/01/2011 11:36 AM <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 20,092,547,072 bytes free
C:\Documents and Settings\Pax\My Documents>move qq1\* qq2
C:\Documents and Settings\Pax\My Documents\qq1\xx1
C:\Documents and Settings\Pax\My Documents\qq1\xx2
C:\Documents and Settings\Pax\My Documents\qq1\xx3
C:\Documents and Settings\Pax\My Documents>dir qq1
Volume in drive C is Primary
Volume Serial Number is 04F7-0E7B
Directory of C:\Documents and Settings\Pax\My Documents\qq1
20/01/2011 11:37 AM <DIR> .
20/01/2011 11:37 AM <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 20,092,547,072 bytes free
C:\Documents and Settings\Pax\My Documents>dir qq2
Volume in drive C is Primary
Volume Serial Number is 04F7-0E7B
Directory of C:\Documents and Settings\Pax\My Documents\qq2
20/01/2011 11:37 AM <DIR> .
20/01/2011 11:37 AM <DIR> ..
20/01/2011 11:36 AM 13 xx1
20/01/2011 11:36 AM 13 xx2
20/01/2011 11:36 AM 13 xx3
3 File(s) 39 bytes
2 Dir(s) 20,092,547,072 bytes free
I don't think you can its an operator and its suppose to return one or the other. It's not if else statement replacement although it can be use for that on certain case.
You can update the accepted answer with the iter_lines method of requests if the file is very large
import csv
import requests
CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'
with requests.Session() as s:
download = s.get(CSV_URL)
line_iterator = (x.decode('utf-8') for x in download.iter_lines(decode_unicode=True))
cr = csv.reader(line_iterator, delimiter=',')
my_list = list(cr)
for row in my_list:
print(row)
in case it helps someone, my issue seems to be just because I was using a subfolder under my home directory, even though permissions seem correct and I don't have SELinux or anything like that. changing it to be under /var/www/something/something made it work.
(if I ever found the real cause, and remember this answer, I'll update it)
Declare @phoneNumber int
select @phoneNumber=Isnull('08041159620',0);
Give error :
The conversion of the varchar value '8041159620' overflowed an int column.: select cast('8041159620' as int)
AS
Integer is defined as :
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.
Solution
Declare @phoneNumber bigint
OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.
<script>
function dostuff() {
if (document.getElementById('MyBox').style.height == "0px") {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;");
}
else {
document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;");
}
}
</script>
<div id="MyBox" style="height: 0px; width: 0px;">
</div>
<input type="button" id="buttontest" onclick="dostuff()" value="Click Me">
If you go to Internet Explorer, Tools, Internet Option, Security, Custom, find the "Include local directory path When uploading files to a server" (it is quite a ways down) and click on "Enable" . This will work
gg=G
will reindent the entire file and removes most if not all the tabs I get in files from co-workers.
To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.
If you have image in the form of bitmap then use
imageview.setImageBitmap(bm);
If you have image in the form of drawable then use
imageview.setImageDrawable(drawable);
If you have image in your resource example if image is present in drawable folder then use
imageview.setImageResource(R.drawable.image);
If you have path of image then use
imageview.setImageURI(Uri.parse("pathofimage"));
The same error occurred when I had another variable named mythread. That variable overwrote this and that's why I got error
or you can try this:
string1 = 'Hello \n World'
tmp = string1.split()
string2 = ' '.join(tmp)
I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.
If you are using Visual Studio 2017 and come across this question, you might consider AxoCover. It's a free VS extension that integrates OpenCover, but supports VS2017 (it also appears to be under active development. +1).
For what it's worth.
$('.js-toggle-edit').on('click', function (e) {
var bool = $('.js-editable').prop('readonly');
$('.js-editable').prop('readonly', ! bool);
})
Keep in mind you can pass a closure to .prop(), and do a per element check. But in this case it doesn't matter, it's just a mass toggle.
In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow
So i used:
stage ('Starting ART job') {
build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.
>>> 1 / 2
0
You should make one of them a float
:
>>> float(10 - 20) / (100 - 10)
-0.1111111111111111
or from __future__ import division
, which the forces /
to adopt Python 3.x's behavior that always returns a float.
>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111
Stuzor and hexcodes solution worked for me as well. However, if you do want the latest connector you have to download another product. From the oracle website:
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
Collections.addAll is what you want.
Collections.addAll(myArrayList, '+', '-', '*', '^');
Another option is to pass the list into the constructor using Arrays.asList like this:
List<Character> myArrayList = new ArrayList<Character>(Arrays.asList('+', '-', '*', '^'));
If, however, you are good with the arrayList being fixed-length, you can go with the creation as simple as list = Arrays.asList(...)
. Arrays.asList specification states that it returns a fixed-length list which acts as a bridge to the passed array, which could be not what you need.
Do a "recursive" setTimeout
of your function, and it will keep being executed every amount of time defined:
function yourFunction(){
// do whatever you like here
setTimeout(yourFunction, 5000);
}
yourFunction();
I used:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
to disable the screen timeout and
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
to re-enable it.
Yes, there is - python may not be in /usr/bin
, but for example in /usr/local/bin
(BSD).
When using virtualenv, it may even be something like ~/projects/env/bin/python
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
Just above JSON.parse
, use:
var newData = JSON.stringify(userData)
There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.
It's worth pointing out that this advice is for CakePHP 2.x, not 3.x.
You would create a relationship with your User model and Messages Model, and use the containable behavior:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array('Message');
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array('User');
}
You need to change the messages.from
column to be messages.user_id
so that cake can automagically associate the records for you.
Then you can do this from the messages controller:
$this->Message->find('all', array(
'contain' => array('User')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController
:
$this->Message->find('all', array(
'joins' => array(
array(
'table' => 'users',
'alias' => 'UserJoin',
'type' => 'INNER',
'conditions' => array(
'UserJoin.id = Message.from'
)
)
),
'conditions' => array(
'Message.to' => 4
),
'fields' => array('UserJoin.*', 'Message.*'),
'order' => 'Message.datetime DESC'
));
Note, I've left the field name messages.from
the same as your current table in this example.
Here is how you can do the first example using two relationships to the same model:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array(
'MessagesSent' => array(
'className' => 'Message',
'foreignKey' => 'from'
)
);
public $belongsTo = array(
'MessagesReceived' => array(
'className' => 'Message',
'foreignKey' => 'to'
)
);
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'UserFrom' => array(
'className' => 'User',
'foreignKey' => 'from'
)
);
public $hasMany = array(
'UserTo' => array(
'className' => 'User',
'foreignKey' => 'to'
)
);
}
Now you can do your find call like this:
$this->Message->find('all', array(
'contain' => array('UserFrom')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
When a query takes that long, I would advice to run it asynchronously and use a callback function for when it's complete.
I don't have much experience with ASP.NET, but maybe you can use AJAX for this asynchronous behavior.
Typically a web page should load in mere seconds, not minutes. Don't keep your users waiting for so long!
This works for me:
@Transactional
public void remove(Integer groupId) {
Group group = groupRepository.findOne(groupId);
group.getUsers().removeAll(group.getUsers());
// Other business logic
groupRepository.delete(group);
}
Also, mark the method @Transactional (org.springframework.transaction.annotation.Transactional), this will do whole process in one session, saves some time.
Although this post is very old. In case if somebody is looking for this..
Guava facilitates partitioning the List into sublists of a specified size
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List<List<Integer>> subSets = Lists.partition(intList, 3);
Check scipy.stats.mode()
(inspired by @tom10's comment):
import numpy as np
from scipy import stats
a = np.array([[1, 3, 4, 2, 2, 7],
[5, 2, 2, 1, 4, 1],
[3, 3, 2, 2, 1, 1]])
m = stats.mode(a)
print(m)
Output:
ModeResult(mode=array([[1, 3, 2, 2, 1, 1]]), count=array([[1, 2, 2, 2, 1, 2]]))
As you can see, it returns both the mode as well as the counts. You can select the modes directly via m[0]
:
print(m[0])
Output:
[[1 3 2 2 1 1]]
This code works very well
function isUndefined(array, index) {
return ((String(array[index]) == "undefined") ? "Yes" : "No");
}
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
You can simply use:
ps -o args= -f -p ProcessPid
Cause: The error occurred since hibernate is not able to connect to the database.
Solution:
1. Please ensure that you have a database present at the server referred to in the configuration file eg. "hibernatedb" in this case.
2. Please see if the username and password for connecting to the db are correct.
3. Check if relevant jars required for the connection are mapped to the project.
On later versions of common Linux distributions you can use:
date -d @1267619929
If a global hotkey would suffice, then RegisterHotKey would do the trick
Try
safeRunCommand() {
"$@"
if [ $? != 0 ]; then
printf "Error when executing command: '$1'"
exit $ERROR_CODE
fi
}
Just do it in the Base, that way any child can be Serialized, less code cleaner code.
public abstract class XmlBaseClass
{
public virtual string Serialize()
{
this.SerializeValidation();
XmlSerializerNamespaces XmlNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
XmlWriterSettings XmlSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
StringWriter StringWriter = new StringWriter();
XmlSerializer Serializer = new XmlSerializer(this.GetType());
XmlWriter XmlWriter = XmlWriter.Create(StringWriter, XmlSettings);
Serializer.Serialize(XmlWriter, this, XmlNamespaces);
StringWriter.Flush();
StringWriter.Close();
return StringWriter.ToString();
}
protected virtual void SerializeValidation() {}
}
[XmlRoot(ElementName = "MyRoot", Namespace = "MyNamespace")]
public class XmlChildClass : XmlBaseClass
{
protected override void SerializeValidation()
{
//Add custom validation logic here or anything else you need to do
}
}
This way you can call Serialize on the child class no matter the circumstance and still be able to do what you need to before object Serializes.
A simple way is the NSSM Wrapper Wrapper (see my blog entry).
Isn't it easiest and shortest that way? I knew it and just tested it - working perfect here:
@GetMapping
public String hello(HttpSession session) {
session.setAttribute("name","value");
return "hello";
}
p.s. I came here searching for an answer of "How to use Session attributes in Spring-mvc", but read so many without seeing the most obvious that I had written in my code. I didn't see it, so I thought its wrong, but no it was not. So lets share that knowledge with the easiest solution for the main question.
For me, this error occurred when I was out of space on my remote.
I just needed to read the rest of the error message:
error: file write error (No space left on device)
fatal: unable to write sha1 file
error: unpack failed: unpack-objects abnormal exit
Qt works very well with graphics. In my opinion it is more versatile than PIL.
You get all the features you want for graphics manipulation, but there's also vector graphics and even support for real printers. And all of that in one uniform API, QPainter
.
To use Qt you need a Python binding for it: PySide or PyQt4.
They both support Python 3.
Here is a simple example that loads a JPG image, draws an antialiased circle of radius 10 at coordinates (20, 20) with the color of the pixel that was at those coordinates and saves the modified image as a PNG file:
from PySide.QtCore import *
from PySide.QtGui import *
app = QCoreApplication([])
img = QImage('input.jpg')
g = QPainter(img)
g.setRenderHint(QPainter.Antialiasing)
g.setBrush(QColor(img.pixel(20, 20)))
g.drawEllipse(QPoint(20, 20), 10, 10)
g.end()
img.save('output.png')
But please note that this solution is quite 'heavyweight', because Qt is a large framework for making GUI applications.
The issue I had is that sometimes I will need to get at a value that is deeply
nested. Normally you would need to do a type assertion at each level, so I went
ahead and just made a method that takes a map[string]interface{}
and a
string
key, and returns the resulting map[string]interface{}
.
The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:
package main
type Slice []interface{}
type Map map[string]interface{}
func (m Map) M(s string) Map {
return m[s].(map[string]interface{})
}
func (m Map) A(s string) Slice {
return m[s].([]interface{})
}
func (a Slice) M(n int) Map {
return a[n].(map[string]interface{})
}
and example code:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
o, e := os.Open("a.json")
if e != nil {
log.Fatal(e)
}
in_m := Map{}
json.NewDecoder(o).Decode(&in_m)
out_m := in_m.
M("contents").
M("sectionListRenderer").
A("contents").
M(0).
M("musicShelfRenderer").
A("contents").
M(0).
M("musicResponsiveListItemRenderer").
M("navigationEndpoint").
M("browseEndpoint")
fmt.Println(out_m)
}
In my case I was getting this error when attempting to update the authentication settings in IIS also in addition to browsing. I was able to remove this error by removing the authentication setting from the web.config itself. Removing a problematic configuration section may be less invasive and preferable in some cases than changing the server roles and features too much:
Section Removed:
<security>
<authentication>
<windowsAuthentication enabled="true" />
</authentication>
</security>
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
git commit -am 'Conflicts resolved'
This worked for me. You can try this also.
I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.
// first day of the month
var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();
Go back and forth using the subtract()
and add()
with the endOf()
and startOf()
:
// last day of previous month
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();
You can resolve this problem by adding nodemon
to your package.json
:
npm install nodemon --save-dev
The problem happens when nodemon
does not exist in /node_modules/.bin
.
Added --save-dev
since it's required during development only.
See my comment above, and I believe you have to use NSInvocation when there is more than one parameter
more information on NSInvocation here
http://cocoawithlove.com/2008/03/construct-nsinvocation-for-any-message.html
$('#demoTable td').contents().each(function() {
if (this.nodeType === 3) {
this.textContent
? this.textContent = 'The text has been '
: this.innerText = 'The text has been '
} else {
this.innerHTML = 'changed';
return false;
}
})
I think the easiest way to do this would be to set the columns to the top level:
df.columns = df.columns.get_level_values(0)
Note: if the to level has a name you can also access it by this, rather than 0.
.
If you want to combine/join
your MultiIndex into one Index (assuming you have just string entries in your columns) you could:
df.columns = [' '.join(col).strip() for col in df.columns.values]
Note: we must strip
the whitespace for when there is no second index.
In [11]: [' '.join(col).strip() for col in df.columns.values]
Out[11]:
['USAF',
'WBAN',
'day',
'month',
's_CD sum',
's_CL sum',
's_CNT sum',
's_PC sum',
'tempf amax',
'tempf amin',
'year']
In a nutshell, no.
However, there are "nice" things you can do.
INSERT dbo.SPCall (What, When) VALUES (OBJECT_NAME(@@PROCID), GETDATE()
"There are "fun" things you can do:
RAISERROR ('Warning: pwn3d: call admin', 16, 1)
, see who callsWAITFOR DELAY '00:01:00'
, see who callsYou get the idea. The tried-and-tested "see who calls" method of IT support.
If the reports are Reporting Services, then you can mine the RS database for the report runs if you can match code to report DataSet.
You couldn't rely on DMVs anyway because they are reset om SQL Server restart. Query cache/locks are transient and don't persist for any length of time.
Try
if (!(i == 'InvKey' || i == 'PostDate')) {
or
if (i != 'InvKey' || i != 'PostDate') {
that says if i does not equals InvKey
OR PostDate
Map over the keys of the object using Object.keys()
:
{Object.keys(yourObject).map(function(key) {
return <div>Key: {key}, Value: {yourObject[key]}</div>;
})}
Use the following to jump to previous folder:
os.chdir(os.pardir)
If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.
json
is simplejson
, added to the stdlib. But since json
was added in 2.6, simplejson
has the advantage of working on more Python versions (2.4+).
simplejson
is also updated more frequently than Python, so if you need (or want) the latest version, it's best to use simplejson
itself, if possible.
A good practice, in my opinion, is to use one or the other as a fallback.
try:
import simplejson as json
except ImportError:
import json
I had a similar problem. I searched conda.exe
and I found it on Scripts folder. So, In Anaconda3 you need to add two variables to PATH
. The first is Anaconda_folder_path
and the second is Anaconda_folder_path\Scripts
If you are using Entity Framework 6, the name space has changed. You want to use
System.Data.Entity.Core.Objects.ObjectQuery
A reasonably good type capture function is the one used by YUI3:
var TYPES = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]': 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
},
TOSTRING = Object.prototype.toString;
function type(o) {
return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};
This captures many of the primitives provided by javascript, but you can always add more by modifying the TYPES
object. Note that typeof HTMLElementCollection
in Safari will report function
, but type(HTMLElementCollection) will return object
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
With no parameters, the .hide() method is the simplest way to hide an element:
$('.target').hide(); The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.
Same about show
add semi-colon the line before:
$total_pages = ceil($total_result / $per_page);
Looked through the answers and the most obvious and straight forward is missing: use document.write()
to write out a chunk of CSS you need.
Here is an example (view it on codepen: http://codepen.io/ssh33/pen/zGjWga):
<style>
@import url(http://fonts.googleapis.com/css?family=Open+Sans:800);
.d, body{ font: 3vw 'Open Sans'; padding-top: 1em; }
.d {
text-align: center; background: #aaf;
margin: auto; color: #fff; overflow: hidden;
width: 12em; height: 5em;
}
</style>
<script>
function w(s){document.write(s)}
w("<style>.long-shadow { text-shadow: ");
for(var i=0; i<449; i++) {
if(i!= 0) w(","); w(i+"px "+i+"px #444");
}
w(";}</style>");
</script>
<div class="d">
<div class="long-shadow">Long Shadow<br> Short Code</div>
</div>
I got this exact same error because Cordova will allow you to create a project with spaces in it, and Xcode doesn't know how to deal.
Attach an event handler to the submit event of the form. Make sure it cancels the default action.
Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.
Here is how you would do it in YUI 3:
<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
YUI().use('event', function (Y) {
Y.one('form').on('submit', function (e) {
// Whatever else you want to do goes here
e.preventDefault();
});
});
</script>
Make sure that the server will pick up the slack if the JavaScript fails for any reason.
sudo apt-get install zlib1g:i386 fixed the Gradle issue on Android 2.1.1 on Xubuntu 16.04.
The docs are pretty clear on this: HashSet.add
doesn't replace:
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
But HashMap.put
will replace:
If the map previously contained a mapping for the key, the old value is replaced.
Your sample array has 3 levels. Because the first level has only [0]
, you can hardcode your access into it and avoid an extra function/construct call.
array_walk_recursive() is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.
array_walk_recursive($array, function($leafvalue)use(&$flat){$flat[] = $leafvalue;});
var_export($flat);
If this was my code, I'd be using array_column() because it is direct and speaks literally about the action being performed.
var_export(array_column($array[0], 'plan'));
Of course a couple of `foreach() loops will perform very efficiently because language constructs generally perform more efficiently than function calls.
foreach ($array[0] as $plans) {
foreach ($plans as $value) {
$flat[] = $value;
}
}
var_export($flat);
Finally, as a funky alternative (which I can't imagine actually putting to use unless I was writing code for someone whom I didn't care for) I'll offer an array_merge_recursive() call with a splat operator (...
).
var_export(array_merge_recursive(...$array[0])['plan']);
To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.
To correct this, add a null check...
SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN
(SELECT pd.part_num FROM wpsapi4.product_details pd
where pd.part_num is not null)
You can set the spinner prompt:
spinner.setPrompt("Select gender...");
=IF(A2="Y","Male",IF(A2="N","Female",""))
If you use the prettier extension in Visual Studio Code, try adding this to the settings.json file:
"editor.insertSpaces": false,
"editor.tabSize": 4,
"editor.detectIndentation": false,
"prettier.tabWidth": 4,
"prettier.useTabs": true // This made it finally work for me
In reference to @stanley's comment -
Don't try and use tap gestures to row selections to work in UITableView
as it already has full tap handling....
But you must set 'Cancels Touches in View' to 'NO' on your single tap gesture recognizers or it will never get the tap events.
You seem to be specifying the form to use a HTTP 'GET' request using FormMethod.Get
. This will not work unless you tell it to do a post as that is what you seem to want the ActionResult to do. This will probably work by changing FormMethod.Get
to FormMethod.Post
.
As well as this you may also want to think about how Get and Post requests work and how these interact with the Model.
You need a 64-bit
trio:
64-bit
OS64-bit
Java 64-bit
EclipseKotlin solution:
fun TextView.disableCopyPaste() {
isLongClickable = false
setTextIsSelectable(false)
customSelectionActionModeCallback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode?, menu: Menu): Boolean {
return false
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem): Boolean {
return false
}
override fun onDestroyActionMode(mode: ActionMode?) {}
}
}
Then you can simply call this method on your TextView
:
override fun onCreate() {
priceEditText.disableCopyPaste()
}
simply use..
location.reload(true/false);
If false, the page will be reloaded from cache, else from the server.
PHP redirects are better if you can as with the JavaScript one you're causing the client to load the page before the redirect, whereas with the PHP one it sends the proper header.
However the PHP shouldn't go in the <head>, it should go before any output is sent to the client, as to do otherwise will cause errors.
Using <meta> tags have the same issue as Javascript in causing the initial page to load before doing the redirect. Server-side redirects are almost always better, if you can use them.
md5.h
also have MD5_*
functions very useful for big file
#include <openssl/md5.h>
#include <fstream>
.......
std::ifstream file(filename, std::ifstream::binary);
MD5_CTX md5Context;
MD5_Init(&md5Context);
char buf[1024 * 16];
while (file.good()) {
file.read(buf, sizeof(buf));
MD5_Update(&md5Context, buf, file.gcount());
}
unsigned char result[MD5_DIGEST_LENGTH];
MD5_Final(result, &md5Context);
Very simple, isn`t it? Convertion to string also very simple:
#include <sstream>
#include <iomanip>
.......
std::stringstream md5string;
md5string << std::hex << std::uppercase << std::setfill('0');
for (const auto &byte: result)
md5string << std::setw(2) << (int)byte;
return md5string.str();
I used a global action filter to remove Accept: application/xml
when the User-Agent
header contains "Chrome":
internal class RemoveXmlForGoogleChromeFilter : IActionFilter
{
public bool AllowMultiple
{
get { return false; }
}
public async Task<HttpResponseMessage> ExecuteActionFilterAsync(
HttpActionContext actionContext,
CancellationToken cancellationToken,
Func<Task<HttpResponseMessage>> continuation)
{
var userAgent = actionContext.Request.Headers.UserAgent.ToString();
if (userAgent.Contains("Chrome"))
{
var acceptHeaders = actionContext.Request.Headers.Accept;
var header =
acceptHeaders.SingleOrDefault(
x => x.MediaType.Contains("application/xml"));
acceptHeaders.Remove(header);
}
return await continuation();
}
}
Seems to work.
I got this working on a join plus union.
(SELECT
table1.column1,
table1.column2,
foo1.column4
FROM table1, table2, foo1, table5
WHERE table5.somerecord = table1.column1
ORDER BY table1.column1 ASC, table1.column2 DESC
)
UNION
(SELECT
... Another complex query as above
)
ORDER BY column1 DESC, column2 ASC
If you don't want indention in your list and also don't care about or don't want bullets, there is the CSS-free option of using a "definition list" (HTML 4.01) or "description list" (HTML 5). Use only the non-indenting definition <dt>
tags, but not the indenting description <dd>
tags, neither of which produces a bullet.
<dl>
<dt>Item 1</dt>
<dt>Item 2</dt>
<dt>Item 3</dt>
</dl>
The output looks like this:
Item 1
Item 2
Item 3
Had a similar problem, where I had to set the form back to pristine, but also to untouched, since $invalid and $error were both used to show error messages. Only using setPristine() was not enough to clear the error messages.
I solved it by using setPristine() and setUntouched(). (See Angular's documentation: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController)
So, in my controller, I used:
$scope.form.setPristine();
$scope.form.setUntouched();
These two functions reset the complete form to $pristine and back to $untouched, so that all error messages were cleared.
you need to set the margin of the body to 0 for the table to stretch the full width. alternatively you can set the margin of the table to a negative number as well.
a possible solution could be
create a batch file
there do a loop on lib directory for all files inside it and set each file unside lib on classpath
then after that run the jar
source for loop in batch file for info on loops
I use it for two reasons:
I can force a refresh of the icon by adding a query parameter for example ?v=2
. like this:
<link rel="icon" href="/favicon.ico?v=2" type="image/x-icon" />
In case I need to specify the path.
Try
UPDATE products SET former_date=20111218131717 WHERE id=1
Alternatively, you might want to look at using the STR_TO_DATE (see STR_TO_DATE(str,format)) function.
you can do it simpler without jquery
location = "https://example.com/" + txt.value
function send() {_x000D_
location = "https://example.com/" + txt.value;_x000D_
}
_x000D_
<form id="abc">_x000D_
<input type="text" id="txt" />_x000D_
</form>_x000D_
_x000D_
<button onclick="send()">Send</button>
_x000D_
CREATE PROCEDURE sp_deleteUserDetails
@Email varchar(255)
AS
declare @tempRegId as int
Delete UserRegistration where Email=@Email
set @tempRegId = (select Id from UserRegistration where Email = @Email)
Delete UserProfile where RegID=@tempRegId
RETURN 0
This works for me
cd "C:\Program Files\SmartBear\SoapUI-5.6.0\bin"
start SoapUI-5.6.0.exe -w "C:\DATA\SoapUi\Workspaces\Production-workspace.xml"
exit
These methods are in ObjectNode
: the division is such that most read operations are included in JsonNode
, but mutations in ObjectNode
and ArrayNode
.
Note that you can just change first line to be:
ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type
or
ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast
December 2020 :
To answer the question :
<video>
element.I think this question should be closed.