Spring Boot, v2.3.0.RELEASE
Recommended (In application.properties):
logging.level.org.hibernate.SQL=DEBUG //logs all SQL DML statements
logging.level.org.hibernate.type=TRACE //logs all JDBC parameters
parameters
Note:
The above will not give you a pretty-print though.
You can add it as a configuration:
properties.put("hibernate.format_sql", "true");
or as per below.
Works but NOT recommended
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Reason: It's better to let the logging framework manage/optimize the output for you + it doesn't give you the prepared statement parameters.
Cheers
for all who will try this in the future.
org.springframework.scheduling.quartz.JobDetailBean supplies map of objects and those objects may be spring beans.
define smth like
<bean name="myJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass"
value="my.cool.class.myCoolJob" />
<property name="jobDataAsMap">
<map>
<entry key="myBean" value-ref="myBean" />
</map>
</property>
</bean>
and then, inside
public void executeInternal(JobExecutionContext context)
call myBean = (myBean) context.getMergedJobDataMap().get("myBean");
and you all set.
I know, it looks ugly, but as a workaround it works
Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<jee:jndi-lookup id="dataSource"
jndi-name="Give_DataSource_Path_From_Your_Server"
expected-type="javax.sql.DataSource" />
Hope It will help someone.Thanks!
sql injection is ignored by prepared statement so security is increase in prepared statement
The first thing to do is to figure out which logging framework is actually used.
Many frameworks are already covered by other authors above. In case you are using Logback you can solve the problem by adding this logback.xml to your classpath:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<logger name="org.hibernate" level="WARN"/>
</configuration>
Further information: Logback Manual-Configuration
I have a use case where I think finally
should be a perfectly acceptable part of the C++11 language, as I think it is easier to read from a flow point of view. My use case is a consumer/producer chain of threads, where a sentinel nullptr
is sent at the end of the run to shut down all threads.
If C++ supported it, you would want your code to look like this:
extern Queue downstream, upstream;
int Example()
{
try
{
while(!ExitRequested())
{
X* x = upstream.pop();
if (!x) break;
x->doSomething();
downstream.push(x);
}
}
finally {
downstream.push(nullptr);
}
}
I think this is more logical that putting your finally declaration at the start of the loop, since it occurs after the loop has exited... but that is wishful thinking because we can't do it in C++. Note that the queue downstream
is connected to another thread, so you can't put in the sentinel push(nullptr)
in the destructor of downstream
because it can't be destroyed at this point... it needs to stay alive until the other thread receives the nullptr
.
So here is how to use a RAII class with lambda to do the same:
class Finally
{
public:
Finally(std::function<void(void)> callback) : callback_(callback)
{
}
~Finally()
{
callback_();
}
std::function<void(void)> callback_;
};
and here is how you use it:
extern Queue downstream, upstream;
int Example()
{
Finally atEnd([](){
downstream.push(nullptr);
});
while(!ExitRequested())
{
X* x = upstream.pop();
if (!x) break;
x->doSomething();
downstream.push(x);
}
}
I would like to mention what is explained in Java Concurrency in Practice:
First point, whether Notify or NotifyAll?
It will be NotifyAll, and reason is that it will save from signall hijacking.
If two threads A and B are waiting on different condition predicates of same condition queue and notify is called, then it is upto JVM to which thread JVM will notify.
Now if notify was meant for thread A and JVM notified thread B, then thread B will wake up and see that this notification is not useful so it will wait again. And Thread A will never come to know about this missed signal and someone hijacked it's notification.
So, calling notifyAll will resolve this issue, but again it will have performance impact as it will notify all threads and all threads will compete for same lock and it will involve context switch and hence load on CPU. But we should care about performance only if it is behaving correctly, if it's behavior itself is not correct then performance is of no use.
This problem can be solved with using Condition object of explicit locking Lock, provided in jdk 5, as it provides different wait for each condition predicate. Here it will behave correctly and there will not be performance issue as it will call signal and make sure that only one thread is waiting for that condition
I had the same problem. I found that if I use a DOCTYPE like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
it didn't work. But if I use:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
it did work.
I might be old-school about this, but I still frown on hotlinking. Maybe Google is the exception, but in general, it's really just good manners to host the files on your own server.
You can get these data from RouteData of a ViewContext
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["action"]
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if #available(iOS 10, *) {
//Notifications get posted to the function (delegate): func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else {
//Display Error.. Handle Error.. etc..
return
}
if granted {
//Do stuff here..
//Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
else {
//Handle user denying permissions..
}
}
//Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
application.registerForRemoteNotifications()
}
else {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
return true
}
Like ligget78 said, DPAPI would be a good way to go for storing passwords. Check out the ProtectedData class on MSDN for example usage.
{{ }}
tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %}
template tag and then assign the value the same way you would in normal python code.
{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}
Result:
it worked
This is a bit confusing, but follow these steps to save the session.
To open the session, double click on particular saved session.
Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...
The other reason is, that it's not clear at all what the "right" implementation of a set is:
There is a functional approach:
func IsInEvenNumbers(n int) bool {
if n % 2 == 0 {
return true
}
return false
}
This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.
A map does not have that problem, since you store something associated with the value.
It would be simpler if you configured it to just run e.g. on monday and thursdays, which would give it a 3 and 4 day break.
Otherwise configure it to run daily, but make your php cron script exit early with:
if (! (date("z") % 3)) {
exit;
}
Only set the time in mills on Calendar object
Calendar c = Calendar.getInstance();
c.setTimeInMillis(1385355600000l);
System.out.println(c.get(Calendar.YEAR));
System.out.println(c.get(Calendar.MONTH));
System.out.println(c.get(Calendar.DAY_OF_MONTH));
// get Date
System.out.println(c.getTime());
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
Just need to add 2 attributes for asp button :
OnClientClick="this.disabled='true';" UseSubmitBehavior="false"
e.g.
<asp:Button ID="Button1" runat="server" Text="TEST" OnClientClick="this.disabled='true';" UseSubmitBehavior="false" CssClass="button-content btnwidth" OnClick="ServerSideMethod_Click" />
For more details:
https://bytes.com/topic/asp-net/answers/918280-disable-button-click-prevent-multiple-postbacks
Use:
options={"default":"foo bar"}
and not:
options={"default"="foo bar"}
For instance:
/**
* @ORM\Column(name="foo", type="smallint", options={"default":0})
*/
private $foo
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
Ordinarily adding '%' to the int value of a char will not work when encoding, the value is supposed to the the hex equivalent. e.g '/' is '%2F' not '%47'.
I think this is the best and concise solutions for both url encoding and decoding (No much header dependencies).
string urlEncode(string str){
string new_str = "";
char c;
int ic;
const char* chars = str.c_str();
char bufHex[10];
int len = strlen(chars);
for(int i=0;i<len;i++){
c = chars[i];
ic = c;
// uncomment this if you want to encode spaces with +
/*if (c==' ') new_str += '+';
else */if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') new_str += c;
else {
sprintf(bufHex,"%X",c);
if(ic < 16)
new_str += "%0";
else
new_str += "%";
new_str += bufHex;
}
}
return new_str;
}
string urlDecode(string str){
string ret;
char ch;
int i, ii, len = str.length();
for (i=0; i < len; i++){
if(str[i] != '%'){
if(str[i] == '+')
ret += ' ';
else
ret += str[i];
}else{
sscanf(str.substr(i + 1, 2).c_str(), "%x", &ii);
ch = static_cast<char>(ii);
ret += ch;
i = i + 2;
}
}
return ret;
}
You can use getEventListeners in your Google Chrome developer console.
getEventListeners(object) returns the event listeners registered on the specified object.
getEventListeners(document.querySelector('option[value=Closed]'));
In Firefox there is Ctrl+Shift+K for the Web console, then you type
;decodeURIComponent("%2c")
and you get the answer:
","
In Spring Boot Rest Controller, I have resolved these by following Steps:
@GetMapping("/statusByEmail/{email:.+}/")
public String statusByEmail(@PathVariable(value = "email") String email){
//code
}
Get http://mywebhook.com/statusByEmail/[email protected]/
You can make it like this:
$('#inputID').keypress(function () {
var maxLength = $(this).val().length;
if (maxLength >= 5) {
alert('You cannot enter more than ' + maxLength + ' chars');
return false;
}
});
Real VNC Viewer (5.0.3) - Free :
Options->Expert->UseAllMonitors = True
UIWebView in Swift
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL (string: "url here")
let requestObj = URLRequest(url: url!)
webView.loadRequest(requestObj)
// Do any additional setup after loading the view.
}
/////////////////////////////////////////////////////////////////////// if you want to use webkit
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.webView.frame.size.height))
self.view.addSubview(webView)
let url = URL(string: "your URL")
webView.load(URLRequest(url: url!))`
I tried various different methods:
printexec() {
printf -- "\033[1;37m$\033[0m"
printf -- " %q" "$@"
printf -- "\n"
eval -- "$@"
eval -- "$*"
"$@"
"$*"
}
Output:
$ printexec echo -e "foo\n" bar
$ echo -e foo\\n bar
foon bar
foon bar
foo
bar
bash: echo -e foo\n bar: command not found
As you can see, only the third one, "$@"
gave the correct result.
In brief words:
If you need better sorting order - use utf8_unicode_ci
(this is the preferred method),
but if you utterly interested in performance - use utf8_general_ci
, but know that it is a little outdated.
The differences in terms of performance are very slight.
try
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
[CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [smalldatetime] NOT NULL
)
PS I think a smalldatetime is good enough. You may decide differently.
Can you not do this at the "moment of impact" ?
In Sql Server, this is common:
Update dbo.MyTable
Set
ColA = @SomeValue ,
UpdateDS = CURRENT_TIMESTAMP
Where...........
Sql Server has a "timestamp" datatype.
But it may not be what you think.
Here is a reference:
http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx
Here is a little RowVersion (synonym for timestamp) example:
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Maybe a complete working example:
DROP TABLE [dbo].[Names]
GO
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
GO
CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS
BEGIN
Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where
triggerInsertedTable.Name = myAlias.Name
END
GO
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Matching on the "Name" value is probably not wise.
Try this more mainstream example with a SurrogateKey
DROP TABLE [dbo].[Names]
GO
CREATE TABLE [dbo].[Names]
(
SurrogateKey int not null Primary Key Identity (1001,1),
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
GO
CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS
BEGIN
UPDATE dbo.Names
SET UpdateTS = CURRENT_TIMESTAMP
From dbo.Names myAlias
WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)
END
GO
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
The workaround is
(this will remove all the new lines and there should be whole one line)
now perform your replacements
search and replace thisismynewlineword to \r\n
(to undo the step 1)
ALTER TABLE TABLE_NAME MODIFY (COLUMN_NAME DROP IDENTITY);
String.prototype.TrimStart = function (n) {
if (this.charAt(0) == n)
return this.substr(1);
};
String.prototype.TrimEnd = function (n) {
if (this.slice(-1) == n)
return this.slice(0, -1);
};
If you have the code to log_out()
, rewrite it. Most likely, you can do:
static FILE *logfp = ...;
void log_out(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(logfp, fmt, args);
va_end(args);
}
If there is extra logging information needed, that can be printed before or after the message shown. This saves memory allocation and dubious buffer sizes and so on and so forth. You probably need to initialize logfp
to zero (null pointer) and check whether it is null and open the log file as appropriate - but the code in the existing log_out()
should be dealing with that anyway.
The advantage to this solution is that you can simply call it as if it was a variant of printf()
; indeed, it is a minor variant on printf()
.
If you don't have the code to log_out()
, consider whether you can replace it with a variant such as the one outlined above. Whether you can use the same name will depend on your application framework and the ultimate source of the current log_out()
function. If it is in the same object file as another indispensable function, you would have to use a new name. If you cannot work out how to replicate it exactly, you will have to use some variant like those given in other answers that allocates an appropriate amount of memory.
void log_out_wrapper(const char *fmt, ...)
{
va_list args;
size_t len;
char *space;
va_start(args, fmt);
len = vsnprintf(0, 0, fmt, args);
va_end(args);
if ((space = malloc(len + 1)) != 0)
{
va_start(args, fmt);
vsnprintf(space, len+1, fmt, args);
va_end(args);
log_out(space);
free(space);
}
/* else - what to do if memory allocation fails? */
}
Obviously, you now call the log_out_wrapper()
instead of log_out()
- but the memory allocation and so on is done once. I reserve the right to be over-allocating space by one unnecessary byte - I've not double-checked whether the length returned by vsnprintf()
includes the terminating null or not.
Nothing worked for me except running a subprocess with this command, before calling HTTPServer(('', 443), myHandler)
:
kill -9 $(lsof -ti tcp:443)
Of course this is only for linux-like OS!
The pretty way is printf '\33c\e[3J'
There are two commands which will work in this situation,
root>git reset --hard HEAD~1
root>git push -f
For more git commands refer this page
Refreshing attribute on events is a better approach than scanning value every tenth of a second...
http://jsfiddle.net/yqdcsqzz/3/
inputElement.onchange = function()
{
this.setAttribute('value', this.value);
};
inputElement.onkeyup = function()
{
this.setAttribute('value', this.value);
};
Demo : http://jsfiddle.net/NbGBj/
$("document").ready(function(){
$("#upload").change(function() {
alert('changed!');
});
});
Create a folder org/tij/exercises and then move HelloWorld.java file. Then run below command
javac -cp . org/tij/exercises/HelloWorld.java
AND
java -cp . org/tij/exercises/HelloWorld
before you run in cmd prompt, make sure "appsettings.json" has same values as "appsettings.Development.json".
In command prompt, go all the way to bin/debug/netcoreapp2.0 folder. then run "dotnet applicationname.dll"
For the benefit of searchers; if you are using jQuery, you can do the following:
var currentOverride = $('#customoverridestyles');
if (currentOverride) {
currentOverride.remove();
}
$('body').append("<style id=\"customoverridestyles\">body{background-color:pink;}</style>");
Obviously you can change the inner css to whatever you want.
Appreciate some people prefer pure JavaScript, but it works and has been pretty robust for writing/overwriting styles dynamically.
break
breaks out of a loop, not an if
statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like
for item in some_iterable:
...
if break_condition():
break
The break
would be pretty useless if it terminated the if
block rather than terminated the loop -- terminating a loop conditionally is the exact thing break
is used for.
So I used the overflowing jquery library: https://github.com/kevinmarx/overflowing
After installing the library, if you want to assign the class overflowing
to all overflowing elements, you simply run:
$('.targetElement').overflowing('.parentElement')
This will then give the class overflowing
, as in <div class="targetElement overflowing">
to all elements that are overflowing. You could then add this to some event handler(click, mouseover) or other function that will run the above code so that it updates dynamically.
You can do all of it in awk
:
<file awk '$1 ~ /A1/ {m=$NF} END {print m}'
You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.
Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM
customers
GROUP BY
LastName,
FirstName
This works because the formula you use (the CASE statement) can never give the same answer for two different inputs.
This is not the case if you used something like:
LEFT(FirstName, 1) + ' ' + LastName
In such a case "James Taylor" and "John Taylor" would both result in "J Taylor".
If you wanted your output to have "J Taylor" twice (one for each person):
GROUP BY LastName, FirstName
If, however, you wanted just one row of "J Taylor" you'd want:
GROUP BY LastName, LEFT(FirstName, 1)
Because the Method2
is static, all you have to do is call like this:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
If they are in different namespaces you will also need to add the namespace of AllMethods
to caller.cs in a using
statement.
If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Update
As of C# 6, you can now also achieve this with using static
directive to call static methods somewhat more gracefully, for example:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
Further Reading
Use the defaults parameter.
>>> from collections import namedtuple
>>> fields = ('val', 'left', 'right')
>>> Node = namedtuple('Node', fields, defaults=(None,) * len(fields))
>>> Node()
Node(val=None, left=None, right=None)
Or better yet, use the new dataclasses library, which is much nicer than namedtuple.
>>> from dataclasses import dataclass
>>> from typing import Any
>>> @dataclass
... class Node:
... val: Any = None
... left: 'Node' = None
... right: 'Node' = None
>>> Node()
Node(val=None, left=None, right=None)
Set Node.__new__.__defaults__
to the default values.
>>> from collections import namedtuple
>>> Node = namedtuple('Node', 'val left right')
>>> Node.__new__.__defaults__ = (None,) * len(Node._fields)
>>> Node()
Node(val=None, left=None, right=None)
Set Node.__new__.func_defaults
to the default values.
>>> from collections import namedtuple
>>> Node = namedtuple('Node', 'val left right')
>>> Node.__new__.func_defaults = (None,) * len(Node._fields)
>>> Node()
Node(val=None, left=None, right=None)
In all versions of Python, if you set fewer default values than exist in the namedtuple, the defaults are applied to the rightmost parameters. This allows you to keep some arguments as required arguments.
>>> Node.__new__.__defaults__ = (1,2)
>>> Node()
Traceback (most recent call last):
...
TypeError: __new__() missing 1 required positional argument: 'val'
>>> Node(3)
Node(val=3, left=1, right=2)
Here's a wrapper for you, which even lets you (optionally) set the default values to something other than None
. This does not support required arguments.
import collections
def namedtuple_with_defaults(typename, field_names, default_values=()):
T = collections.namedtuple(typename, field_names)
T.__new__.__defaults__ = (None,) * len(T._fields)
if isinstance(default_values, collections.Mapping):
prototype = T(**default_values)
else:
prototype = T(*default_values)
T.__new__.__defaults__ = tuple(prototype)
return T
Example:
>>> Node = namedtuple_with_defaults('Node', 'val left right')
>>> Node()
Node(val=None, left=None, right=None)
>>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
>>> Node()
Node(val=1, left=2, right=3)
>>> Node = namedtuple_with_defaults('Node', 'val left right', {'right':7})
>>> Node()
Node(val=None, left=None, right=7)
>>> Node(4)
Node(val=4, left=None, right=7)
There is a jQuery plugin for this exact purpose: https://github.com/dubbs/equal-height
If you want to make all columns the same height, use:
$('.columns').equalHeight();
If you want to group them by their top position, eg. within each container:
$('.columns').equalHeight({ groupByTop: true });
"Upstream" would refer to the main repo that other people will be pulling from, e.g. your GitHub repo. The -u option automatically sets that upstream for you, linking your repo to a central one. That way, in the future, Git "knows" where you want to push to and where you want to pull from, so you can use git pull
or git push
without arguments. A little bit down, this article explains and demonstrates this concept.
I would just use this small extension to Date
- http://blog.stevenlevithan.com/archives/date-time-format
var date = new Date(msSinceEpoch);
date.format("isoDateTime"); // 2007-06-09T17:46:21
apt -y -qq install python3 python3-pip
ln -s /usr/bin/python3 /usr/bin/python
ln -s /usr/bin/pip3 /usr/bin/pip
try to empty your innerHtml everytime. just like this:
Element.innerHtml="";
_x000D_
var jsObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];
to access the third object, use: jsObjects[2];
to access the third object b value, use: jsObjects[2].b;
This worked for me:
h1 {
display: inline;
overflow: hidden;
}
div {
position: relative;
float: right;
}
It's similar to the approach of the media object, by Stubbornella.
Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)
In NuGet 3.x (Visual Studio 2015) you can just select the version from the UI
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
easy one
("^ (?=.* [0-9]) (?=.* [a-z]) (?=.* [A-Z]) (?=.* [\\W_])[\\S]{8,10}$")
(?= anything ) ->means positive looks forward in all input string and make sure for this condition is written .sample(?=.*[0-9])-> means ensure one digit number is written in the all string.if not written return false .
(?! anything ) ->(vise versa) means negative looks forward if condition is written return false.
close meaning ^(condition)(condition)(condition)(condition)[\S]{8,10}$
my recipe:
datatable declaration:
defaultContent: "<button type='button'....
events:
$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }
Since 0.11 hive has a NVL function
nvl(T value, T default_value)
which says Returns default value if value is null else returns value
Don't set error_log
to where your syslog
stuff goes, eg /var/log/apache2
, because they errors will get intercepted by ErrorLog
. Instead, create a subdir
in your project folder for logs and do php_value
error_log "/path/to/project/logs"
. This goes for both .htaccess
files and vhosts. Also make sure you put php_flag
log_errors
on
In addition to @ImportanceOfBeingErnest's post, I use the following line to add a legend at an absolute position in a plot.
plt.legend(bbox_to_anchor=(1.0,1.0),\
bbox_transform=plt.gcf().transFigure)
For unknown reasons, bbox_transform=fig.transFigure
does not work with me.
Small performance test comparision for three solutions:
$(".link").prop('href',"https://example.com")
$(".link").attr('href',"https://example.com")
document.querySelector(".link").href="https://example.com";
Here you can perform test by yourself https://jsperf.com/a-href-js-change
We can read href values in following ways
let href = $(selector).prop('href');
let href = $(selector).attr('href');
let href = document.querySelector(".link").href;
Here you can perform test by yourself https://jsperf.com/a-href-js-read
In Swift 3, please try out below:
let stringURL = "YOUR URL TO BE ENCODE";
let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(encodedURLString)
Since, stringByAddingPercentEscapesUsingEncoding
encodes non URL characters but leaves the reserved characters (like !*'();:@&=+$,/?%#[]
), You can encode the url like the following code:
let stringURL = "YOUR URL TO BE ENCODE";
let characterSetTobeAllowed = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)
if let encodedURLString = stringURL.addingPercentEncoding(withAllowedCharacters: characterSetTobeAllowed) {
print(encodedURLString)
}
Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().
Spread syntax for object literals was introduced in ECMAScript 2018):
const a = { "one": 1, "two": 2 };
const b = { "three": 3 };
const c = { "four": 4, "five": 5 };
const result = {...a, ...b, ...c};
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }
Spread (...) operator is supported in many modern browsers but not all of them.
So, it is recommend to use a transpiler like Babel to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
This is the equivalent code Babel will generate for you:
"use strict";
var _extends = Object.assign || function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var a = { "one": 1, "two": 2 };
var b = { "three": 3 };
var c = { "four": 4, "five": 5 };
var result = _extends({}, a, b, c);
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }
in function component, this works great - a new React user since 2020 :)
handleRemove = (e, id) => {
//removeById(id);
}
return(<button onClick={(e)=> handleRemove(e, id)}></button> )
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
Use Controls
object
For i = 1 To X
Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode
has most of the functions that you would typically associate with array nodes from other API's. As such, you do not need to cast to an ArrayNode
to use. Here's an example:
JSON:
{
"objects" : ["One", "Two", "Three"]
}
Code:
final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
for (final JsonNode objNode : arrNode) {
System.out.println(objNode);
}
}
Output:
"One"
"Two"
"Three"
Note the use of isArray
to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your datas structure, but its available should you need it (and this is no different from most other JSON libraries).
Common reasons for the error:
=
) instead of equality (==
/===
)foo() = 42
instead of passing arguments (foo(42)
) getFoo() = 42
instead of getFoo().theAnswer = 42
or array indexing getArray() = 42
instead of getArray()[0]= 42
In this particular case you want to use ==
(or better ===
- What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock")
, but it the actual reason you are getting the error is trickier.
The reason for the error is Operator precedence. In particular we are looking for &&
(precedence 6) and =
(precedence 3).
Let's put braces in the expression according to priority - &&
is higher than =
so it is executed first similar how one would do 3+4*5+6
as 3+(4*5)+6
:
if(one= ("rock" && two) = "rock"){...
Now we have expression similar to multiple assignments like a = b = 42
which due to right-to-left associativity executed as a = (b = 42)
. So adding more braces:
if(one= ( ("rock" && two) = "rock" ) ){...
Finally we arrived to actual problem: ("rock" && two)
can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two
as truthy).
Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do &&
on two strings "rock" && "rock"
resulting in "rock"
(which in turn is truthy) all the time due to behavior of logial &&:
if((one = "rock") && (two = "rock"))
{
// always executed, both one and two are set to "rock"
...
}
For even more details on the error and other cases when it can happen - see specification:
LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true
and The Reference Specification Type explaining IsStrictReference:
... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...
You can use -b to specify a cookie file to read the cookies from as well.
In many situations using -c and -b to the same file is what you want:
curl -b cookies.txt -c cookies.txt http://example.com
Further
Using only -c will make curl start with no cookies but still parse and understand cookies and if redirects or multiple URLs are used, it will then use the received cookies within the single invoke before it writes them all to the output file in the end.
The -b option feeds a set of initial cookies into curl so that it knows about them at start, and it activates curl's cookie parser so that it'll parse and use incoming cookies as well.
See Also
The cookies chapter in the Everything curl book.
The best way to do, I think, is to handle it like the MSDN said on http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx
But handle it, how you really need it. My way (in the example below) is to catch every KeyDown ;-)
/// <summary>
/// onPreviewKeyDown
/// </summary>
/// <param name="e"></param>
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
e.IsInputKey = true;
}
/// <summary>
/// onKeyDown
/// </summary>
/// <param name="e"></param>
protected override void OnKeyDown(KeyEventArgs e)
{
Input.SetFlag(e.KeyCode);
e.Handled = true;
}
/// <summary>
/// onKeyUp
/// </summary>
/// <param name="e"></param>
protected override void OnKeyUp(KeyEventArgs e)
{
Input.RemoveFlag(e.KeyCode);
e.Handled = true;
}
For Notepad++ 64-bit:
There is an unreleased 64-bit version of this plugin. You can download the DLL from here, drop it under Notepad++/plugins/NppTextFX directory and restart Notepad++. You will need to create the NppTextFX directory first though.
As per this GitHub issue, there might be some bugs lurking around. If you run into any, feel free to raise a GitHub ticket for each, as the author (HQJaTu) is recommending. As per the author, the code behind this binary is found on this branch.
Tested on Notepad++ v7.5.8 (64-bit, Build time: Jul 23 2018)
Read this if you are populating your mat-select asyncronously via an http request.
If you are using a service to make an api call to return the mat-select options values, you must set the 'selected value' on your form control as part of the 'complete' section of your service api call subscribe().
For example:
this.customerService.getCustomers().subscribe(
customers => this.customers = customers ,
error => this.errorMessage = error as any,
() => this.customerSelectControl.setValue(this.mySelectedValue));
HTML CODE
<div id="borderLoader" data-height="230px" data-color="lightgrey" data-
width="230px" data-image="https://fiverr- res.cloudinary.com/t_profile_thumb,q_auto,f_auto/attachments/profile/photo/a54f24b2ab6f377ea269863cbf556c12-619447411516923848661/913d6cc9-3d3c-4884-ac6e-4c2d58ee4d6a.jpg">
</div>
JS CODE
var dataValue, dataSet,key;
dataValue = document.getElementById('borderLoader');
//data set contains all the dataset that you are to style the shape;
dataSet ={
"height":dataValue.dataset.height,
"width":dataValue.dataset.width,
"color":dataValue.dataset.color,
"imageBg":dataValue.dataset.image
};
dataValue.style.height = dataSet.height;
dataValue.style.width = dataSet.width;
dataValue.style.background = "#f3f3f3 url("+dataSet.imageBg+") no-repeat
center";
Please refer following code may help you.
public static Method method[];
public static MethodClass obj;
public static String testMethod="A";
public static void main(String args[])
{
obj=new MethodClass();
method=obj.getClass().getMethods();
try
{
for(int i=0;i<method.length;i++)
{
String name=method[i].getName();
if(name==testMethod)
{
method[i].invoke(name,"Test Parameters of A");
}
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
Thanks....
If you hit git stash
when you have changes in the working copy (not in the staging area), git will create a stashed object and pushes onto the stack of stashes (just like you did git checkout -- .
but you won't lose changes). Later, you can pop from the top of the stack.
I was experiencing this error and in my case the cause was that some time ago I modified the user password, and the 503 error didn't appears till I restarted the application pool.
So I fixed it setting the new password on Applications Pools / Advanced Settings / Identity / [...] / Set... / Password / Confirm Password
The sort
command prints the result of the sorting operation to standard output by default. In order to achieve an "in-place" sort, you can do this:
sort -o file file
This overwrites the input file
with the sorted output. The -o
switch, used to specify an output, is defined by POSIX, so should be available on all version of sort
:
-o Specify the name of an output file to be used instead of the standard output. This file can be the same as one of the input files.
If you are unfortunate enough to have a version of sort
without the -o
switch (Luis assures me that they exist), you can achieve an "in-place" edit in the standard way:
sort file > tmp && mv tmp file
<input type="checkbox" checked="checked" onclick="this.checked=true" />
I started from the problem: "how to POST/Submit an Input Checkbox that is disabled?" and in my answer I skipped the comment: "If we want to disable a checkbox we surely need to keep a prefixed value (checked or unchecked) and also we want that the user be aware of it (otherwise we should use a hidden type and not a checkbox)". In my answer I supposed that we want to keep always a checkbox checked and that code works in this way. If we click on that ckeckbox it will be forever checked and its value will be POSTED/Submitted! In the same way if I write onclick="this.checked=false" without checked="checked" (note: default is unchecked) it will be forever unchecked and its value will be not POSTED/Submitted!.
@FunctionalInterface
is a new annotation are released with Java 8 and provide target types for lambda expressions and it used on compilation time checking of your code.
When you want to use it :
1- Your interface must not have more than one abstract methods, otherwise compilation error will be given.
1- Your interface Should be pure, which means functional interface is intended to be implemented by stateless classes, exmple of pure is Comparator
interface because its not depend on the implementers state, in this case No compilation error will be given, but in many cases you will not be able to use lambda with this kind of interfaces
The java.util.function
package contains various general purpose functional interfaces such as Predicate
, Consumer
, Function
, and Supplier
.
Also please note that you can use lambdas without this annotation.
The prototype-solution from Krishna Chytanya is very nice, but needs a minor but important improvement. The days param must be parsed as Integer to avoid weird calculations when days is a String like "1". (I needed several hours to find out, what went wrong in my application.)
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + parseInt(days));
return this;
};
Even if you do not use this prototype function: Always be sure to have an Integer when using setDate().
How do threads
work? What is synchronized
? If there are two synchronized
methods in a class can they be simultaneously executed by two threads. You will be surprised to hear many people answer yes. Then all thread related question, e.g. deadlock, starvation etc.
A class is an element in object oriented programming that aggregates attributes(fields) - which can be public accessible or not - and methods(functions) - which also can be public or private and usually writes/reads those attributes.
so you can have a class like Array
with a public attribute length
and a public method sort()
.
Let's say you have the following enum
public enum Numbers {Zero = 0, One, Two};
You need to have a struct to map those values to a string:
public struct EntityName
{
public Numbers _num;
public string _caption;
public EntityName(Numbers type, string caption)
{
_num = type;
_caption = caption;
}
public Numbers GetNumber()
{
return _num;
}
public override string ToString()
{
return _caption;
}
}
Now return an array of objects with all the enums mapped to a string:
public object[] GetNumberNameRange()
{
return new object[]
{
new EntityName(Number.Zero, "Zero is chosen"),
new EntityName(Number.One, "One is chosen"),
new EntityName(Number.Two, "Two is chosen")
};
}
And use the following to populate your combo box:
ComboBox numberCB = new ComboBox();
numberCB.Items.AddRange(GetNumberNameRange());
Create a function to retrieve the enum type just in case you want to pass it to a function
public Numbers GetConversionType()
{
EntityName type = (EntityName)numberComboBox.SelectedItem;
return type.GetNumber();
}
and then you should be ok :)
Got stupid error. So post here, if anyone find it useful
[-\._]
- means hyphen, dot and underscore[\.-_]
- means all signs in range from dot to underscore<?php
$file = fopen("members.txt", "r");
$members = array();
while (!feof($file)) {
$members[] = fgets($file);
}
fclose($file);
var_dump($members);
?>
It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>")
and the title was <a href=".." title="Test" <br> <p>">Testing</a>
.
It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>")
and it worked in every browser.
@Giuseppe, you may want to consider this for a flexible specification of the plots arrangement (modified from here):
library(ggplot2)
library(gridExtra)
library(grid)
grid_arrange_shared_legend <- function(..., nrow = 1, ncol = length(list(...)), position = c("bottom", "right")) {
plots <- list(...)
position <- match.arg(position)
g <- ggplotGrob(plots[[1]] + theme(legend.position = position))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
gl <- lapply(plots, function(x) x + theme(legend.position = "none"))
gl <- c(gl, nrow = nrow, ncol = ncol)
combined <- switch(position,
"bottom" = arrangeGrob(do.call(arrangeGrob, gl),
legend,
ncol = 1,
heights = unit.c(unit(1, "npc") - lheight, lheight)),
"right" = arrangeGrob(do.call(arrangeGrob, gl),
legend,
ncol = 2,
widths = unit.c(unit(1, "npc") - lwidth, lwidth)))
grid.newpage()
grid.draw(combined)
}
Extra arguments nrow
and ncol
control the layout of the arranged plots:
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data = dsamp, colour = clarity)
p2 <- qplot(cut, price, data = dsamp, colour = clarity)
p3 <- qplot(color, price, data = dsamp, colour = clarity)
p4 <- qplot(depth, price, data = dsamp, colour = clarity)
grid_arrange_shared_legend(p1, p2, p3, p4, nrow = 1, ncol = 4)
grid_arrange_shared_legend(p1, p2, p3, p4, nrow = 2, ncol = 2)
Ultimately, .keystore
and .jks
are just file extensions: it's up to you to name your files sensibly. Some application use a keystore file stored in $HOME/.keystore
: it's usually implied that it's a JKS file, since JKS is the default keystore type in the Sun/Oracle Java security provider. Not everyone uses the .jks
extension for JKS files, because it's implied as the default. I'd recommend using the extension, just to remember which type to specify (if you need).
In Java, the word keystore can have either of the following meanings, depending on the context:
When talking about the file and storage, this is not really a storage facility for key/value pairs (there are plenty or other formats for this). Rather, it's a container to store cryptographic keys and certificates (I believe some of them can also store passwords). Generally, these files are encrypted and password-protected so as not to let this data available to unauthorized parties.
Java uses its KeyStore
class and related API to make use of a keystore (whether it's file based or not). JKS
is a Java-specific file format, but the API can also be used with other file types, typically PKCS#12. When you want to load a keystore, you must specify its keystore type. The conventional extensions would be:
.jks
for type "JKS"
,.p12
or .pfx
for type "PKCS12"
(the specification name is PKCS#12, but the #
is not used in the Java keystore type name).In addition, BouncyCastle also provides its implementations, in particular BKS (typically using the .bks
extension), which is frequently used for Android applications.
If you want to know the list of procedures you can run the following command -
show procedure status;
It will give you the list of procedures and their definers
Then you can run the show create procedure <procedurename>;
You have four options
Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.
Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.
Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy
syntax then Theano might be a good choice.
Here is an example using SymPy
In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2·x
In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2. 2. 2. 2. 2.]
I would probably choose Git because I feel it's much more powerful than SVN. There are cheap Code Hosting services available which work just great for me - you don't have to do backups or any maintenance work - GitHub is the most obvious candidate.
That said, I don't know anything regarding the integration of Visual Studio and the different SCM systems. I imagine the integration with SVN to notably better.
Let's say we have an external table called employee
hive> SHOW CREATE TABLE employee;
OK
CREATE EXTERNAL TABLE employee(
id string,
fname string,
lname string,
salary double)
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
WITH SERDEPROPERTIES (
'colelction.delim'=':',
'field.delim'=',',
'line.delim'='\n',
'serialization.format'=',')
STORED AS INPUTFORMAT
'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
'maprfs:/user/hadoop/data/employee'
TBLPROPERTIES (
'COLUMN_STATS_ACCURATE'='false',
'numFiles'='0',
'numRows'='-1',
'rawDataSize'='-1',
'totalSize'='0',
'transient_lastDdlTime'='1487884795')
To create a person
table like employee
CREATE TABLE person LIKE employee;
To create a person
external table like employee
CREATE TABLE person LIKE employee LOCATION 'maprfs:/user/hadoop/data/person';
then use
DESC person;
to see the newly created table schema.
It should be Ctrl + J.
You can set TextBox properties for setting negative number display and decimal places settings.
the format for the image you have chosen must be 16x16 pixels or 32x32 pixels, using either 8-bit or 24-bit colors. The format of the image must be one of PNG (a W3C standard), GIF, or ICO. - How to Add a Favicon to your Site - QA @ W3C
Tested and Working procedure:
Goto the file path
..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp
remove the whole content or declare the below lines of code at the top of the index.jsp
<% response.sendRedirect("http://yourRedirectionURL"); %>
Please note that in jsp file you need to start the above line with <% and end with %>
Simplest way! (To Display In Your Main Activity, replace First Argument for other activity)
Button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Toast.makeText(MainActivity.this,"Toast Message",Toast.LENGTH_SHORT).show();
}
}
BTW: the .htaccess config must be done on the server hosting the API. For example you create an AngularJS app on x.com domain and create a Rest API on y.com, you should set Access-Control-Allow-Origin "*" in the .htaccess file on the root folder of y.com not x.com :)
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
Also as Lukas mentioned make sure you have enabled mod_headers if you use Apache
Tomcat will only extract the war which is copied to webapps
directory.
Change Dockerfile
as below:
FROM tomcat:8.0.20-jre8
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war
You might need to access the url as below unless you have specified the webroot
Alternatively, if you use position: absolute
then height: 100%
will work just fine.
you shouldn't include c-files in other c-files. Instead create a header file where the function is declared that you want to call. Like so: file ClasseAusiliaria.h:
int addizione(int a, int b); // this tells the compiler that there is a function defined and the linker will sort the right adress to call out.
In your Main.c file you can then include the newly created header file:
#include <stdlib.h>
#include <stdio.h>
#include <ClasseAusiliaria.h>
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
Random ran = new Random();
int top = 3;
char data = ' ';
String dat = "";
for (int i=0; i<=top; i++) {
data = (char)(ran.nextInt(25)+97);
dat = data + dat;
}
System.out.println(dat);
@Configuration
@ConfigurationProperties(prefix = "params.datasource")
public class JpaConfig extends HikariConfig {
@Bean
public DataSource dataSource() throws SQLException {
return new HikariDataSource(this);
}
}
application.yml
params:
datasource:
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://localhost:3306/myDb
username: login
password: password
maximumPoolSize: 5
UPDATED! Since version Spring Boot 1.3.0 :
application.yml
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:h2:mem:TEST
driver-class-name: org.h2.Driver
username: username
password: password
hikari:
idle-timeout: 10000
UPDATED! Since version Spring Boot 2.0.0 :
The default connection pool has changed from Tomcat to Hikari :)
There is maybe a solution (but i didnt test it) : you could use CSP (Content Security Policy) to enable your remote domain and browsers will maybe skip the CORS OPTIONS request verification.
I if find some time, I will test that and update this post !
CSP : https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Content-Security-Policy
CSP Specification : https://www.w3.org/TR/CSP/
now apple support that
overflow:hidden;
-webkit-overflow-scrolling:touch;
That is illegal syntax. It is not an optional thing for you to return a variable. You MUST return a variable of the type you specify in your method.
public String myMethod()
{
if(condition)
{
return x;
}
}
You are effectively saying, I promise any class can use this method(public) and I promise it will always return a String(String).
Then you are saying IF my condition is true I will return x. Well that is too bad, there is no IF in your promise. You promised that myMethod will ALWAYS return a String. Even if your condition is ALWAYS true the compiler has to assume that there is a possibility of it being false. Therefore you always need to put a return at the end of your non-void method outside of any conditions JUST IN CASE all of your conditions fail.
public String myMethod()
{
if(condition)
{
return x;
}
return ""; //or whatever the default behavior will be if all of your conditions fail to return.
}
Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.
ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.
The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).
A better option
Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE
). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses
(and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.
For the recent version of MySQL,
default-character-set = utf8
causes a problem. It's deprecated I think.
As Justin Ball says in "Upgrade to MySQL 5.5.12 and now MySQL won’t start, you should:
Remove that directive and you should be good.
Then your configuration file ('/etc/my.cnf' for example) should look like that:
[mysqld]
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
Restart MySQL.
For making sure, your MySQL is UTF-8, run the following queries in your MySQL prompt:
First query:
mysql> show variables like 'char%';
The output should look like:
+--------------------------+---------------------------------+
| Variable_name | Value |
+--------------------------+---------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/local/mysql/share/charsets/|
+--------------------------+---------------------------------+
Second query:
mysql> show variables like 'collation%';
And the query output is:
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
The shorter ES6 version of the answer:
const delay = t => new Promise(resolve => setTimeout(resolve, t));
And then you can do:
delay(3000).then(() => console.log('Hello'));
Another option is :
View > Quick Switch Scheme > Keymap > Eclipse
You can create a "fake" delay between infinite animations purely with CSS. The way to do it is smartly define your keyframe animation points and your animation duration speed.
For example, if we wanted to animate a bouncing ball, and we wanted a good .5s to 1s delay between each bounce, we can do something like:
@keyframes bounce{
0%{
transform: translateY(0);
}
50%{
transform: translateY(25%);
}
75%{
transform: translateY(15%);
}
90%{
transform: translateY(0%);
}
100%{
transform: translateY(0);
}
}
What we do is make sure that the ball goes back to its original position much earlier than 100%. In my example, I'm doing it in 90% which provided me with around .1s delay which was good enough for me. But obviously for your case, you can either add more key frame points and change the transform values.
Furthermore, you can add additional animation duration to balance your key frame animations.
For example:
animation: bounce .5s ease-in-out infinite;
Lets say that we wanted the full animation to end in .5s, but we wanted an additional .2s in delay between the animations.
animation: bounce .7s ease-in-out infinite;
So we'll add an additional .2s delay, and in our key frame animations, we can add more percentage points to fill in the gaps of the .2s delay.
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
There is how to get count of all responsibilities for selected Id. Just change @dbTableName value, @dbRowId value and its type (if int you need to remove '' in line no 82 (..SET @SQL = ..)). Enjoy.
DECLARE @dbTableName varchar(max) = 'User'
DECLARE @dbRowId uniqueidentifier = '21d34ecd-c1fd-11e2-8545-002219a42e1c'
DECLARE @FK_ROWCOUNT int
DECLARE @SQL nvarchar(max)
DECLARE @PKTABLE_QUALIFIER sysname
DECLARE @PKTABLE_OWNER sysname
DECLARE @PKTABLE_NAME sysname
DECLARE @PKCOLUMN_NAME sysname
DECLARE @FKTABLE_QUALIFIER sysname
DECLARE @FKTABLE_OWNER sysname
DECLARE @FKTABLE_NAME sysname
DECLARE @FKCOLUMN_NAME sysname
DECLARE @UPDATE_RULE smallint
DECLARE @DELETE_RULE smallint
DECLARE @FK_NAME sysname
DECLARE @PK_NAME sysname
DECLARE @DEFERRABILITY sysname
IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL
DROP TABLE #Temp1;
CREATE TABLE #Temp1 (
PKTABLE_QUALIFIER sysname,
PKTABLE_OWNER sysname,
PKTABLE_NAME sysname,
PKCOLUMN_NAME sysname,
FKTABLE_QUALIFIER sysname,
FKTABLE_OWNER sysname,
FKTABLE_NAME sysname,
FKCOLUMN_NAME sysname,
UPDATE_RULE smallint,
DELETE_RULE smallint,
FK_NAME sysname,
PK_NAME sysname,
DEFERRABILITY sysname,
FK_ROWCOUNT int
);
DECLARE FK_Counter_Cursor CURSOR FOR
SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.SCHEMA_ID)),
PKTABLE_NAME = CONVERT(SYSNAME,O1.NAME),
PKCOLUMN_NAME = CONVERT(SYSNAME,C1.NAME),
FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.SCHEMA_ID)),
FKTABLE_NAME = CONVERT(SYSNAME,O2.NAME),
FKCOLUMN_NAME = CONVERT(SYSNAME,C2.NAME),
-- Force the column to be non-nullable (see SQL BU 325751)
--KEY_SEQ = isnull(convert(smallint,k.constraint_column_id), sysconv(smallint,0)),
UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsUpdateCascade')
WHEN 1 THEN 0
ELSE 1
END),
DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsDeleteCascade')
WHEN 1 THEN 0
ELSE 1
END),
FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.OBJECT_ID)),
PK_NAME = CONVERT(SYSNAME,I.NAME),
DEFERRABILITY = CONVERT(SMALLINT,7) -- SQL_NOT_DEFERRABLE
FROM SYS.ALL_OBJECTS O1,
SYS.ALL_OBJECTS O2,
SYS.ALL_COLUMNS C1,
SYS.ALL_COLUMNS C2,
SYS.FOREIGN_KEYS F
INNER JOIN SYS.FOREIGN_KEY_COLUMNS K
ON (K.CONSTRAINT_OBJECT_ID = F.OBJECT_ID)
INNER JOIN SYS.INDEXES I
ON (F.REFERENCED_OBJECT_ID = I.OBJECT_ID
AND F.KEY_INDEX_ID = I.INDEX_ID)
WHERE O1.OBJECT_ID = F.REFERENCED_OBJECT_ID
AND O2.OBJECT_ID = F.PARENT_OBJECT_ID
AND C1.OBJECT_ID = F.REFERENCED_OBJECT_ID
AND C2.OBJECT_ID = F.PARENT_OBJECT_ID
AND C1.COLUMN_ID = K.REFERENCED_COLUMN_ID
AND C2.COLUMN_ID = K.PARENT_COLUMN_ID
AND O1.NAME = @dbTableName
OPEN FK_Counter_Cursor;
FETCH NEXT FROM FK_Counter_Cursor INTO @PKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'SELECT @dbCountOut = COUNT(*) FROM [' + @FKTABLE_NAME + '] WHERE [' + @FKCOLUMN_NAME + '] = ''' + CAST(@dbRowId AS varchar(max)) + '''';
EXECUTE sp_executesql @SQL, N'@dbCountOut int OUTPUT', @dbCountOut = @FK_ROWCOUNT OUTPUT;
INSERT INTO #Temp1 (PKTABLE_QUALIFIER, PKTABLE_OWNER, PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_QUALIFIER, FKTABLE_OWNER, FKTABLE_NAME, FKCOLUMN_NAME, UPDATE_RULE, DELETE_RULE, FK_NAME, PK_NAME, DEFERRABILITY, FK_ROWCOUNT) VALUES (@FKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY, @FK_ROWCOUNT)
FETCH NEXT FROM FK_Counter_Cursor INTO @PKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY;
END;
CLOSE FK_Counter_Cursor;
DEALLOCATE FK_Counter_Cursor;
GO
SELECT * FROM #Temp1
GO
Here are the steps I follow to delete a topic named MyTopic
:
rm -rf /tmp/kafka-logs/MyTopic-0
. Repeat for other partitions, and all replicaszkCli.sh
then rmr /brokers/MyTopic
If you miss you step 3, then Apache Kafka will continue to report the topic as present (for example when if you run kafka-list-topic.sh
).
Tested with Apache Kafka 0.8.0.
You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)
Sounds like one part of the project is being built for x86-only while the rest is being built for any CPU/x64. This bit me, too. Are you running an x64 (or uh... IA64)?
Check the project properties and make sure everything is being built for "Any CPU". f you're in Visual Studio, you can check for everything by going to the "x86" or "Any CPU" menu (next to the "Debug"/"Release" menu) on the toolbar at the top of the screen and clicking "Configuration Manager..."
Create key value pairs on the phpsh commandline like this:
php> $keyvalues = array();
php> $keyvalues['foo'] = "bar";
php> $keyvalues['pyramid'] = "power";
php> print_r($keyvalues);
Array
(
[foo] => bar
[pyramid] => power
)
Get the count of key value pairs:
php> echo count($offerarray);
2
Get the keys as an array:
php> echo implode(array_keys($offerarray));
foopyramid
I don't know if it's possible but I always pictured myself being able to do this with the CSV storage engine in MySQL. I don't know the details of this engine: http://dev.mysql.com/doc/refman/5.7/en/csv-storage-engine.html but you can look into it and have a file watcher in your operating system that triggers a PHP call if the file is modified.
Try this variation:
$(".tr_clone_add").live('click', CloneRow);
function CloneRow()
{
$(this).closest('.tr_clone').clone().insertAfter(".tr_clone:last");
}
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.
As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.
There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).
ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.
At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).
Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.
ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.
Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.
So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.
SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices
Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.
Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload
Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id
(it won't trigger row update even though id
is assigned to itself).
If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE
.
You may try like this:
import java.applet.Applet;
import java.awt.*;
public class Rect1 extends Applet {
public void paint (Graphics g) {
g.drawRect (x, y, width, height); //can use either of the two//
g.fillRect (x, y, width, height);
g.setColor(color);
}
}
where x is x co-ordinate y is y cordinate color=the color you want to use eg Color.blue
if you want to use rectangle object you could do it like this:
import java.applet.Applet;
import java.awt.*;
public class Rect1 extends Applet {
public void paint (Graphics g) {
Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
g.setColor(color);
}
}
You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.
A bit more elaborate version (to use from another window):
#!/bin/bash
DELAY=3
TERM_PID=$(echo `ps -C gnome-terminal -o pid= | head -1`) # get first gnome-terminal's PID
WID=$(wmctrl -lp | awk -v pid=$TERM_PID '$3==pid{print $1;exit;}') # get window id
xdotool windowfocus $WID
xdotool key alt+t # my key map
xdotool sleep $DELAY # it may take a while to start new shell :(
xdotool type --delay 1 --clearmodifiers "$@"
xdotool key Return
wmctrl -i -a $WID # go to that window (WID is numeric)
# vim:ai
# EOF #
The function fromJSON() in RJSONIO, rjson and jsonlite don't return a simple 2D data.frame for complex nested json objects.
To overcome this you can use tidyjson. It takes in a json and always returns a data.frame. It is currently not availble in CRAN, you can get it here: https://github.com/sailthru/tidyjson
Update: tidyjson is now available in cran, you can install it directly using install.packages("tidyjson")
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html
w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).
for widget in frame.winfo_children():
widget.destroy()
Will destroy all the widget in your frame. No need for a second frame.
Every variable or field of a primitive value type or structure type holds a unique instance of that type, including all its fields (public and private). By contrast, variables or fields of reference types may hold null, or may refer to an object, stored elsewhere, to which any number of other references may also exist. The fields of a struct will be stored in the same place as the variable or field of that structure type, which may be either on the stack or may be part of another heap object.
Creating a variable or field of a primitive value type will create it with a default value; creating a variable or field of a structure type will create a new instance, creating all fields therein in the default manner. Creating a new instance of a reference type will start by creating all fields therein in the default manner, and then running optional additional code depending upon the type.
Copying one variable or field of a primitive type to another will copy the value. Copying one variable or field of structure type to another will copy all the fields (public and private) of the former instance to the latter instance. Copying one variable or field of reference type to another will cause the latter to refer to the same instance as the former (if any).
It's important to note that in some languages like C++, the semantic behavior of a type is independent of how it is stored, but that isn't true of .NET. If a type implements mutable value semantics, copying one variable of that type to another copies the properties of the first to another instance, referred to by the second, and using a member of the second to mutate it will cause that second instance to be changed, but not the first. If a type implements mutable reference semantics, copying one variable to another and using a member of the second to mutate the object will affect the object referred to by the first variable; types with immutable semantics do not allow mutation, so it doesn't matter semantically whether copying creates a new instance or creates another reference to the first.
In .NET, it is possible for value types to implement any of the above semantics, provided that all of their fields can do likewise. A reference type, however, can only implement mutable reference semantics or immutable semantics; value types with fields of mutable reference types are limited to either implementing mutable reference semantics or weird hybrid semantics.
There is a small gotcha with readonly. A readonly field can be set multiple times within the constructor(s). Even if the value is set in two different chained constructors it is still allowed.
public class Sample {
private readonly string ro;
public Sample() {
ro = "set";
}
public Sample(string value) : this() {
ro = value; // this works even though it was set in the no-arg ctor
}
}
Following can be used as a common method to return different arguments on different method calls. Only thing we need to do is we need to pass an array with order in which objects should be retrieved in each call.
@SafeVarargs
public static <Mock> Answer<Mock> getAnswerForSubsequentCalls(final Mock... mockArr) {
return new Answer<Mock>() {
private int count=0, size=mockArr.length;
public Mock answer(InvocationOnMock invocation) throws throwable {
Mock mock = null;
for(; count<size && mock==null; count++){
mock = mockArr[count];
}
return mock;
}
}
}
Ex. getAnswerForSubsequentCalls(mock1, mock3, mock2);
will return mock1 object on first call, mock3 object on second call and mock2 object on third call.
Should be used like when(something()).doAnswer(getAnswerForSubsequentCalls(mock1, mock3, mock2));
This is almost similar to when(something()).thenReturn(mock1, mock3, mock2);
Sounds like you're doing this:
0..10.to_a
The warning is from Fixnum#to_a, not from Range#to_a. Try this instead:
(0..10).to_a
I noticed that this error happens when I send an IQueriable to the view and use it in a double foreach, where the inner foreach also needs to use the connection. Simple example (ViewBag.parents can be IQueriable or DbSet):
foreach (var parent in ViewBag.parents)
{
foreach (var child in parent.childs)
{
}
}
The simple solution is to use .ToList()
on the collection before using it. Also note that MARS does not work with MySQL.
Another solution I've just found here How to render a scaled SVG to a QImage?
from PySide.QtSvg import *
from PySide.QtGui import *
def convertSvgToPng(svgFilepath,pngFilepath,width):
r=QSvgRenderer(svgFilepath)
height=r.defaultSize().height()*width/r.defaultSize().width()
i=QImage(width,height,QImage.Format_ARGB32)
p=QPainter(i)
r.render(p)
i.save(pngFilepath)
p.end()
PySide is easily installed from a binary package in Windows (and I use it for other things so is easy for me).
However, I noticed a few problems when converting country flags from Wikimedia, so perhaps not the most robust svg parser/renderer.
My problem was, that Visual Studio somehow automatically lowercased *ngFor
to *ngfor
on copy&paste.
If your developing an app that uses google fonts and want to ensure your users do not see these warnings. A possible solution (detailed here) was to load the fonts locally.
I used this solution for an application which at times has slow internet (or no internet access) but still serves pages, This assumes your app uses Google fonts and updates to these fonts are not critical. Also assume that using ttf fonts are appropriate for your application WC3 TTF Font Browser Support.
Here is how I accomplished locally serving fonts:
You may try
$("#addRunner input").each(function(){ ... });
Inputs are no selectors, so you do not need the :
Haven't tested it with your code. Just a fast guess!
UPDATE `table` SET table_column='test';
I agree it is generally preferable to use an Array
for this.
However, this can also be accomplished in JavaScript by simply adding properties to the current scope (the global scope, if top-level code; the function scope, if within a function) by simply using this
– which always refers to the current scope.
for (var i = 0; i < coords.length; ++i) {
this["marker"+i] = "some stuff";
}
You can later retrieve the stored values (if you are within the same scope as when they were set):
var foo = this.marker0;
console.log(foo); // "some stuff"
This slightly odd feature of JavaScript is rarely used (with good reason), but in certain situations it can be useful.
I don't know about targeting iOS as a whole, but to target iOS Safari specifically:
@supports (-webkit-touch-callout: none) {
/* CSS specific to iOS devices */
}
@supports not (-webkit-touch-callout: none) {
/* CSS for other than iOS devices */
}
Apparently as of iOS 13 -webkit-overflow-scrolling
no longer responds to @supports
, but -webkit-touch-callout
still does. Of course that could change in the future...
Floating-Point Types (Approximate Value) - FLOAT, DOUBLE
The FLOAT and DOUBLE types represent approximate numeric data values. MySQL uses four bytes for single-precision values and eight bytes for double-precision values.
For FLOAT, the SQL standard permits an optional specification of the precision (but not the range of the exponent) in bits following the keyword FLOAT in parentheses. MySQL also supports this optional precision specification, but the precision value is used only to determine storage size. A precision from 0 to 23 results in a 4-byte single-precision FLOAT column. A precision from 24 to 53 results in an 8-byte double-precision DOUBLE column.
MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE PRECISION(M,D). Here, “(M,D)” means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. For example, a column defined as FLOAT(7,4) will look like -999.9999 when displayed. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001.
Because floating-point values are approximate and not stored as exact values, attempts to treat them as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies.
For maximum portability, code requiring storage of approximate numeric data values should use FLOAT or DOUBLE PRECISION with no specification of precision or number of digits.
https://dev.mysql.com/doc/refman/5.5/en/floating-point-types.html
Problems with Floating-Point Values
Floating-point numbers sometimes cause confusion because they are approximate and not stored as exact values. A floating-point value as written in an SQL statement may not be the same as the value represented internally. Attempts to treat floating-point values as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies. The FLOAT and DOUBLE data types are subject to these issues. For DECIMAL columns, MySQL performs operations with a precision of 65 decimal digits, which should solve most common inaccuracy problems.
The following example uses DOUBLE to demonstrate how calculations that are done using floating-point operations are subject to floating-point error.
mysql> CREATE TABLE t1 (i INT, d1 DOUBLE, d2 DOUBLE);
mysql> INSERT INTO t1 VALUES (1, 101.40, 21.40), (1, -80.00, 0.00),
-> (2, 0.00, 0.00), (2, -13.20, 0.00), (2, 59.60, 46.40),
-> (2, 30.40, 30.40), (3, 37.00, 7.40), (3, -29.60, 0.00),
-> (4, 60.00, 15.40), (4, -10.60, 0.00), (4, -34.00, 0.00),
-> (5, 33.00, 0.00), (5, -25.80, 0.00), (5, 0.00, 7.20),
-> (6, 0.00, 0.00), (6, -51.40, 0.00);
mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b
-> FROM t1 GROUP BY i HAVING a <> b;
+------+-------+------+
| i | a | b |
+------+-------+------+
| 1 | 21.4 | 21.4 |
| 2 | 76.8 | 76.8 |
| 3 | 7.4 | 7.4 |
| 4 | 15.4 | 15.4 |
| 5 | 7.2 | 7.2 |
| 6 | -51.4 | 0 |
+------+-------+------+
The result is correct. Although the first five records look like they should not satisfy the comparison (the values of a and b do not appear to be different), they may do so because the difference between the numbers shows up around the tenth decimal or so, depending on factors such as computer architecture or the compiler version or optimization level. For example, different CPUs may evaluate floating-point numbers differently.
If columns d1 and d2 had been defined as DECIMAL rather than DOUBLE, the result of the SELECT query would have contained only one row—the last one shown above.
The correct way to do floating-point number comparison is to first decide on an acceptable tolerance for differences between the numbers and then do the comparison against the tolerance value. For example, if we agree that floating-point numbers should be regarded the same if they are same within a precision of one in ten thousand (0.0001), the comparison should be written to find differences larger than the tolerance value:
mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b FROM t1
-> GROUP BY i HAVING ABS(a - b) > 0.0001;
+------+-------+------+
| i | a | b |
+------+-------+------+
| 6 | -51.4 | 0 |
+------+-------+------+
1 row in set (0.00 sec)
Conversely, to get rows where the numbers are the same, the test should find differences within the tolerance value:
mysql> SELECT i, SUM(d1) AS a, SUM(d2) AS b FROM t1
-> GROUP BY i HAVING ABS(a - b) <= 0.0001;
+------+------+------+
| i | a | b |
+------+------+------+
| 1 | 21.4 | 21.4 |
| 2 | 76.8 | 76.8 |
| 3 | 7.4 | 7.4 |
| 4 | 15.4 | 15.4 |
| 5 | 7.2 | 7.2 |
+------+------+------+
5 rows in set (0.03 sec)
Floating-point values are subject to platform or implementation dependencies. Suppose that you execute the following statements:
CREATE TABLE t1(c1 FLOAT(53,0), c2 FLOAT(53,0));
INSERT INTO t1 VALUES('1e+52','-1e+52');
SELECT * FROM t1;
On some platforms, the SELECT statement returns inf and -inf. On others, it returns 0 and -0.
An implication of the preceding issues is that if you attempt to create a replication slave by dumping table contents with mysqldump on the master and reloading the dump file into the slave, tables containing floating-point columns might differ between the two hosts.
https://dev.mysql.com/doc/refman/5.5/en/problems-with-float.html
If I am the one who faced the interview, I would say that as the end-user perspective abstraction and encapsulation are fairly same. It is nothing but information hiding. As a Software Developer perspective, Abstraction solves the problems at the design level and Encapsulation solves the problem in implementation level
This can also be accomplished with a while loop which checks to see if any documents remain that still have subdocuments that have not been updated. This method preserves the atomicity of your updates (which many of the other solutions here do not).
var query = {
events: {
$elemMatch: {
profile: 10,
handled: { $ne: 0 }
}
}
};
while (db.yourCollection.find(query).count() > 0) {
db.yourCollection.update(
query,
{ $set: { "events.$.handled": 0 } },
{ multi: true }
);
}
The number of times the loop is executed will equal the maximum number of times subdocuments with profile
equal to 10 and handled
not equal to 0 occur in any of the documents in your collection. So if you have 100 documents in your collection and one of them has three subdocuments that match query
and all the other documents have fewer matching subdocuments, the loop will execute three times.
This method avoids the danger of clobbering other data that may be updated by another process while this script executes. It also minimizes the amount of data being transferred between client and server.
List indexes of -x mean the xth item from the end of the list, so n[-1]
means the last item in the list n
. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1]
to access the last item of a list.
Make sure you are not dynamically applying relative constraints to a view which is not yet there in view hierarchy.
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectZero];
[self.view addSubview:bottomView];
bottomConstraint = [NSLayoutConstraint constraintWithItem:bottomView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0];
bottomConstraint.active = YES;
In above example, bottomView has been made part of view hierarchy before applying relative constraints on it.
I was simply trying to Bind IP with IIS but ended up messing with IIS config files I literally tried 20+ solutions for this, which includes
but what worked which may work for someone else as well was to REPAIR
IIS from
Control Panel\Programs\Programs and Features
Else you can refer to this answer as well
this query may help you
SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'tbl_ifo'
This worked for me.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
btnSendSMS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendSMS("5556", "Hi You got a message!");
/*here i can send message to emulator 5556. In Real device
*you can change number*/
}
});
}
//Sends an SMS message to another device
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
You can add this line in AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>
Take a look at this
This may be helpful for you.
According to RFC 4337 § 2, video/mp4
is indeed the correct Content-Type for MPEG-4 video.
Generally, you can find official MIME definitions by searching for the file extension and "IETF" or "RFC". The RFC (Request for Comments) articles published by the IETF (Internet Engineering Taskforce) define many Internet standards, including MIME types.
In the constructor method of your model class set the default value whatever you want. Then in your first action create an instance of the model and pass it to your view.
public ActionResult VolunteersAdd()
{
VolunteerModel model = new VolunteerModel(); //to set the default values
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VolunteersAdd(VolunteerModel model)
{
return View(model);
}
It sounds like you have macro recording turned on. To shut it off, press q
.
Refer to ":help recording" for further information.
Related links:
The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:
For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next
If you do not want the symbols like colon to be inserted put an if condition in the loop.
Make SymbolIndexer( const SymbolIndexer& )
private. If you're assigning to a reference, you're not copying.
Using dplyr
:
require(dplyr)
df <- data.frame(A = c(1, 1, 2, 3, 3), B = c(2, 3, 3, 5, 6))
df %>% group_by(A) %>% summarise(B = sum(B))
## Source: local data frame [3 x 2]
##
## A B
## 1 1 5
## 2 2 3
## 3 3 11
With sqldf
:
library(sqldf)
sqldf('SELECT A, SUM(B) AS B FROM df GROUP BY A')
File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
File curentPath = new File(file.getParent());
//get current path "C:/aaa/bbb/ccc/ddd/"
String currentFolder= currentPath.getName().toString();
//get name of file to string "ddd"
if you need to append folder "ddd" by another path use;
String currentFolder= "/" + currentPath.getName().toString();
as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so
echo date('n'); // "9"
This is what worked for me on windows:
Edit the pg_hba.conf file locates at C:\Program Files\PostgreSQL\9.3\data.
# IPv4 local connections:
host all all 127.0.0.1/32 trust
Change the method from trust to md5 and restart the postgres service on windows.
After that, you can login using postgres user without password by using pgadmin. You can change password using File->Change password.
If postgres user does not have superuser privileges , then you cannot change the password. In this case , login with another user(pgsql)with superuser access and provide privileges to other users by right clicking on users and selecting properties->Role privileges.
For Angular 5+ :
import { Observable } from 'rxjs/Observable';
should work. The observer package should match the import as well import { Observer } from 'rxjs/Observer';
if you're using observers that is
import {<something>} from 'rxjs';
does a huge import so it's better to avoid it.
Jsfiddle: http://jsfiddle.net/guhokemk/1/
function compare(dateTimeA, dateTimeB) {
var momentA = moment(dateTimeA,"DD/MM/YYYY");
var momentB = moment(dateTimeB,"DD/MM/YYYY");
if (momentA > momentB) return 1;
else if (momentA < momentB) return -1;
else return 0;
}
alert(compare("11/07/2015", "10/07/2015"));
The method returns 1 if dateTimeA is greater than dateTimeB
The method returns 0 if dateTimeA equals dateTimeB
The method returns -1 if dateTimeA is less than dateTimeB
Read man sshd_config
for more details, but you can use the AllowUsers
directive in /etc/ssh/sshd_config
to limit the set of users who can login.
e.g.
AllowUsers boris
would mean that only the boris
user could login via ssh.
Check this basic code to setup html server. its work for me.
var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(8000); });
Just add [mysqld]
as first line in the /etc/mysql/my.cnf
file.
[mysqld]
default-time-zone = "+08:00"
Afterwards, remember to restart your MySQL Service.
sudo mysqld stop
sudo mysqld start
Put the data into a Pivot Table and do a top n filter on it
If you're already using Heroku, consider running your server via Foreman. It supports a .env
file which is simply a list of lines with KEY=VAL
that will be exported to your app before it runs.
Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).
Anyways, if you're already planning on using MSYS2, there's no need for that installer.
Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).
After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit
or MSYS2 32-bit
in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu
, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).
Install a toolchain
a) for 32-bit:
pacman -S mingw-w64-i686-gcc
b) for 64-bit:
pacman -S mingw-w64-x86_64-gcc
install any libraries/tools you may need. You can search the repositories by doing
pacman -Ss name_of_something_i_want_to_install
e.g.
pacman -Ss gsl
and install using
pacman -S package_name_of_something_i_want_to_install
e.g.
pacman -S mingw-w64-x86_64-gsl
and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!
Open a MinGW-w64 shell:
a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"
b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"
Verify that the compiler is working by doing
gcc -v
If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin
or <MSYS2 root>/mingw64/bin
to your PATH
.
Ubuntu 18.04 LTS
These are the steps which worked for me. Many, many thanks to William Desportes for providing the automatic updates on their Ubuntu PPA.
Step 1 (from William Desportes post)
$ sudo add-apt-repository ppa:phpmyadmin/ppa
Step 2
$ sudo apt-get --with-new-pkgs upgrade
Step 3
$ sudo service mysql restart
If you have issues restarting mysql, you can also restart with the following sequence
$ sudo service mysql stop;
$ sudo service mysql start;
list_1.insert(0,ur_data)
make sure that ur_data is of string type
so if u have data= int(5)
convert it to ur_data = str(data)
You can try this:
@OneToOne(cascade = CascadeType.REFRESH)
or
@OneToMany(cascade = CascadeType.REFRESH)
First of all make sure you java is working or not run this command in cmd
C:\>java -version
if it's working it will show this output:-
C:\>java -version
java version "1.8.0_74"
Java(TM) SE Runtime Environment (build 1.8.0_74-b02)
Java HotSpot(TM) Client VM (build 25.74-b02, mixed mode)
step 1. First set your java_home[C:\Program Files\Java\jdk1.8.0_74] path in user variable.
step 2. Then set MAVEN_HOME[C:\Program Files\maven\apache-maven-3.3.9] path in system variable and make sure your maven folder should be present in C folder only.
step 3. Then set M2 path in system variable and give maven bin location there i.e.[C:\Program Files\maven\apache-maven-3.3.9\bin].
Step 4. Then set new system variable i.e. variable name = MAVEN_OPTS in and variable value =-Xms256m -Xmx512m
Step 5. Then edit path/system path variable be care full don't remove anything from there simply add java_home path i.e=;C:\Program Files\Java\jdk1.8.0_74 and M2 variable=;%M2% in the end.
Step 6. To make sure maven is now working or not run this command in cmd
> C:\>mvn --version
if it's working it will show this result :-
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-
7+05:30)
Maven home: C:\Program Files\maven\apache-maven-3.3.9\bin\..
Java version: 1.8.0_74, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_74\jre
Default locale: en_IN, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "dos"
Simple socket server app example
I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.
This example app runs a server that returns a ROT-1 cypher of the input.
You would then need to add an Exit
button + some sleep delays, but this should get you started.
To play with it:
netcat $PHONE_IP 12345
Android sockets are the same as Java's, except we have to deal with some permission issues.
src/com/cirosantilli/android_cheat/socket/Main.java
package com.cirosantilli.android_cheat.socket;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main extends Activity {
static final String TAG = "AndroidCheatSocket";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Main.TAG, "onCreate");
Main.this.startService(new Intent(Main.this, MyService.class));
}
public static class MyService extends IntentService {
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(Main.TAG, "onHandleIntent");
final int port = 12345;
ServerSocket listener = null;
try {
listener = new ServerSocket(port);
Log.d(Main.TAG, String.format("listening on port = %d", port));
while (true) {
Log.d(Main.TAG, "waiting for client");
Socket socket = listener.accept();
Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
for (String inputLine; (inputLine = in.readLine()) != null;) {
Log.d(Main.TAG, "received");
Log.d(Main.TAG, inputLine);
StringBuilder outputStringBuilder = new StringBuilder("");
char inputLineChars[] = inputLine.toCharArray();
for (char c : inputLineChars)
outputStringBuilder.append(Character.toChars(c + 1));
out.println(outputStringBuilder);
}
}
} catch(IOException e) {
Log.d(Main.TAG, e.toString());
}
}
}
}
We need a Service
or other background method or else: How do I fix android.os.NetworkOnMainThreadException?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cirosantilli.android_cheat.socket"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="AndroidCheatsocket">
<activity android:name="Main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Main$MyService" />
</application>
</manifest>
We must add: <uses-permission android:name="android.permission.INTERNET" />
or else: Java socket IOException - permission denied
On GitHub with a build.xml
: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket
Avoid hardcoding try making the code that is dynamic below is the code it will work for any xml I have used SAX Parser you can use dom,xpath it's upto you
I am storing all the tags name and values in the map after that it becomes easy to retrieve any values you want I hope this helps
SAMPLE XML:
<parent>
<child >
<child1> value 1 </child1>
<child2> value 2 </child2>
<child3> value 3 </child3>
</child>
<child >
<child4> value 4 </child4>
<child5> value 5</child5>
<child6> value 6 </child6>
</child>
</parent>
JAVA CODE:
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class saxParser {
static Map<String,String> tmpAtrb=null;
static Map<String,String> xmlVal= new LinkedHashMap<String, String>();
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {
/**
* We can pass the class name of the XML parser
* to the SAXParserFactory.newInstance().
*/
//SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);
SAXParserFactory saxDoc = SAXParserFactory.newInstance();
SAXParser saxParser = saxDoc.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
String tmpElementName = null;
String tmpElementValue = null;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tmpElementValue = "";
tmpElementName = qName;
tmpAtrb=new HashMap();
//System.out.println("Start Element :" + qName);
/**
* Store attributes in HashMap
*/
for (int i=0; i<attributes.getLength(); i++) {
String aname = attributes.getLocalName(i);
String value = attributes.getValue(i);
tmpAtrb.put(aname, value);
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(tmpElementName.equals(qName)){
System.out.println("Element Name :"+tmpElementName);
/**
* Retrive attributes from HashMap
*/ for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue());
}
System.out.println("Element Value :"+tmpElementValue);
xmlVal.put(tmpElementName, tmpElementValue);
System.out.println(xmlVal);
//Fetching The Values From The Map
String getKeyValues=xmlVal.get(tmpElementName);
System.out.println("XmlTag:"+tmpElementName+":::::"+"ValueFetchedFromTheMap:"+getKeyValues);
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
tmpElementValue = new String(ch, start, length) ;
}
};
/**
* Below two line used if we use SAX 2.0
* Then last line not needed.
*/
//saxParser.setContentHandler(handler);
//saxParser.parse(new InputSource("c:/file.xml"));
saxParser.parse(new File("D:/Test _ XML/file.xml"), handler);
}
}
OUTPUT:
Element Name :child1
Element Value : value 1
XmlTag:<child1>:::::ValueFetchedFromTheMap: value 1
Element Name :child2
Element Value : value 2
XmlTag:<child2>:::::ValueFetchedFromTheMap: value 2
Element Name :child3
Element Value : value 3
XmlTag:<child3>:::::ValueFetchedFromTheMap: value 3
Element Name :child4
Element Value : value 4
XmlTag:<child4>:::::ValueFetchedFromTheMap: value 4
Element Name :child5
Element Value : value 5
XmlTag:<child5>:::::ValueFetchedFromTheMap: value 5
Element Name :child6
Element Value : value 6
XmlTag:<child6>:::::ValueFetchedFromTheMap: value 6
Values Inside The Map:{child1= value 1 , child2= value 2 , child3= value 3 , child4= value 4 , child5= value 5, child6= value 6 }
I think if you are looking for fullscreen only, no need to set geometry or maxsize etc.
You just need to do this:
-If you are working on ubuntu:
root=tk.Tk()
root.attributes('-zoomed', True)
-and if you are working on windows:
root.state('zoomed')
Now for toggling between fullscreen, for minimising it to taskbar you can use:
Root.iconify()
Your attempt wasn't that bad. You have to do it with LIKE
, yes.
In the manual it says:
Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table.
So you do:
CREATE TABLE New_Users LIKE Old_Users;
Then you insert with
INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID;
But you can not do it in one statement.
Next to being in the wrong directory I just tripped about another variant:
I had a File.open(my_file).each {|line| puts line}
exploding but there was something by that name in the directory I was working in (ls in the command line showed the name). I checked with a File.exists?(my_file)
which strangely returned false
. Explanation: my_file
was a symlink which target didn't exist anymore! Since File.exists?
will follow a symlink it will say false
though the link is still there.
Step 1: Write the following javascript inside your head tag
<script language="javascript">
function PrintMe(DivID) {
var disp_setting="toolbar=yes,location=no,";
disp_setting+="directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
var content_vlue = document.getElementById(DivID).innerHTML;
var docprint=window.open("","",disp_setting);
docprint.document.open();
docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"');
docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">');
docprint.document.write('<head><title>My Title</title>');
docprint.document.write('<style type="text/css">body{ margin:0px;');
docprint.document.write('font-family:verdana,Arial;color:#000;');
docprint.document.write('font-family:Verdana, Geneva, sans-serif; font-size:12px;}');
docprint.document.write('a{color:#000;text-decoration:none;} </style>');
docprint.document.write('</head><body onLoad="self.print()"><center>');
docprint.document.write(content_vlue);
docprint.document.write('</center></body></html>');
docprint.document.close();
docprint.focus();
}
</script>
Step 2: Call the PrintMe('DivID') function by an onclick event.
<input type="button" name="btnprint" value="Print" onclick="PrintMe('divid')"/>
<div id="divid">
here is some text to print inside this div with an id 'divid'
</div>
To deal with situations where there are a possibility of multiple values (v in your example), I use PIVOT
and LISTAGG
:
SELECT * FROM
(
SELECT id, k, v
FROM _kv
)
PIVOT
(
LISTAGG(v ,',')
WITHIN GROUP (ORDER BY k)
FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;
Since you want dynamic values, use dynamic SQL and pass in the values determined by running a select on the table data before calling the pivot statement.
I've had the same problem.
Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.
In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :
<script>document.write('<style>.js_hidden { display: none; }</style>');</script>
<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>
Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :
For a list of elements
List<string> lstTest = new List<string>();
lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");
If you want to copy all the elements
List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);
If you want to copy the first 3 elements
List<string> lstNew = lstTest.GetRange(0, 3);
you could try this:
1. Open the "Android Virtual device Manager"
2. Select from one the listed devices there and run it.
3. Right click your Android App -> Run As -> Android Application
It worked for me. I tried this on an emulator in eclipse. It takes a while before the app is run. For me it took 33 seconds. Wait until the message in the console says "Success!"
Adding value to all these answers,
many have asked the command for running App in AVD after build sucessful.
adb install -r {path-to-your-bild-folder}/{yourAppName}.apk
There are two ways to go about this:
I recommend the first option initially, due to its ease of implementation. Once you mature in your build processes, switch over to the second.
Poll the repository to see if changes occurred. This might "skip" a commit if two commits come in within the same polling interval. Description of how to do so here, note the fourth screenshot where you configure on the job a "build trigger" based on polling the repository (with a crontab-like configuration).
Configure your repository to have a post-commit hook which notifies Jenkins that a build needs to start. Description of how to do so here, in the section "post-commit hooks"
The SVN Tag feature is not part of the polling, it is part of promoting the current "head" of the source code to a tag, to snapshot a build. This allows you to refer to Jenkins buid #32 as SVN tag /tags/build-32 (or something similar).
Delete the .metadata
folder in your workspace.
Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.
The .project
file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)
The .classpath
file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings
directory inside the project); the .classpath
file is just one of them. Specifically, the .classpath
file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).
Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath
file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath
file portability.
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
For those with a git gui bent, you can also use gitk.
Right click on the commit you want to return to and select "Reset master branch to here". Then choose hard from the next menu.
Use and empty()
whit negation (for test if not empty)
if(!empty($_GET['id'])) {
// if get id is not empty
}
I am using an ImageView in an RelativeLayout that overlays with my normal layout. No code required. It sizes the image to the full height of the screen (or any other layout you use) and then crops the picture left and right to fit the width. In my case, if the user turns the screen, the picture may be a tiny bit too small. Therefore I use match_parent, which will make the image stretch in width if too small.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/main_backgroundImage"
android:layout_width="match_parent"
//comment: Stretches picture in the width if too small. Use "wrap_content" does not stretch, but leaves space
android:layout_height="match_parent"
//in my case I always want the height filled
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
//will crop picture left and right, so it fits in height and keeps aspect ratio
android:contentDescription="@string/image"
android:src="@drawable/your_image" />
<LinearLayout
android:id="@+id/main_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
You should do it like this:
for ($i=1; $i <=10; $i+=2)
{
echo $i.'<br>';
}
"+=" you can increase your variable as much or less you want. "$i+=5" or "$i+=.5"
The problem is this block:
using (var sr = new StreamReader(ms))
{
Console.WriteLine(sr.ReadToEnd());
}
When the StreamReader
is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream
is closed. When the StreamWriter
gets closed, it tries to flush everything to the MemoryStream
, but it is closed.
You should consider not putting the StreamReader
in a using block.
I want to explain the error with an example below:
> names(lenses)
[1] "X1..1..1..1..1..3"
names(lenses)=c("ID","Age","Sight","Astigmatism","Tear","Class") Error in names(lenses) = c("ID", "Age", "Sight", "Astigmatism", "Tear", : 'names' attribute [6] must be the same length as the vector [1]
The error happened because of mismatch in a number of attributes. I only have one but trying to add 6 names. In this case, the error happens. See below the correct one:::::>>>>
> names(lenses)=c("ID")
> names(lenses)
[1] "ID"
Now there was no error.
I hope this will help!
I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.
I see 2 easy options:
gradient option:
html {
min-height:100%;
background:linear-gradient(0deg, rgba(255, 0, 150, 0.3), rgba(255, 0, 150, 0.3)), url(http://lorempixel.com/800/600/nature/2);
background-size:cover;
}
shadow option:
html {
min-height:100%;
background:url(http://lorempixel.com/800/600/nature/2);
background-size:cover;
box-shadow:inset 0 0 0 2000px rgba(255, 0, 150, 0.3);
}
an old codepen of mine with few examples
a third option
The
background-blend-mode
CSS property sets how an element's background images should blend with each other and with the element's background color.
html {
min-height:100%;
background:url(http://lorempixel.com/800/600/nature/2) rgba(255, 0, 150, 0.3);
background-size:cover;
background-blend-mode: multiply;
}
Java 8 now allows implementation of methods inside an interface itself with default scope (and static only).
timer.scheduleAtFixedRate( new Task(), 1000,3000);
And in swift, you don't need to import "QuartzCore/QuartzCore.h"
Just use:
button.layer.borderWidth = 0.8
button.layer.borderColor = (UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )).cgColor
or
button.layer.borderWidth = 0.8
button.layer.borderColor = UIColor.grayColor().cgColor
user1594322 gave a correct answer but when I tried it I ran into admin/permission problems. I was able to copy 'mingw32-make.exe' and paste it, over-ruling/by-passing admin issues and then editing the copy to 'make.exe'. On VirtualBox in a Win7 guest.
What do you mean by
"but it will not act as a real fully functional interface (if the original interface is inactive, then the derived one is also inactive"
?
I can make a new interface, base it on an already existing one, then disable the existing one and the new one still works. Making a second interface does however not create a real interface (when you check with ifconfig), it will just assign a second IP to the already existing one (however, this one can be DHCP while the first one is hard coded for example).
So did I understand you right, that you want to create an interface, not bound to any real interface? How would this interface then be used? E.g. if you disconnect all WLAN and pull all network cables, where would this interface send traffic to, if you send traffic to it? Maybe your question is a bit unclear, it might help a lot if rephrase it, so it's clear what you are actually trying to do with this "virtual interface" once you have it.
As you mentioned "alias IP" in your question, this would mean an alias interface. But an alias interface is always bound to a real interface. The difference is in Linux such an interface really IS an interface (e.g. an alias interface for eth0 could be eth1), while on Mac, no real interface is created, instead a virtual interface is created, that can configured and used independently, but it is still the same interface physically and thus no new named interface is generated (you just have two interfaces, that are both in fact en0, but both can be enabled/disabled and configured independently).
After enabling "SQL Server and Windows Authentication mode"(check above answers on how to), navigate to the following.
Finally restart the SQL Server.
See MSDN documentation for InitialCatalog Property:
Gets or sets the name of the database associated with the connection...
This property corresponds to the "Initial Catalog" and "database" keys within the connection string...