This is a quite confusing way of using Apache configuration directives.
Technically, the first bit is equivalent to
Allow From All
This is because Order Deny,Allow
makes the Deny directive evaluated before the Allow Directives.
In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.
Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.
The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.
Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.
It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.
The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy all
</Files>
which forbids access to any file beginning by ".ht".
The equivalent Apache 2.4 configuration should look like:
<Files ~ "^\.ht">
Require all denied
</Files>
Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.
For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:
For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.
In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.
There are several ways that you can transform data from multiple rows into columns.
PIVOT
In SQL Server you can use the PIVOT
function to transform the data from rows to columns:
select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
select value, columnname
from yourtable
) d
pivot
(
max(value)
for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;
See Demo.
columnnames
If you have an unknown number of columnnames
that you want to transpose, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)
from yourtable
group by ColumnName, id
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select value, ColumnName
from yourtable
) x
pivot
(
max(value)
for ColumnName in (' + @cols + N')
) p '
exec sp_executesql @query;
See Demo.
If you do not want to use the PIVOT
function, then you can use an aggregate function with a CASE
expression:
select
max(case when columnname = 'FirstName' then value end) Firstname,
max(case when columnname = 'Amount' then value end) Amount,
max(case when columnname = 'PostalCode' then value end) PostalCode,
max(case when columnname = 'LastName' then value end) LastName,
max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable
See Demo.
This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:
select fn.value as FirstName,
a.value as Amount,
pc.value as PostalCode,
ln.value as LastName,
an.value as AccountNumber
from yourtable fn
left join yourtable a
on fn.somecol = a.somecol
and a.columnname = 'Amount'
left join yourtable pc
on fn.somecol = pc.somecol
and pc.columnname = 'PostalCode'
left join yourtable ln
on fn.somecol = ln.somecol
and ln.columnname = 'LastName'
left join yourtable an
on fn.somecol = an.somecol
and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'
Look at Compare-Object
Compare-Object $a1 $b1 | ForEach-Object { $_.InputObject }
Or if you would like to know where the object belongs to, then look at SideIndicator:
$a1=@(1,2,3,4,5,8)
$b1=@(1,2,3,4,5,6)
Compare-Object $a1 $b1
You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.
select dbo.fun_functional_score('01091400003')
You'll see people using the Timer class to do this. Unfortunately, it isn't always accurate. Your best bet is to get the system time when the user enters input, calculate a target system time, and check if the system time has exceeded the target system time. If it has, then break out of the loop.
If you use
android:taskAffinity="myApp.widget.notify.activity"
android:excludeFromRecents="true"
in your AndroidManifest.xml file for the Activity to launch, you have to use the following in your intent:
Intent notificationClick = new Intent(context, NotifyActivity.class);
Bundle bdl = new Bundle();
bdl.putSerializable(NotifyActivity.Bundle_myItem, myItem);
notificationClick.putExtras(bdl);
notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
notificationClick.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); // schließt tasks der app und startet einen seperaten neuen
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotifyActivity.class);
stackBuilder.addNextIntent(notificationClick);
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(notificationPendingIntent);
Important is to set unique data e.g. using an unique id like:
notificationClick.setData(Uri.parse(notificationClick.toUri(Intent.URI_INTENT_SCHEME) + myItem.getId()));
Your setters are strange, which is why you may be seeing a problem.
First, consider whether you even need these setters - if so, they should take a List<string>
, not just a string
:
set
{
_subHead = value;
}
These lines:
newSec.subHead.Add("test string");
Are calling the getter and then call Add
on the returned List<string>
- the setter is not invoked.
In Notepad++ to replace, hit Ctrl+H to open the Replace menu.
Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google). For example, let's say that you want to match each of the following lines
value="4"
value="403"
value="200"
value="201"
value="116"
value="15"
using the .*"\d+"
pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses (
and )
, like that: .*"(\d+)"
. So now in your replacement you can simply write $1
, where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)"
, $1
will return the string value
and $2
will return the number.
So by using:
Find: .*"(\d+)"
Replace: $1
It will return you
4
403
200
201
116
15
Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)"
would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)
Please note, this answer works with numeric data types (int, long). If you are starting with a string, you'll need to convert it to a number first. Also, please take into account that you'll need to validate that the initial string is at least 10 characters in length.
From a good page full of examples:
String.Format("{0:(###) ###-####}", 8005551212);
This will output "(800) 555-1212".
Although a regex may work even better, keep in mind the old programming quote:
Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
--Jamie Zawinski, in comp.lang.emacs
Switching to the legacy build system fixed the issue for me
You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.
dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);
Check this
EDIT
As per the comment posted by Frank and Mat, you can also enable it with Null
exec dbms_output.enable(NULL);
buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).
The semantics of Having
To better understand having, you need to see it from a theoretical point of view.
A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.
The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.
Lets say your query is:
select a, b, count(*)
from Table
where c > 100
group by a, b
having count(*) > 10;
The evaluation of this query can be seen as the following steps:
You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).
In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:
SELECT list
FROM table
GROUP BY attrList
HAVING condition;
can be rewritten as:
SELECT list from (
SELECT listatt
FROM table
GROUP BY attrList) as Name
WHERE condition;
The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:
select a, b, count
from (select a, b, count(*) as count
from Table
where c > 100
group by a, b) as someName
where count > 10;
The solution you need
Your solution seems to be correct:
SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2
You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2
, which is that you wanted originally.
Best solution to your problem
I personally prefer a simpler cleaner solution:
SELECT sid, sname from
(SELECT sid from supplies
GROUP BY sid, pid
HAVING count(DISTINCT jid) >= 2
) AS T1
NATURAL JOIN
Supliers;
It will also be faster to execute, because the join is only done when needed, not all the times.
--dmg
For select twitter meta name , you can add a data attribute.
example :
meta name="twitter:card" data-twitterCard="" content=""
$('[data-twitterCard]').attr('content');
If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.
CREATE TABLE #Table(C1 int,
C2 NVarchar(100) , C3 varchar(100)
UNIQUE CLUSTERED (c1)
);
Create table with unique clustered index
Insert data into Temp "#Table" table
Create non clustered indexes.
CREATE NONCLUSTERED INDEX IX1 ON #Table (C2,C3);
Running a simple test, I thought I'd document what works and what doesn't. Often I see people checking to see if the object's class is a member of the other class or is equal to the other class.
For the line below, we have some poorly formed data that can be an NSArray
, an NSDictionary
or (null)
.
NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] objectForKey: @"Hit"];
These are the tests that were performed:
NSLog(@"%@", [hits class]);
if ([hits isMemberOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
isKindOfClass
worked rather well while isMemberOfClass
didn't.
Try to use this variant:
<?php echo Yii::app()->createAbsoluteUrl('your_yii_application/?lg=pl', array('id'=>$model->id));?>
It is the easiest way, I guess.
Something like this?
public static T ConvertValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
You can then use it like this:
int val = ConvertValue<int>("42");
Edit:
You can even do this more generic and not rely on a string
parameter provided the type U
implements IConvertible
- this means you have to specify two type parameters though:
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
I considered catching the InvalidCastException
exception that might be raised by Convert.ChangeType()
- but what would you return in this case? default(T)
? It seems more appropriate having the caller deal with the exception.
In the simplest terms, an ASP.NET HttpHandler is a class that implements the System.Web.IHttpHandler
interface.
ASP.NET HTTPHandlers are responsible for intercepting requests made to your ASP.NET web application server. They run as processes in response to a request made to the ASP.NET Site. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.
ASP.NET offers a few default HTTP handlers:
You can create your own custom HTTP handlers that render custom output to the browser. Typical scenarios for HTTP Handlers in ASP.NET are for example
You implement the IHttpHandler
interface to create a synchronous handler and the IHttpAsyncHandler
interface to create an asynchronous handler. The interfaces require you to implement the ProcessRequest
method and the IsReusable
property.
The ProcessRequest
method handles the actual processing for requests made, while the Boolean IsReusable
property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.
I think Buu's digest cycle watch is genius. Thanks for sharing. As others have noted $interval also causes the digest cycle to run. We could for the purpose of auto logging the user out use setInterval which will not cause a digest loop.
app.run(function($rootScope) {
var lastDigestRun = new Date();
setInterval(function () {
var now = Date.now();
if (now - lastDigestRun > 10 * 60 * 1000) {
//logout
}
}, 60 * 1000);
$rootScope.$watch(function() {
lastDigestRun = new Date();
});
});
One method is to manually set the default for the axis background color within your script (see Customizing matplotlib):
import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'black'
This is in contrast to Nick T's method which changes the background color for a specific axes
object. Resetting the defaults is useful if you're making multiple different plots with similar styles and don't want to keep changing different axes
objects.
Note: The equivalent for
fig = plt.figure()
fig.patch.set_facecolor('black')
from your question is:
plt.rcParams['figure.facecolor'] = 'black'
Why don't you try this
for(int i=0; i < dt.Rows.Count; i++)
{
// u can use here the i
}
I find the following code to be much simpler than anything else:
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Now, calling functions
setCookie('ppkcookie','testcookie',7);
var x = getCookie('ppkcookie');
if (x) {
[do something with x]
}
Source - http://www.quirksmode.org/js/cookies.html
They updated the page today so everything in the page should be latest as of now.
Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:
<script>
$(document).ready(function() {
$('img.thumbnail').click(function() {
window.location.href = this.id + '.html';
});
});
</script>
Basically, it attaches an onClick
event to all images with class thumbnail
to redirect to the corresponding HTML page (id
+ .html
). Then you only need the images in your HTML (without the a
elements), like this:
<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />
A lot of people mention companion objects, which is correct. But, just so you know, you can also use any sort of object (using the object keyword, not class) i.e.,
object StringUtils {
fun toUpper(s: String) : String { ... }
}
Use it just like any static method in java:
StringUtils.toUpper("foobar")
That sort of pattern is kind of useless in Kotlin though, one of its strengths is that it gets rid of the need for classes filled with static methods. It is more appropriate to utilize global, extension and/or local functions instead, depending on your use case. Where I work we often define global extension functions in a separate, flat file with the naming convention: [className]Extensions.kt i.e., FooExtensions.kt. But more typically we write functions where they are needed inside their operating class or object.
One issue is that reindex
will fail if there are duplicate values. Say we're working with timestamped data, which we want to index by date:
df = pd.DataFrame({
'timestamps': pd.to_datetime(
['2016-11-15 1:00','2016-11-16 2:00','2016-11-16 3:00','2016-11-18 4:00']),
'values':['a','b','c','d']})
df.index = pd.DatetimeIndex(df['timestamps']).floor('D')
df
yields
timestamps values
2016-11-15 "2016-11-15 01:00:00" a
2016-11-16 "2016-11-16 02:00:00" b
2016-11-16 "2016-11-16 03:00:00" c
2016-11-18 "2016-11-18 04:00:00" d
Due to the duplicate 2016-11-16
date, an attempt to reindex:
all_days = pd.date_range(df.index.min(), df.index.max(), freq='D')
df.reindex(all_days)
fails with:
...
ValueError: cannot reindex from a duplicate axis
(by this it means the index has duplicates, not that it is itself a dup)
Instead, we can use .loc
to look up entries for all dates in range:
df.loc[all_days]
yields
timestamps values
2016-11-15 "2016-11-15 01:00:00" a
2016-11-16 "2016-11-16 02:00:00" b
2016-11-16 "2016-11-16 03:00:00" c
2016-11-17 NaN NaN
2016-11-18 "2016-11-18 04:00:00" d
fillna
can be used on the column series to fill blanks if needed.
+=
adds a number to a variable, changing the variable itself in the process (whereas +
would not). Similar to this, there are the following that also modifies the variable:
-=
, subtracts a value from variable, setting the variable to the result*=
, multiplies the variable and a value, making the outcome the variable/=
, divides the variable by the value, making the outcome the variable%=
, performs modulus on the variable, with the variable then being set to the result of itThere may be others. I am not a Python programmer.
The existing answers will fail if the string is empty or only has one character. Options:
String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;
or
String substring = str.substring(Math.max(str.length() - 2, 0));
That's assuming that str
is non-null, and that if there are fewer than 2 characters, you just want the original string.
move
in windows is equivalent of mv
command in Linux
del
in windows is equivalent of rm
command in Linux
If you're using the ReSharper plugin, you can do that using the Shift + Alt + L shortcut or navigate via menu as shown.
You need xlutils.copy
. Try something like this:
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
Keep in mind you can't overwrite cells by default as noted in this question.
Step 1. Figure out which errors you want to trap:
If the table does not exist:
SQL> drop table x;
drop table x
*
ERROR at line 1:
ORA-00942: table or view does not exist
If the table is in use:
SQL> create global temporary table t (data varchar2(4000));
Table created.
Use the table in another session. (Notice no commit or anything after the insert.)
SQL> insert into t values ('whatever');
1 row created.
Back in the first session, attempt to drop:
SQL> drop table t;
drop table t
*
ERROR at line 1:
ORA-14452: attempt to create, alter or drop an index on temporary table already in use
So the two errors to trap:
See if the errors are predefined. They aren't. So they need to be defined like so:
create or replace procedure p as
table_or_view_not_exist exception;
pragma exception_init(table_or_view_not_exist, -942);
attempted_ddl_on_in_use_GTT exception;
pragma exception_init(attempted_ddl_on_in_use_GTT, -14452);
begin
execute immediate 'drop table t';
exception
when table_or_view_not_exist then
dbms_output.put_line('Table t did not exist at time of drop. Continuing....');
when attempted_ddl_on_in_use_GTT then
dbms_output.put_line('Help!!!! Someone is keeping from doing my job!');
dbms_output.put_line('Please rescue me');
raise;
end p;
And results, first without t
:
SQL> drop table t;
Table dropped.
SQL> exec p;
Table t did not exist at time of drop. Continuing....
PL/SQL procedure successfully completed.
And now, with t
in use:
SQL> create global temporary table t (data varchar2(4000));
Table created.
In another session:
SQL> insert into t values (null);
1 row created.
And then in the first session:
SQL> exec p;
Help!!!! Someone is keeping from doing my job!
Please rescue me
BEGIN p; END;
*
ERROR at line 1:
ORA-14452: attempt to create, alter or drop an index on temporary table already in use
ORA-06512: at "SCHEMA_NAME.P", line 16
ORA-06512: at line 1
Since the quickest, shortest answer is in a comment (from Jeff) and has a typo, here it is corrected and in full:
sales['time_hour'] = pd.DatetimeIndex(sales['timestamp']).hour
Use this:
mysqli_query($this->db_link, $query) or die(mysqli_error($this->db_link));
# mysqli_query($link,$query) returns 0 if there's an error.
# mysqli_error($link) returns a string with the last error message
You can also use this to print the error code.
echo mysqli_errno($this->db_link);
If you look at the documentation for str.split
:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
In other words, if you're trying to figure out what to pass to split
to get '\n\tName: Jane Smith'
to ['Name:', 'Jane', 'Smith']
, just pass nothing (or None).
This almost solves your whole problem. There are two parts left.
First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:
s.split(None, 1)
Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:
key, value = s.split(None, 1)
key = key[:-1]
There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.
When we create new types by defining classes, we can take advantage of certain features of Python to make the new classes convenient to use. One of these features is "special methods", also referred to as "magic methods".
Special methods have names that begin and end with two underscores. We define them, but do not usually call them directly by name. Instead, they execute automatically under under specific circumstances.
It is convenient to be able to output the value of an instance of an object by using a print statement. When we do this, we would like the value to be represented in the output in some understandable unambiguous format. The repr special method can be used to arrange for this to happen. If we define this method, it can get called automatically when we print the value of an instance of a class for which we defined this method. It should be mentioned, though, that there is also a str special method, used for a similar, but not identical purpose, that may get precedence, if we have also defined it.
If we have not defined, the repr method for the Point3D class, and have instantiated my_point as an instance of Point3D, and then we do this ...
print my_point ... we may see this as the output ...
Not very nice, eh?
So, we define the repr or str special method, or both, to get better output.
**class Point3D(object):
def __init__(self,a,b,c):
self.x = a
self.y = b
self.z = c
def __repr__(self):
return "Point3D(%d, %d, %d)" % (self.x, self.y, self.z)
def __str__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point # __repr__ gets called automatically
print my_point # __str__ gets called automatically**
Output ...
(1, 2, 3) (1, 2, 3)
You have to know that:
Assignment operators syntax is: variable = expression;
For this reason 1 += 2
-> 1 = 1 + 2
is not a valid syntax as the left operand isn't a variable. The error in this case is ReferenceError: invalid assignment left-hand side
.
x += y
is the short form for x = x + y
, where x
is the variable and x + y
the expression.
The result of the sum is 15.
sum = 0; sum = sum + 1; // 1 sum = sum + 2; // 3 sum = sum + 3; // 6 sum = sum + 4; // 10 sum = sum + 5; // 15
Other assignment operator shortcuts works the same way (relatively to the standard operations they refer to). .
I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on
git branch -f <branchname> <commit>
Here is a scenario where I have needed to do this.
Develop on the wrong branch and hence need to reset it.
Cleanly develop and release some software.
Mistake: Accidentally stay on the release branch while developing further.
"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.
Create a branch for the development that is up to date holding the work committed so far and switch to it.
git branch development
git checkout development
Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.
Correct the release branch to point back to the last real release.
git branch -f release release2
The release branch is now correct again, like this ...
git push -f <remote> <branch>
is well described in another thread, though the word "overwrite" in the title is misleading.
Force "git push" to overwrite remote files
Assuming you have two programs that process the two files, process_in.exe and process_out.exe:
for %%f in (*.in) do (
echo %%~nf
process_in "%%~nf.in"
process_out "%%~nf.out"
)
%%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.
I know rather old question but....came across looking other thing so I give my shot:
[each*2 for each in [1,2,3,4,5] if each % 10 == 0])
If you generated the script from the MySQL workbench.
The following line is generated
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
Remove TRADITIONAL from the SQL_MODE, and then the script should work fine
Else, you could set the SQL_MODE as Allow Invalid Dates
SET SQL_MODE='ALLOW_INVALID_DATES';
I had the same problem and I fixed it by using the
This is a late answer, but I believe it is still useful.
I have created the NinjaNye.SearchExtension nuget package that can help solve this very problem.:
string[] terms = new[]{"search", "term", "collection"};
var result = context.Table.Search(terms, x => x.Name);
You could also search multiple string properties
var result = context.Table.Search(terms, x => x.Name, p.Description);
Or perform a RankedSearch
which returns IQueryable<IRanked<T>>
which simply includes a property which shows how many times the search terms appeared:
//Perform search and rank results by the most hits
var result = context.Table.RankedSearch(terms, x => x.Name, x.Description)
.OrderByDescending(r = r.Hits);
Hope this helps future visitors
Imagine you have have a Book model and a Page model,
1:N means:
One book can have **many** pages. One page can only be in **one** book.
N:N means:
One book can have **many** pages. And one page can be in **many** books.
Well, i guess M represent the mantissa. Decimal can be used to save money, but it doesn't mean, decimal only used for money.
var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);
var first = month.AddMonths(-1);
var last = month.AddDays(-1);
In-line them if you really need one or two lines.
You can reset by update sequence after deleted rows in your-table
UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';
Here I am trying to help you do the job step by step: (this may be the answer to other questions)
that is pretty much it. now you can use SQLite in your project. to use it in your project on the code level you may use this below example code:
make a connection string:
string connectionString = @"URI=file:{the location of your sqlite database}";
establish a sqlite connection:
SQLiteConnection theConnection = new SQLiteConnection(connectionString );
open the connection:
theConnection.Open();
create a sqlite command:
SQLiteCommand cmd = new SQLiteCommand(theConnection);
Make a command text, or better said your SQLite statement:
cmd.CommandText = "INSERT INTO table_name(col1, col2) VALUES(val1, val2)";
Execute the command
cmd.ExecuteNonQuery();
that is it.
response.setContentType("text/json");
//create the JSON string, I suggest using some framework.
String your_string;
out.write(your_string.getBytes("UTF-8"));
Following workaround can be used to kill a thread:
kill_threads = False
def doSomething():
global kill_threads
while True:
if kill_threads:
thread.exit()
......
......
thread.start_new_thread(doSomething, ())
This can be used even for terminating threads, whose code is written in another module, from main thread. We can declare a global variable in that module and use it to terminate thread/s spawned in that module.
I usually use this to terminate all the threads at the program exit. This might not be the perfect way to terminate thread/s but could help.
Here's another way to set directories to 775 and files to 664.
find /opt/lampp/htdocs \
\( -type f -exec chmod ug+rw,o+r {} \; \) , \
\( -type d -exec chmod ug+rwxs,o+rx {} \; \)
It may look long, but it's pretty cool for three reasons:
man
pages (see below).Note that I have not confirmed the performance difference (if any) between this solution and that of simply using two find commands (as in Peter Mortensen's solution). However, seeing a similar example in the manual is encouraging.
Example from man find
page:
find / \
\( -perm -4000 -fprintf /root/suid.txt %#m %u %p\n \) , \
\( -size +100M -fprintf /root/big.txt %-10s %p\n \)
Traverse the filesystem just once, listing setuid files and direct-
tories into /root/suid.txt and large files into /root/big.txt.
Cheers
I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :
[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.
I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...
I like this for a simple check from the shell:
mysql -p<password> -D<database> -B -e "SHOW TABLES LIKE 'User%'" \
| awk 'NR != 1 {print "CHECK TABLE "$1";"}' \
| mysql -p<password> -D<database>
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
I would recommend to use date->diff function, as in example below:
$dStart = new DateTime('2012-07-26');
$dEnd = new DateTime('2012-08-26');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater
Place this on your model:
[DisplayName("Electric Fan")]
public bool ElectricFan { get; set; }
private string electricFanRate;
public string ElectricFanRate
{
get { return electricFanRate ?? (electricFanRate = "$15/month"); }
set { electricFanRate = value; }
}
And this in your cshtml:
<div class="row">
@Html.CheckBoxFor(m => m.ElectricFan, new { @class = "" })
@Html.LabelFor(m => m.ElectricFan, new { @class = "" })
@Html.DisplayTextFor(m => m.ElectricFanRate)
</div>
Which will output this:
If you click on the checkbox or the bold label it will check/uncheck the checkbox
Just by using select select
you can select particular columns, give them readable names and cast them. For example like this:
spark.read.csv(path).select(
'_c0.alias("stn").cast(StringType),
'_c1.alias("wban").cast(StringType),
'_c2.alias("lat").cast(DoubleType),
'_c3.alias("lon").cast(DoubleType)
)
.where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)
Below are scripts for emptying and deleting a Kafka topic assuming localhost as the zookeeper server and Kafka_Home is set to the install directory:
The script below will empty a topic by setting its retention time to 1 second and then removing the configuration:
#!/bin/bash
echo "Enter name of topic to empty:"
read topicName
/$Kafka_Home/bin/kafka-configs --zookeeper localhost:2181 --alter --entity-type topics --entity-name $topicName --add-config retention.ms=1000
sleep 5
/$Kafka_Home/bin/kafka-configs --zookeeper localhost:2181 --alter --entity-type topics --entity-name $topicName --delete-config retention.ms
To fully delete topics you must stop any applicable kafka broker(s) and remove it's directory(s) from the kafka log dir (default: /tmp/kafka-logs) and then run this script to remove the topic from zookeeper. To verify it's been deleted from zookeeper the output of ls /brokers/topics should no longer include the topic:
#!/bin/bash
echo "Enter name of topic to delete from zookeeper:"
read topicName
/$Kafka_Home/bin/zookeeper-shell localhost:2181 <<EOF
rmr /brokers/topics/$topicName
ls /brokers/topics
quit
EOF
Tip: generate error.
declare @Day int, @Config_Node varchar(50)
set @Config_Node = 'value to trace'
set @Day = @Config_Node
You will get this message:
Conversion failed when converting the varchar value 'value to trace' to data type int.
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.
=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))
or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.
=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")
in earlier versions you need to repeat the VLOOKUP, e.g.
=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
There are two ways to do this, depending on your Bash version.
The classic and portable (Bash pre-4) way is:
cmd >> outfile 2>&1
A nonportable way, starting with Bash 4 is
cmd &>> outfile
(analog to &> outfile
)
For good coding style, you should
If your script already starts with #!/bin/sh
(no matter if intended or not), then the Bash 4 solution, and in general any Bash-specific code, is not the way to go.
Also remember that Bash 4 &>>
is just shorter syntax — it does not introduce any new functionality or anything like that.
The syntax is (beside other redirection syntax) described here: http://bash-hackers.org/wiki/doku.php/syntax/redirection#appending_redirected_output_and_error_output
With vuejs 2, you could use vue2-filters which does have other goodies as well.
npm install vue2-filters
import Vue from 'vue'
import Vue2Filters from 'vue2-filters'
Vue.use(Vue2Filters)
Then use it like so:
{{ amount | currency }} // 12345 => $12,345.00
You can use the following script:
var findclasses = _doc.DocumentNode.Descendants("div").Where(d =>
d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")
);
I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.
I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:
jQuery.param
JSON.stringify + encodeURIComponent
JSURL.stringify
clearly JSURL has the most optimized format for urlEncoding a js object.
the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.
Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.
JE
and JZ
are just different names for exactly the same thing: a
conditional jump when ZF
(the "zero" flag) is equal to 1.
(Similarly, JNE
and JNZ
are just different names for a conditional jump
when ZF
is equal to 0.)
You could use them interchangeably, but you should use them depending on what you are doing:
JZ
/JNZ
are more appropriate when you are explicitly testing
for something being equal to zero:
dec ecx
jz counter_is_now_zero
JE
and JNE
are more appropriate after a CMP
instruction:
cmp edx, 42
je the_answer_is_42
(A CMP
instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1
when the operands are equal
and ZF=0
when they're not.)
Now, after I was pointed in the right direction, here's my complete solution:
This is the middleware class which is executed on every incoming request and checks if the request has the correct credentials. If no credentials are present or if they are wrong, the service responds with a 401 Unauthorized error immediately.
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
string authHeader = context.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':');
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
if(username == "test" && password == "test" )
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
else
{
// no authorization header
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
}
The middleware extension needs to be called in the Configure method of the service Startup class
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseMvc();
}
And that's all! :)
A very good resource for middleware in .Net Core and authentication can be found here: https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/
Thank God, Microsoft got that figured out in WPF :)
Every Control
, like a progress bar, button, form, etc. has a Dispatcher
on it. You can give the Dispatcher
an Action
that needs to be performed, and it will automatically call it on the correct thread (an Action
is like a function delegate).
You can find an example here.
Of course, you'll have to have the control accessible from other classes, e.g. by making it public
and handing a reference to the Window
to your other class, or maybe by passing a reference only to the progress bar.
If you set CURLINFO_HEADER_OUT
to true
, outgoing headers are available in the array returned by curl_getinfo()
, under request_header
key:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info['request_header']);
This will print:
GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*
Note the auth details are base64-encoded:
echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword
Also note that username and password need to be percent-encoded to escape any URL reserved characters (/
, ?
, &
, :
and so on) they might contain:
curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));
I second the pdfunite
recommendation. I was however getting Argument list too long
errors as I was attempting to merge > 2k PDF files.
I turned to Python for this and two external packages: PyPDF2 (to handle all things PDF related) and natsort (to do a "natural" sort of the directory's file names). In case this can help someone:
from PyPDF2 import PdfFileMerger
import natsort
import os
DIR = "dir-with-pdfs/"
OUTPUT = "output.pdf"
file_list = filter(lambda f: f.endswith('.pdf'), os.listdir(DIR))
file_list = natsort.natsorted(file_list)
# 'strict' used because of
# https://github.com/mstamy2/PyPDF2/issues/244#issuecomment-206952235
merger = PdfFileMerger(strict=False)
for f_name in file_list:
f = open(os.path.join(DIR, f_name), "rb")
merger.append(f)
output = open(OUTPUT, "wb")
merger.write(output)
You want to use the ParameterizedThreadStart
delegate for thread methods that take parameters. (Or none at all actually, and let the Thread
constructor infer.)
Example usage:
var thread = new Thread(new ParameterizedThreadStart(download));
//var thread = new Thread(download); // equivalent
thread.Start(filename)
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
Here you go. this should work.
questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7)
answerFrame.frame = CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)
For me, it was because I'd accidentally deleted my render
method !
I had a class with a componentWillReceiveProps
method I didn't need anymore, immediately preceding a short render
method. In my haste removing it, I accidentally removed the entire render
method as well.
This was a PAIN to track down, as I was getting console errors pointing at comments in completely irrelevant files as being the "source" of the problem.
Tomcat is merely an HTTP server and Java servlet container. JBoss and GlassFish are full-blown Java EE application servers, including an EJB container and all the other features of that stack. On the other hand, Tomcat has a lighter memory footprint (~60-70 MB), while those Java EE servers weigh in at hundreds of megs. Tomcat is very popular for simple web applications, or applications using frameworks such as Spring that do not require a full Java EE server. Administration of a Tomcat server is arguably easier, as there are fewer moving parts.
However, for applications that do require a full Java EE stack (or at least more pieces that could easily be bolted-on to Tomcat)... JBoss and GlassFish are two of the most popular open source offerings (the third one is Apache Geronimo, upon which the free version of IBM WebSphere is built). JBoss has a larger and deeper user community, and a more mature codebase. However, JBoss lags significantly behind GlassFish in implementing the current Java EE specs. Also, for those who prefer a GUI-based admin system... GlassFish's admin console is extremely slick, whereas most administration in JBoss is done with a command-line and text editor. GlassFish comes straight from Sun/Oracle, with all the advantages that can offer. JBoss is NOT under the control of Sun/Oracle, with all the advantages THAT can offer.
Go to installed updates and just uninstall Internet Explorer 11 Windows update. It works for me.
You cannot set inter-paragraph spacing in CSS using line-height, the spacing between <p>
blocks. That instead sets the intra-paragraph line spacing, the space between lines within a <p>
block. That is, line-height is the typographer's inter-line leading within the paragraph is controlled by line-height.
I presently do not know of any method in CSS to produce (for example) a 0.15em inter-<p>
spacing, whether using em or rem variants on any font property. I suspect it can be done with more complex floats or offsets. A pity this is necessary in CSS.
You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).
For example, if you wanted to use a DataTable:
ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
EDIT - More complete example
private void LoadSubjects()
{
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
adapter.Fill(subjects);
ddlSubject.DataSource = subjects;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
}
To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:
<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>
You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:
ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));
from the code-behind, or you'll have two "" items.
You can use the std::istream::getline() (or preferably the version that works on std::string) function to get an entire line. Both have versions that allow you to specify the delimiter (end of line character). The default for the string version is '\n'.
Both Python dict
(before Python 3.7) and JSON object are unordered collections. You could pass sort_keys
parameter, to sort the keys:
>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'
If you need a particular order; you could use collections.OrderedDict
:
>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'
Since Python 3.6, the keyword argument order is preserved and the above can be rewritten using a nicer syntax:
>>> json.dumps(OrderedDict(a=1, b=2))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict(b=2, a=1))
'{"b": 2, "a": 1}'
See PEP 468 – Preserving Keyword Argument Order.
If your input is given as JSON then to preserve the order (to get OrderedDict
), you could pass object_pair_hook
, as suggested by @Fred Yankowski:
>>> json.loads('{"a": 1, "b": 2}', object_pairs_hook=OrderedDict)
OrderedDict([('a', 1), ('b', 2)])
>>> json.loads('{"b": 2, "a": 1}', object_pairs_hook=OrderedDict)
OrderedDict([('b', 2), ('a', 1)])
I think this is what you are looking for.I does exactly what you asked for. Copy and Paste it in Notepad.Save as *.bat.Run.Enter Number.Multiply the process by 2 and thats the number of divisors.I made that on purpose so the it determine the divisors faster:
Pls note that a CMD varriable cant support values over 999999999
@echo off
modecon:cols=100 lines=100
:start
title Enter the Number to Determine
cls
echo Determine a number as a product of 2 numbers
echo.
echo Ex1 : C = A * B
echo Ex2 : 8 = 4 * 2
echo.
echo Max Number length is 9
echo.
echo If there is only 1 proces done it
echo means the number is a prime number
echo.
echo Prime numbers take time to determine
echo Number not prime are determined fast
echo.
set /p number=Enter Number :
if %number% GTR 999999999 goto start
echo.
set proces=0
set mindet=0
set procent=0
set B=%Number%
:Determining
set /a mindet=%mindet%+1
if %mindet% GTR %B% goto Results
set /a solution=%number% %%% %mindet%
if %solution% NEQ 0 goto Determining
if %solution% EQU 0 set /a proces=%proces%+1
set /a B=%number% / %mindet%
set /a procent=%mindet%*100/%B%
if %procent% EQU 100 set procent=%procent:~0,3%
if %procent% LSS 100 set procent=%procent:~0,2%
if %procent% LSS 10 set procent=%procent:~0,1%
title Progress : %procent% %%%
if %solution% EQU 0 echo %proces%. %mindet% * %B% = %number%
goto Determining
:Results
title %proces% Results Found
echo.
@pause
goto start
I was trying to do the same thing in Laravel 5.8 and got an error about calling pluck statically. For my solution I used the following. The collection clearly was called todoStatuses.
<div class="row mb-2">
<label for="status" class="mr-2">Status:</label>
{{ Form::select('status',
$todoStatuses->pluck('status', 'id'),
null,
['placeholder' => 'Status']) }}
</div>
if (!secondaryPassword.equals(initialPassword))
Use commons-io IOUtils.toByteArray(URL):
String url = "http://localhost:8080/images/anImage.jpg";
byte[] fileContent = IOUtils.toByteArray(new URL(url));
Maven dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Currently Angular CLI doesn't support an option to remove the component, you need to do it manually.
UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;
you might want to use CEIL()
if A
is always a floating point value > 0
and <= 2
You should have name column as a unique constraint. here is a 3 lines of code to change your issues
First find out the primary key constraints by typing this code
\d table_name
you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)
Drop the constraint:
ALTER TABLE table_name DROP CONSTRAINT some_constraint
Add a new primary key column with existing one:
ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
That's All.
In Ansible 2.x, you can use the block
for group of tasks:
- block:
- name: checkout repo
git:
repo: https://github.com/some/repo.git
version: master
dest: "{{ dst }}"
- name: change perms
file:
dest: "{{ dst }}"
state: directory
mode: 0755
owner: some_user
become: yes
become_user: some user
<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />
Excellent tool for cross-browser favicon - http://www.convertico.com/
Using this source code you can upload multiple file like google one by one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:
root:~# python -V
Python 3.5.2
root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.5 3 auto mode
1 /usr/bin/python2.7 2 manual mode
2 /usr/bin/python3.5 3 manual mode
root:~# update-alternatives --remove python /usr/bin/python3.5
root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
0 /usr/bin/python2.7 2 auto mode
* 1 /usr/bin/python2.7 2 manual mode
Press <enter> to keep the current choice[*], or type selection number: 0
root:~# python -V
Python 2.7.12
root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.
In PS 7, you can use ConvertFrom-SecureString
and -AsPlainText
:
$UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText
ConvertFrom-SecureString
[-SecureString] <SecureString>
[-AsPlainText]
[<CommonParameters>]
What is the difference?
From the documentation:
- - (Boolean)
instance_of?(class)
- Returns
true
ifobj
is an instance of the given class.
and:
- - (Boolean)
is_a?(class)
- (Boolean)kind_of?(class)
- Returns
true
ifclass
is the class ofobj
, or ifclass
is one of the superclasses ofobj
or modules included inobj
.
If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.
When should I use which?
Never. Use polymorphism instead.
Why are there so many of them?
I wouldn't call two "many". There are two of them, because they do two different things.
One thing I have observed regarding this error is that is appears only for the first response from the server, which in case of http should be the handshake response. Once an immediate response is sent from the server to the gateway, if after the main response takes time it does not give an error. The key here is that the first response on a request by a server should be fast.
isset() is fine for top level, but empty() is much more useful to find whether nested values are set. Eg:
if(isset($json['foo'] && isset($json['foo']['bar'])) {
$value = $json['foo']['bar']
}
Or:
if (!empty($json['foo']['bar']) {
$value = $json['foo']['bar']
}
If the structs only contain primitives or if you are interested in strict equality then you can do something like this:
int my_struct_cmp(const struct my_struct * lhs, const struct my_struct * rhs) { return memcmp(lhs, rsh, sizeof(struct my_struct)); }
However, if your structs contain pointers to other structs or unions then you will need to write a function that compares the primitives properly and make comparison calls against the other structures as appropriate.
Be aware, however, that you should have used memset(&a, sizeof(struct my_struct), 1) to zero out the memory range of the structures as part of your ADT initialization.
For a simple array, you have the union approach, but you can also use :
_.uniq([2, 1, 2]);
You can use stream
and flatMap
to map &
to &
String str = "begin&end";
String newString = str.chars()
.flatMap(ch -> (ch == '&') ? "&".chars() : IntStream.of(ch))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
All credits go to elian-ebbing
Just for the lazy ones here I also provide a customized version of the function for the format yyyy-mm-dd.
function isValidDate(dateString)
{
// First check for the pattern
var regex_date = /^\d{4}\-\d{1,2}\-\d{1,2}$/;
if(!regex_date.test(dateString))
{
return false;
}
// Parse the date parts to integers
var parts = dateString.split("-");
var day = parseInt(parts[2], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[0], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
{
return false;
}
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
{
monthLength[1] = 29;
}
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
}
As per your question requirement , I would like to suggest that Map will solve your problem very efficient and without any hassle.
In Map you can give the name as key and your original object as value.
Map<String,Cave> myMap=new HashMap<String,Cave>();
Why not just use key name on dictionary, C# has this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("UserID", "test");
string userIDFromDictionaryByKey = dict["UserID"];
If you look at the tip suggestion:
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
Scanner in = new Scanner (System.in);
/*Prints out the welcome message at the top of the screen */
System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
System.out.printf ("%55s", "=================================\n");
String[] codes =
{
"G22", "K13", "I30", "S20"};
System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
codes[3]);
System.out.printf ("Enter one of the above!\n");
String usercode = in.nextLine ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}
Simply use
SELECT @@VERSION
Sample output
Microsoft SQL Server 2012 - 11.0.2100.60 (X64)
Feb 10 2012 19:39:15
Copyright (c) Microsoft Corporation
Express Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
Source: How to check sql server version? (Various ways explained)
You can sort a map by value as below, more example here
//Sort a Map by their Value.
Map<Integer, String> random = new HashMap<Integer, String>();
random.put(1,"z");
random.put(6,"k");
random.put(5,"a");
random.put(3,"f");
random.put(9,"c");
Map<Integer, String> sortedMap =
random.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
Using background-size cover worked for me.
#footer {
background-color: #eee;
background-image: url(images/bodybgbottomleft.png);
background-repeat: no-repeat;
background-size: cover;
clear: both;
width: 100%;
margin: 0;
padding: 30px 0 0;
}
Obviously be aware of support issues, check Can I Use: http://caniuse.com/#search=background-size
try onsubmit="submit(); window.close()"
Try this
var gdate='01-05-2014';
date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
if(parseInt(date) < parseInt(Date.now()))
{
alert('small');
}else{
alert('big');
}
Regarding your second question about properties, you can use self.myView
only if you declared it as a property in class. Since myView
is a local variable, you can not use it that way. For more details on this, I would recommend you to go through the apple documentation on Declared Properties,
Those "anchors" that exist solely to provide a click event, but do not actually link to other content, should really be button elements because that's what they really are.
It can be styled like so:
<button style="border:none; background:transparent; cursor: pointer;">Click me</button>
And of course click events can be attached to buttons without worry of the browser jumping to the top, and without adding extraneous javascript such as onclick="return false;" or event.preventDefault() .
A simple and fairly efficient solution is to sort both collections and then compare them for equality:
bool equal = collection1.OrderBy(i => i).SequenceEqual(
collection2.OrderBy(i => i));
This algorithm is O(N*logN), while your solution above is O(N^2).
If the collections have certain properties, you may be able to implement a faster solution. For example, if both of your collections are hash sets, they cannot contain duplicates. Also, checking whether a hash set contains some element is very fast. In that case an algorithm similar to yours would likely be fastest.
I have implemented @satchmorun's suggestion here: https://github.com/andresesfm/angular-underscore-module
To use it:
Make sure you have included underscore.js in your project
<script src="bower_components/underscore/underscore.js">
Get it:
bower install angular-underscore-module
Add angular-underscore-module.js to your main file (index.html)
<script src="bower_components/angular-underscore-module/angular-underscore-module.js"></script>
Add the module as a dependency in your App definition
var myapp = angular.module('MyApp', ['underscore'])
To use, add as an injected dependency to your Controller/Service and it is ready to use
angular.module('MyApp').controller('MyCtrl', function ($scope, _) {
...
//Use underscore
_.each(...);
...
Try this below code
<?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file);
?>
Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.
In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.
The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new
keyword, and the context within that function (the this
keyword) will refer to the actual object instance where you call it.
Consider this example:
// constructor function
function MyClass () {
var privateVariable; // private member only available within the constructor fn
this.privilegedMethod = function () { // it can access private members
//..
};
}
// A 'static method', it's just like a normal function
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};
MyClass.prototype.publicMethod = function () {
// the 'this' keyword refers to the object instance
// you can access only 'privileged' and 'public' members
};
var myObj = new MyClass(); // new object instance
myObj.publicMethod();
MyClass.staticMethod();
You can try open MVG library, It can be used for multiple interfaces too.
The simplest is to call stop propagation on an event handler. $event
works the same in Angular 2, and contains the ongoing event (by it a mouse click, mouse event, etc.):
(click)="onEvent($event)"
on the event handler, we can there stop the propagation:
onEvent(event) {
event.stopPropagation();
}
socket.gethostname()
could do
For those with the problem of not working because you used "$(element).show()". I solved it the next way:
var textbox = $("#otherOption");
textbox.show("fast", function () {
textbox[0].focus();
});
So you dont need a timer, it will execute after the show method is completed.
You could use assign
, but using assign
(or get
) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.
with a list:
A <- lapply (1 : 10, function (x) d + rnorm (3))
with a matrix:
A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
Use these:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
My default has been:
find -type f | egrep -i "*.java|*.css|*.cs|*.sql"
Like the less process intencive find
execution by Brendan Long and Stephan202 et al.:
find Documents \( -name "*.py" -or -name "*.html" \)
I often have this problem with date fields (where comparison operators are very common).
To elaborate further on Mihai's answer, which I believe is a solid approach.
To the models you can add scopes like this:
scope :updated_at_less_than, -> (date_param) {
where(arel_table[:updated_at].lt(date_param)) }
... and then in your controller, or wherever you are using your model:
result = MyModel.updated_at_less_than('01/01/2017')
... a more complex example with joins looks like this:
result = MyParentModel.joins(:my_model).
merge(MyModel.updated_at_less_than('01/01/2017'))
A huge advantage of this approach is (a) it lets you compose your queries from different scopes and (b) avoids alias collisions when you join to the same table twice since arel_table will handle that part of the query generation.
Just use -p1
: you will need to use -p0
in the --no-prefix
case anyway, so you can just leave out the --no-prefix
and use -p1
:
$ git diff > save.patch
$ patch -p1 < save.patch
$ git diff --no-prefix > save.patch
$ patch -p0 < save.patch
Make an jInternalFrame into main frame and make it invisible. Then you can use it for further events.
jInternalFrame.setSize(300,150);
jInternalFrame.setVisible(true);
I catch all the exceptions and store it in database, so errors can be corrected easily - the page, place, date etc stored
try
{
Cart = DB.BuyOnlineCartMasters.Where(c => c.CmpyID == LoginID && c.Active == true).FirstOrDefault();
}
catch (Exception e)
{
ErrorReport.StoreError("CartMinifiedPartial-Company", e);
-- storing the error for reference
}
Storing
public static void StoreError(string ErrorPage, Exception e)
{
try
{
eDurar.Models.db_edurarEntities1 DB = new Models.db_edurarEntities1();
eDurar.Models.ErrorTable Err = new eDurar.Models.ErrorTable();
Err.ErrorPage = ErrorPage;
if (e.Message != null)
{
Err.ErrorDetails = e.Message;
}
if (e.InnerException != null)
{
Err.InnerException = e.InnerException.Message.ToString();
}
Err.Date = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
DB.ErrorTables.AddObject(Err);
DB.SaveChanges();
}
In this simple example you can just put synchronized
as a modifier after public
in both method signatures.
More complex scenarios require other stuff.
Your webapp has servletcontainer specific libraries like servlet-api.jar file in its /WEB-INF/lib. This is not right.
Remove them all.
The /WEB-INF/lib should contain only the libraries specific to the webapp, not to the servletcontainer. The servletcontainer (like Tomcat) is the one who should already provide the servletcontainer specific libraries.
If you supply libraries from an arbitrary servletcontainer of a different make/version, you'll run into this kind of problems because your webapp wouldn't be able to run on a servletcontainer of a different make/version than where those libraries are originated from.
How to solve: In Eclipse Right click on the project in eclipse Properties -> Java Build Path -> Add library -> Server Runtime Library -> Apache Tomcat
Im Maven Project:-
add follwing line in pom.xml file
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${default.javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${default.javax.servlet.jsp.version}</version>
<scope>provided</scope>
</dependency>
Well According to a comment on the shuf answer he shuffed 78 000 000 000 lines in under a minute.
Challenge accepted...
EDIT: I beat my own record
$ time ./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null
./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null 0.02s user 0.01s system 80% cpu 0.047 total
The reason it is so fast, well I don't read the whole file and just move the file pointer 10 times and print the line after the pointer.
First I needed a file of 78.000.000.000 lines:
seq 1 78 | xargs -n 1 -P 16 -I% seq 1 1000 | xargs -n 1 -P 16 -I% echo "" > lines_78000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000.txt > lines_78000000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000000.txt > lines_78000000000.txt
This gives me a a file with 78 Billion newlines ;-)
Now for the shuf part:
$ time shuf -n 10 lines_78000000000.txt
shuf -n 10 lines_78000000000.txt 2171.20s user 22.17s system 99% cpu 36:35.80 total
The bottleneck was CPU and not using multiple threads, it pinned 1 core at 100% the other 15 were not used.
Python is what I regularly use so that's what I'll use to make this faster:
#!/bin/python3
import random
f = open("lines_78000000000.txt", "rt")
count = 0
while 1:
buffer = f.read(65536)
if not buffer: break
count += buffer.count('\n')
for i in range(10):
f.readline(random.randint(1, count))
This got me just under a minute:
$ time ./shuf.py
./shuf.py 42.57s user 16.19s system 98% cpu 59.752 total
I did this on a Lenovo X1 extreme 2nd gen with the i9 and Samsung NVMe which gives me plenty read and write speed.
I know it can get faster but I'll leave some room to give others a try.
Line counter source: Luther Blissett
There is code and binaries available here for a console app that can export private keys marked as non-exportable, and it won't trigger antivirus apps like mimikatz will.
The code is based on a paper by the NCC Group.
will need to run the tool with the local system account, as it works by writing directly to memory used by Windows' lsass
process, in order to temporarily mark keys as exportable. This can be done using PsExec
from SysInternals' PsTools:
PsExec64.exe -s -i cmd
exportrsa.exe
Have you tried QCoreApplication::applicationDirPath()
qDebug() << "App path : " << qApp->applicationDirPath();
The CGI is specified in RFC 3875, though that is a later "official" codification of the original NCSA document. Basically, CGI defines a protocol to pass data about a HTTP request from a webserver to a program to process - any program, in any language. At the time the spec was written (1993), most web servers contained only static pages, "web apps" were a rare and new thing, so it seemed natural to keep them apart from the "normal" static content, such as in a cgi-bin
directory apart from the static content, and having them end in .cgi
.
At this time, here also were no dedicated "web programming languages" like PHP, and C was the dominating portable programming language - so many people wrote their CGI scripts in C. But Perl quickly turned out to be a better fit for this kind of thing, and CGI became almost synonymous with Perl for a while. Then there came Java Servlets, PHP and a bunch of others and took over large parts of Perl's market share.
Essentially console.log("Put a message here.")
if the browser has a supporting console.
Another typical debugging method is using alerts, alert("Put a message here.")
RE: Update II
This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.
Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print()
method for evaluating expressions and printing them out. Checkout this documentation.
These links might be of interest to you.
You just need to add this line to the window there:
exec (your stored proc name) (and possibly add parameters)
What is your stored proc called, and what parameters does it expect?
Heres a good one with NSRegularExpression that's working for me.
[text rangeOfString:@"^.+@.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;
You can insert whatever regex you want but I like being able to do it in one line.
What really worked to me: (source: oracle documentation "reading url")
import java.net.*;
import java.io.*;
public class UrlTextfile {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://yoursite.com/yourfile.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
You're getting the error because result
defined as Sequential()
is just a container for the model and you have not defined an input for it.
Given what you're trying to build set result
to take the third input x3
.
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))
# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])
# then concatenate the two outputs
result = Concatenate([merged, third])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
However, my preferred way of building a model that has this type of input structure would be to use the functional api.
Here is an implementation of your requirements to get you started:
from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad
first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)
second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)
merge_one = concatenate([first_dense, second_dense])
third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])
model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
To answer the question in the comments:
Concatenation works like this:
a b c
a b c g h i a b c g h i
d e f j k l d e f j k l
i.e rows are just joined.
x1
is input to first, x2
is input into second and x3
input into third.CLOCK_REALTIME
is affected by NTP, and can move forwards and backwards. CLOCK_MONOTONIC
is not, and advances at one tick per tick.
You can find these method usefull in reading and writing data in android.
public void saveData(View view) {
String text = "This is the text in the file, this is the part of the issue of the name and also called the name od the college ";
FileOutputStream fos = null;
try {
fos = openFileOutput("FILE_NAME", MODE_PRIVATE);
fos.write(text.getBytes());
Toast.makeText(this, "Data is saved "+ getFilesDir(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos!= null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void logData(View view) {
FileInputStream fis = null;
try {
fis = openFileInput("FILE_NAME");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb= new StringBuilder();
String text;
while((text = br.readLine()) != null){
sb.append(text).append("\n");
Log.e("TAG", text
);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Maybe what you want is just plain old predefined variables.
Consider trying
$_SERVER['REQUEST_URI'']
Or read more here.
Rather Cast It to an Object Array.
Object obj2 = from some source . . ;
Object[] objects=(Object[])obj2;
Or you could catch a failed attempt to cast into E eg.
public int indexOf(Object arg0){
try{
E test=(E)arg0;
return doStuff(test);
}catch(ClassCastException e){
return -1;
}
}
There is a bundled collection of Vim plugins for Python development: http://www.vim.org/scripts/script.php?script_id=3770
Short story: The 0
tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x
is an arbitrary choice.
Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).
The BCPL language used the syntax 8 1234
for octal numbers. When Ken Thompson created B from BCPL, he used the 0
prefix instead. This is great because
0
is the same in both bases),00005 == 05
), and#123
).When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x
was arbitrarily chosen (00
was probably ruled out as awkward).
C# is a descendant of C, so it inherits the syntax.
I use "xor" (it seems it's a keyword; in Code::Blocks at least it gets bold) just as you can use "and" instead of &&
and "or" instead of ||
.
if (first xor second)...
Yes, it is bitwise. Sorry.
From SQL Server 2008 Setup, you have to select "Client Tools Connectivity" to install SQL Server Configuration Manager.
Very Simple Example below:
Hope it helps.
String str = "Hello I'm your String";
String[] splited = str.split(" ");
var splited = str.split(" ");
var splited1=splited[0]; //Hello
var splited2=splited[1]; //I'm
var splited3=splited[2]; //your
var splited4=splited[3]; //String
To read the html file from server using http
module. This is one way to read file from server. If you want to get it on console just remove http
module declaration.
var http = require('http');_x000D_
var fs = require('fs');_x000D_
var server = http.createServer(function(req, res) {_x000D_
fs.readFile('HTMLPage1.html', function(err, data) {_x000D_
if (!err) {_x000D_
res.writeHead(200, {_x000D_
'Content-Type': 'text/html'_x000D_
});_x000D_
res.write(data);_x000D_
res.end();_x000D_
} else {_x000D_
console.log('error');_x000D_
}_x000D_
});_x000D_
});_x000D_
server.listen(8000, function(req, res) {_x000D_
console.log('server listening to localhost 8000');_x000D_
});
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<h1>My Header</h1>_x000D_
<p>My paragraph.</p>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc:
export LC_ALL=C
then type source .bashrc
Now you don't need to call this command manually every time, when you connecting via ssh for example.
As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as.
grant SELECT on TABLE_NAME to READ_USERNAME;
I usually do this in the thread handling the json response:
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
Remove all widths set using CSS and set white-space to nowrap like so:
.content-loader tr td {
white-space: nowrap;
}
I would also remove the fixed width from the container (or add overflow-x: scroll
to the container) if you want the fields to display in their entirety without it looking odd...
See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp
If variable1
is a string, and you are searching for a substring in it, this should work:
when: '"value" in variable1'
if variable1
is an array or dict instead, in
will search for the exact string as one of its items.
If you want to use small inline commands in the onclick tag you could go with something like this.
<button id="" class="delete" onclick="javascript:if(confirm('Are you sure you want to delete this entry?')){jQuery(this).parent().remove(); return false;}" type="button">
Delete
</button>
Add the border to each cell with this:
table > tbody > tr > td { border: 1px solid rgba(255, 255, 255, 0.1); }
Remove the top border from all the cells in the first row:
table > tbody > tr:first-child > td { border-top: 0; }
Remove the left border from the cells in the first column:
table > tbody > tr > td:first-child { border-left: 0; }
Remove the right border from the cells in the last column:
table > tbody > tr > td:last-child { border-right: 0; }
Remove the bottom border from the cells in the last row:
table > tbody > tr:last-child > td { border-bottom: 0; }
result_array()
returns Associative Array type data. Returning pure array is slightly faster than returning an array of objects. result()
is recursive in that it returns an std class object where as result_array()
just returns a pure array, so result_array()
would be choice regarding performance.
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'¶m='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.
What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.
Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.
Like follow:
switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
alert('10');
break;
case (cnt >= 21 && cnt <= 30 && cnt):
alert('21');
break;
case (cnt >= 31 && cnt <= 40 && cnt):
alert('31');
break;
default:
alert('>41');
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>
_x000D_
It is likely you will have to pull the text file into memory and then do the replacements. You will then have to overwrite the file using the method you clearly know about. So you would first:
// Read lines from source file.
string[] arr = File.ReadAllLines(file);
YOu can then loop through and replace the text in the array.
var writer = new StreamWriter(GetFileName(baseFolder, prefix, num));
for (int i = 0; i < arr.Length; i++)
{
string line = arr[i];
line.Replace("match", "new value");
writer.WriteLine(line);
}
this method gives you some control on the manipulations you can do. Or, you can merely do the replace in one line
File.WriteAllText("test.txt", text.Replace("match", "new value"));
I hope this helps.
You could set your _JAVA_OPTIONS
environmental variable. For example in bash this would do the trick:
export _JAVA_OPTIONS=-Djava.io.tmpdir=/new/tmp/dir
I put that into my bash login script and it seems to do the trick.
I really hate forms which don't tell me what input(s) is/are missing. So I improve the Dominic's answer - thanks for this.
In the css file set the "borderR" class to border has red color.
$('#<form_id>').submit(function () {
var allIsOk = true;
// Check if empty of not
$(this).find( 'input[type!="hidden"]' ).each(function () {
if ( ! $(this).val() ) {
$(this).addClass('borderR').focus();
allIsOk = false;
}
});
return allIsOk
});
Why to use regex? PHP has some built in functionality to do that
<?php
$valid_symbols = array('-', '_');
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
echo "String 1 not acceptable acceptable";
}
?>
preg_match('/\s/',$username)
will check for blank space
!ctype_alnum(str_replace($valid_symbols, '', $string1))
will check for valid_symbols
Per this other post: Insert all values of a..., you can do the following:
INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
It's important to specify the column names as indicated by the other answers.
Only this code works for me
/usr/local/mysql/bin/mysql -V
In my case when I use something like result.class.name
I got something like Module1::class_name
. But if we only want class_name
, use
result.class.table_name.singularize
Turning on tethering actually allowed me to install and debug on a LG device and it was the only way it would work
Here is a one line lambda that also works:
df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)
Input:
searchfor = ['og', 'at']
df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])
col1 col2
0 cat 1000.0
1 hat 2000000.0
2 dog 1000.0
3 fog 330000.0
4 pet 330000.0
Apply Lambda:
df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)
Output:
col1 col2 TrueFalse
0 cat 1000.0 1
1 hat 2000000.0 1
2 dog 1000.0 1
3 fog 330000.0 1
4 pet 330000.0 0
You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.
class Book {
public BookId: number;
public Title: string;
public Author: string;
public Price: number;
public Description: string;
}
var bks: Book[] = [];
bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"}); //This is all done in JSON.
Dim x As Integer = 0
Dim y As Integer = 0
Dim k = 0
Dim l = 0
Dim bm As New Bitmap(p1.Image)
Dim om As New Bitmap(p1.Image.Width, p1.Image.Height)
Dim r, g, b As Byte
Do While x < bm.Width - 1
y = 0
l = 0
Do While y < bm.Height - 1
r = 255 - bm.GetPixel(x, y).R
g = 255 - bm.GetPixel(x, y).G
b = 255 - bm.GetPixel(x, y).B
om.SetPixel(k, l, Color.FromArgb(r, g, b))
y += 3
l += 1
Loop
x += 3
k += 1
Loop
p2.Image = om
This is my solution, feedback is welcome.. :)
$('input').keydown( function (event) { //event==Keyevent
if(event.which == 13) {
var inputs = $(this).closest('form').find(':input:visible');
inputs.eq( inputs.index(this)+ 1 ).focus();
event.preventDefault(); //Disable standard Enterkey action
}
// event.preventDefault(); <- Disable all keys action
});
Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.
String.split()
can provide you with a replacement for explode()
For a replacement of implode()
I'd advice you to write either a custom function or use Apache Commons's StringUtils.join()
functions.
There are many good scripts above for generating insert statements, but I attempted one of my own to make it as user friendly as possible and to also be able to do UPDATE statements. + package the result ready for .sql files that can be stored by date.
It takes as input your normal SELECT statement with WHERE clause, then outputs a list of Insert statements and update statements. Together they form a sort of IF NOT EXISTS () INSERT ELSE UPDATE It is handy too when there are non-updatable columns that need exclusion from the final INSERT/UPDATE statement.
Another thing that below script can do is: it can even handle INNER JOINs with other tables as input statement for the stored proc. It can be handy as a poor man's Release management tool that sits right at your finger tips where you are typing the sql SELECT statements all day.
original post : Generate UPDATE statement in SQL Server for specific table
CREATE PROCEDURE [dbo].[sp_generate_updates] (
@fullquery nvarchar(max) = '',
@ignore_field_input nvarchar(MAX) = '',
@PK_COLUMN_NAME nvarchar(MAX) = ''
)
AS
SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
/*
-- For Standard USAGE: (where clause is mandatory)
EXEC [sp_generate_updates] 'select * from dbo.mytable where mytext=''1'' '
OR
SET QUOTED_IDENTIFIER OFF
EXEC [sp_generate_updates] "select * from dbo.mytable where mytext='1' "
-- For ignoring specific columns (to ignore in the UPDATE and INSERT SQL statement)
EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1 ' , 'Column01,Column02'
-- For just updates without insert statement (replace the * )
EXEC [sp_generate_updates] 'select Column01, Column02 from dbo.mytable where 1=1 '
-- For tables without a primary key: construct the key in the third variable
EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1 ' ,'','your_chosen_primary_key_Col1,key_Col2'
-- For complex updates with JOINED tables
EXEC [sp_generate_updates] 'select o1.Name, o1.category, o2.name+ '_hello_world' as #name
from overnightsetting o1
inner join overnightsetting o2 on o1.name=o2.name
where o1.name like '%appserver%'
(REMARK about above: the use of # in front of a column name (so #abc) can do an update of that columname (abc) with any column from an inner joined table where you use the alias #abc )
-------------README for the deeper interested person:
Goal of the Stored PROCEDURE is to get updates from simple SQL SELECT statements. It is made ot be simple but fast and powerfull. As always => power is nothing without control, so check before you execute.
Its power sits also in the fact that you can make insert statements, so combined gives you a "IF NOT EXISTS() INSERT " capability.
The scripts work were there are primary keys or identity columns on table you want to update (/ or make inserts for).
It will also works when no primary keys / identity column exist(s) and you define them yourselve. But then be carefull (duplicate hits can occur). When the table has a primary key it will always be used.
The script works with a real temporary table, made on the fly (APPROPRIATE RIGHTS needed), to put the values inside from the script, then add 3 columns for constructing the "insert into tableX (...) values ()" , and the 2 update statement.
We work with temporary structures like "where columnname = {Columnname}" and then later do the update on that temptable for the columns values found on that same line.
example "where columnname = {Columnname}" for birthdate becomes "where birthdate = {birthdate}" an then we find the birthdate value on that line inside the temp table.
So then the statement becomes "where birthdate = {19800417}"
Enjoy releasing scripts as of now... by Pieter van Nederkassel - freeware "CC BY-SA" (+use at own risk)
*/
IF OBJECT_ID('tempdb..#ignore','U') IS NOT NULL DROP TABLE #ignore
DECLARE @stringsplit_table TABLE (col nvarchar(255), dtype nvarchar(255)) -- table to store the primary keys or identity key
DECLARE @PK_condition nvarchar(512), -- placeholder for WHERE pk_field1 = pk_value1 AND pk_field2 = pk_value2 AND ...
@pkstring NVARCHAR(512), -- sting to store the primary keys or the idendity key
@table_name nvarchar(512), -- (left) table name, including schema
@table_N_where_clause nvarchar(max), -- tablename
@table_alias nvarchar(512), -- holds the (left) table alias if one available, else @table_name
@table_schema NVARCHAR(30), -- schema of @table_name
@update_list1 NVARCHAR(MAX), -- placeholder for SET fields section of update
@update_list2 NVARCHAR(MAX), -- placeholder for SET fields section of update value comming from other tables in the join, other than the main table to update => updateof base table possible with inner join
@list_all_cols BIT = 0, -- placeholder for values for the insert into table VALUES command
@select_list NVARCHAR(MAX), -- placeholder for SELECT fields of (left) table
@COLUMN_NAME NVARCHAR(255), -- will hold column names of the (left) table
@sql NVARCHAR(MAX), -- sql statement variable
@getdate NVARCHAR(17), -- transform getdate() to YYYYMMDDHHMMSSMMM
@tmp_table NVARCHAR(255), -- will hold the name of a physical temp table
@pk_separator NVARCHAR(1), -- separator used in @PK_COLUMN_NAME if provided (only checking obvious ones ,;|-)
@COLUMN_NAME_DATA_TYPE NVARCHAR(100), -- needed for insert statements to convert to right text string
@own_pk BIT = 0 -- check if table has PK (0) or if provided PK will be used (1)
set @ignore_field_input=replace(replace(replace(@ignore_field_input,' ',''),'[',''),']','')
set @PK_COLUMN_NAME= replace(replace(replace(@PK_COLUMN_NAME, ' ',''),'[',''),']','')
-- first we remove all linefeeds from the user query
set @fullquery=replace(replace(replace(@fullquery,char(10),''),char(13),' '),' ',' ')
set @table_N_where_clause=@fullquery
if charindex ('order by' , @table_N_where_clause) > 0
print ' WARNING: ORDER BY NOT ALLOWED IN UPDATE ...'
if @PK_COLUMN_NAME <> ''
select ' WARNING: IF you select your own primary keys, make double sure before doing the update statements below!! '
--print @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) = 0
set @table_N_where_clause= 'select * from ' + @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) > 0
exec (@table_N_where_clause)
set @table_N_where_clause=rtrim(ltrim(substring(@table_N_where_clause,CHARINDEX(' from ', @table_N_where_clause )+6, 4000)))
--print @table_N_where_clause
set @table_name=left(@table_N_where_clause,CHARINDEX(' ', @table_N_where_clause )-1)
IF CHARINDEX('where ', @table_N_where_clause) > 0 SELECT @table_alias = LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(@table_N_where_clause,1, CHARINDEX('where ', @table_N_where_clause )-1),'(nolock)',''),@table_name,'')))
IF CHARINDEX('join ', @table_alias) > 0 SELECT @table_alias = SUBSTRING(@table_alias, 1, CHARINDEX(' ', @table_alias)-1) -- until next space
IF LEN(@table_alias) = 0 SELECT @table_alias = @table_name
IF (charindex (' *' , @fullquery) > 0 or charindex (@table_alias+'.*' , @fullquery) > 0 ) set @list_all_cols=1
/*
print @fullquery
print @table_alias
print @table_N_where_clause
print @table_name
*/
-- Prepare PK condition
SELECT @table_schema = CASE WHEN CHARINDEX('.',@table_name) > 0 THEN LEFT(@table_name, CHARINDEX('.',@table_name)-1) ELSE 'dbo' END
SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND i1.TABLE_SCHEMA = @table_schema
-- if no primary keys exist then we try for identity columns
IF @PK_condition is null SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
IF @pkstring is null SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
-- Same but in form of a table
INSERT INTO @stringsplit_table
SELECT 'pk_'+i1.COLUMN_NAME as col, i2.DATA_TYPE as dtype
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
inner join INFORMATION_SCHEMA.COLUMNS i2
on i1.TABLE_NAME = i2.TABLE_NAME AND i1.TABLE_SCHEMA = i2.TABLE_SCHEMA
WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND i1.TABLE_SCHEMA = @table_schema
-- if no primary keys exist then we try for identity columns
IF 0=(select count(*) from @stringsplit_table) INSERT INTO @stringsplit_table
SELECT 'pk_'+i2.COLUMN_NAME as col, i2.DATA_TYPE as dtype
FROM INFORMATION_SCHEMA.COLUMNS i2
WHERE COLUMNPROPERTY(object_id(i2.TABLE_SCHEMA+'.'+i2.TABLE_NAME), i2.COLUMN_NAME, 'IsIdentity') = 1
AND i2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND i2.TABLE_SCHEMA = @table_schema
-- NOW handling the primary key given as parameter to the main batch
SELECT @pk_separator = ',' -- take this as default, we'll check lower if it's a different one
IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME <> ''
BEGIN
IF CHARINDEX(';', @PK_COLUMN_NAME) > 0
SELECT @pk_separator = ';'
ELSE IF CHARINDEX('|', @PK_COLUMN_NAME) > 0
SELECT @pk_separator = '|'
ELSE IF CHARINDEX('-', @PK_COLUMN_NAME) > 0
SELECT @pk_separator = '-'
SELECT @PK_condition = NULL -- make sure to make it NULL, in case it was ''
INSERT INTO @stringsplit_table
SELECT LTRIM(RTRIM(x.value)) , 'datetime' FROM STRING_SPLIT(@PK_COLUMN_NAME, @pk_separator) x
SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME(x.col) + ' = ' + replace(QUOTENAME(x.col,'{'),'{','{pk_')
FROM @stringsplit_table x
SELECT @PK_COLUMN_NAME = NULL -- make sure to make it NULL, in case it was ''
SELECT @PK_COLUMN_NAME = ISNULL(@PK_COLUMN_NAME + ', ', '') + QUOTENAME(x.col) + ' as pk_' + x.col
FROM @stringsplit_table x
--print 'pkcolumns '+ isnull(@PK_COLUMN_NAME,'')
update @stringsplit_table set col='pk_' + col
SELECT @own_pk = 1
END
ELSE IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME = ''
BEGIN
RAISERROR('No Primary key or Identity column available on table. Add some columns as the third parameter when calling this SP to make your own temporary PK., also remove [] from tablename',17,1)
END
-- IF there are no primary keys or an identity key in the table active, then use the given columns as a primary key
if isnull(@pkstring,'') = '' set @pkstring = @PK_COLUMN_NAME
IF ISNULL(@pkstring, '') <> '' SELECT @fullquery = REPLACE(@fullquery, 'SELECT ','SELECT ' + @pkstring + ',' )
--print @pkstring
-- ignore fields for UPDATE STATEMENT (not ignored for the insert statement, in iserts statement we ignore only identity Columns and the columns provided with the main stored proc )
-- Place here all fields that you know can not be converted to nvarchar() values correctly, an thus should not be scripted for updates)
-- for insert we will take these fields along, although they will be incorrectly represented!!!!!!!!!!!!!.
SELECT ignore_field = 'uniqueidXXXX' INTO #ignore
UNION ALL SELECT ignore_field = 'UPDATEMASKXXXX'
UNION ALL SELECT ignore_field = 'UIDXXXXX'
UNION ALL SELECT value FROM string_split(@ignore_field_input,@pk_separator)
SELECT @getdate = REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(30), GETDATE(), 121), '-', ''), ' ', ''), ':', ''), '.', '')
SELECT @tmp_table = 'Release_DATA__' + @getdate + '__' + REPLACE(@table_name,@table_schema+'.','')
SET @sql = replace( @fullquery, ' from ', ' INTO ' + @tmp_table +' from ')
----print (@sql)
exec (@sql)
SELECT @sql = N'alter table ' + @tmp_table + N' add update_stmt1 nvarchar(max), update_stmt2 nvarchar(max) , update_stmt3 nvarchar(max)'
EXEC (@sql)
-- Prepare update field list (only columns from the temp table are taken if they also exist in the base table to update)
SELECT @update_list1 = ISNULL(@update_list1 + ', ', '') +
CASE WHEN C1.COLUMN_NAME = 'ModifiedBy' THEN '[ModifiedBy] = left(right(replace(CONVERT(VARCHAR(19),[Modified],121),''''-'''',''''''''),19) +''''-''''+right(SUSER_NAME(),30),50)'
WHEN C1.COLUMN_NAME = 'Modified' THEN '[Modified] = GETDATE()'
ELSE QUOTENAME(C1.COLUMN_NAME) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
END
FROM INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2
on c1.COLUMN_NAME =c2.COLUMN_NAME and c2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') AND c2.TABLE_SCHEMA = @table_schema
WHERE c1.TABLE_NAME = @tmp_table --REPLACE(@table_name,@table_schema+'.','')
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND COLUMNPROPERTY(object_id(c2.TABLE_SCHEMA+'.'+c2.TABLE_NAME), c2.COLUMN_NAME, 'IsIdentity') <> 1
AND NOT EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku
WHERE 1 = 1
AND ku.TABLE_NAME = c2.TABLE_NAME
AND ku.TABLE_SCHEMA = c2.TABLE_SCHEMA
AND ku.COLUMN_NAME = c2.COLUMN_NAME
AND OBJECTPROPERTY(OBJECT_ID(ku.CONSTRAINT_SCHEMA + '.' + QUOTENAME(ku.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1)
AND NOT EXISTS (SELECT 1 FROM @stringsplit_table x WHERE x.col = c2.COLUMN_NAME AND @own_pk = 1)
-- Prepare update field list (here we only take columns that commence with a #, as this is our queue for doing the update that comes from an inner joined table)
SELECT @update_list2 = ISNULL(@update_list2 + ', ', '') + QUOTENAME(replace( C1.COLUMN_NAME,'#','')) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS c1
WHERE c1.TABLE_NAME = @tmp_table --AND c1.TABLE_SCHEMA = @table_schema
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND c1.COLUMN_NAME like '#%'
-- similar for select list, but take all fields
SELECT @select_list = ISNULL(@select_list + ', ', '') + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')
AND TABLE_SCHEMA = @table_schema
AND COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') <> 1 -- Identity columns are filled automatically by MSSQL, not needed at Insert statement
AND QUOTENAME(c.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
SELECT @PK_condition = REPLACE(@PK_condition, '[pk_', '[')
set @select_list='if not exists (select * from '+ REPLACE(@table_name,@table_schema+'.','') +' where '+ @PK_condition +') INSERT INTO '+ REPLACE(@table_name,@table_schema+'.','') + '('+ @select_list + ') VALUES (' + replace(replace(@select_list,'[','{'),']','}') + ')'
SELECT @sql = N'UPDATE ' + @tmp_table + ' set update_stmt1 = ''' + @select_list + ''''
if @list_all_cols=1 EXEC (@sql)
--print 'select========== ' + @select_list
--print 'update========== ' + @update_list1
SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt2 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name +
N' SET ' + @update_list1 + N''' + ''' +
N' WHERE ' + @PK_condition + N''') '
EXEC (@sql)
--print @sql
SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt3 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name +
N' SET ' + @update_list2 + N''' + ''' +
N' WHERE ' + @PK_condition + N''') '
EXEC (@sql)
--print @sql
-- LOOPING OVER ALL base tables column for the INSERT INTO .... VALUES
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = (CASE WHEN @list_all_cols=0 THEN @tmp_table ELSE REPLACE(@table_name,@table_schema+'.','') END )
AND TABLE_SCHEMA = @table_schema
UNION--pned
SELECT col, 'datetime' FROM @stringsplit_table
OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @sql =
CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)), '''''''','''''''''''') + '''''''', ''NULL'')) '
ELSE
N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
END
----PRINT @sql
EXEC (@sql)
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns
--SELECT col FROM @stringsplit_table -- these are the primary keys
-- LOOPING OVER ALL temp tables column for the Update values
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
SELECT COLUMN_NAME,DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @tmp_table -- AND TABLE_SCHEMA = @table_schema
UNION--pned
SELECT col, 'datetime' FROM @stringsplit_table
OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @sql =
CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)), '''''''','''''''''''') + '''''''', ''NULL'')) '
WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
THEN N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)), '''''''','''''''''''') + '''''''', ''NULL'')) '
ELSE
N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])), '''''''','''''''''''') + '''''''', ''NULL'')) '
END
EXEC (@sql)
----print @sql
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns
SET @sql = 'Select * from ' + @tmp_table + ';'
--exec (@sql)
SELECT @sql = N'
IF OBJECT_ID(''' + @tmp_table + N''', ''U'') IS NOT NULL
BEGIN
SELECT ''USE ' + DB_NAME() + ''' as executelist
UNION ALL
SELECT ''GO '' as executelist
UNION ALL
SELECT '' /*PRESCRIPT CHECK */ ' + replace(@fullquery,'''','''''')+''' as executelist
UNION ALL
SELECT update_stmt1 as executelist FROM ' + @tmp_table + N' where update_stmt1 is not null
UNION ALL
SELECT update_stmt2 as executelist FROM ' + @tmp_table + N' where update_stmt2 is not null
UNION ALL
SELECT isnull(update_stmt3, '' add more columns inn query please'') as executelist FROM ' + @tmp_table + N' where update_stmt3 is not null
UNION ALL
SELECT ''--EXEC usp_AddInstalledScript 5, 5, 1, 1, 1, ''''' + @tmp_table + '.sql'''', 2 '' as executelist
UNION ALL
SELECT '' /*VERIFY WITH: */ ' + replace(@fullquery,'''','''''')+''' as executelist
UNION ALL
SELECT ''-- SCRIPT LOCATION: F:\CopyPaste\++Distributionpoint++\Release_Management\' + @tmp_table + '.sql'' as executelist
END'
exec (@sql)
SET @sql = 'DROP TABLE ' + @tmp_table + ';'
exec (@sql)
I had this same problem in asp.net mvc, I fixed it by putting this method in my base api controller that all my api controllers inherit from:
/// <summary>
/// Get the session from HttpContext.Current, if that is null try to get it from the Request properties.
/// </summary>
/// <returns></returns>
protected HttpContextWrapper GetHttpContextWrapper()
{
HttpContextWrapper httpContextWrapper = null;
if (HttpContext.Current != null)
{
httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
}
else if (Request.Properties.ContainsKey("MS_HttpContext"))
{
httpContextWrapper = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
}
return httpContextWrapper;
}
Then in your api call that you want to access the session you just do:
HttpContextWrapper httpContextWrapper = GetHttpContextWrapper();
var someVariableFromSession = httpContextWrapper.Session["SomeSessionValue"];
I also have this in my Global.asax.cs file like other people have posted, not sure if you still need it using the method above, but here it is just in case:
/// <summary>
/// The following method makes Session available.
/// </summary>
protected void Application_PostAuthorizeRequest()
{
if (HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api"))
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
You could also just make a custom filter attribute that you can stick on your api calls that you need session, then you can use session in your api call like you normally would via HttpContext.Current.Session["SomeValue"]:
/// <summary>
/// Filter that gets session context from request if HttpContext.Current is null.
/// </summary>
public class RequireSessionAttribute : ActionFilterAttribute
{
/// <summary>
/// Runs before action
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (HttpContext.Current == null)
{
if (actionContext.Request.Properties.ContainsKey("MS_HttpContext"))
{
HttpContext.Current = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).ApplicationInstance.Context;
}
}
}
}
Hope this helps.
As mentioned by Dan Abramov
Do it right inside render
We actually use that approach with memoise one for any kind of proxying props to state calculations.
Our code looks this way
// ./decorators/memoized.js
import memoizeOne from 'memoize-one';
export function memoized(target, key, descriptor) {
descriptor.value = memoizeOne(descriptor.value);
return descriptor;
}
// ./components/exampleComponent.js
import React from 'react';
import { memoized } from 'src/decorators';
class ExampleComponent extends React.Component {
buildValuesFromProps() {
const {
watchedProp1,
watchedProp2,
watchedProp3,
watchedProp4,
watchedProp5,
} = this.props
return {
value1: buildValue1(watchedProp1, watchedProp2),
value2: buildValue2(watchedProp1, watchedProp3, watchedProp5),
value3: buildValue3(watchedProp3, watchedProp4, watchedProp5),
}
}
@memoized
buildValue1(watchedProp1, watchedProp2) {
return ...;
}
@memoized
buildValue2(watchedProp1, watchedProp3, watchedProp5) {
return ...;
}
@memoized
buildValue3(watchedProp3, watchedProp4, watchedProp5) {
return ...;
}
render() {
const {
value1,
value2,
value3
} = this.buildValuesFromProps();
return (
<div>
<Component1 value={value1}>
<Component2 value={value2}>
<Component3 value={value3}>
</div>
);
}
}
The benefits of it are that you don't need to code tons of comparison boilerplate inside getDerivedStateFromProps
or componentWillReceiveProps
and you can skip copy-paste initialization inside a constructor.
NOTE:
This approach is used only for proxying the props to state, in case you have some inner state logic it still needs to be handled in component lifecycles.
Don't forget, if any functions that are called in your function and their prototypes must be situated above your function in the code otherwise the compiler might not find them before it attempts to compile your function. This will generate the error in question.
Do NOT eval. use a real parser, i.e., from json.org
Just use.
$('input[name="name_of_your_radiobutton"]:checked').val();
So easy it is.
If you have a pandas dataframe and want to preserve the dtypes, even the categoricals, this is a fast way to do it:
import numpy as np
import pandas as pd
df = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})
number_repeats = 50
new_df = df.reindex(np.tile(df.index, number_repeats))
I'm going to guess you aren't getting errors or you would've mentioned them. If that's the case, try removing the href
attribute value so the page doesn't navigate away before your code is executed. In Angular it's perfectly acceptable to leave href
attributes blank.
<a href="" data-router="article" ng-click="changeListName('metro')">
Also I don't know what data-router
is doing but if you still aren't getting the proper result, that could be why.
If you have this in your application.properties
:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
,
you can get rid of the error by removing that line.
I know this is old and whatnot (and not exactly sure if it's a question), but after searching, I had success with this command for --onefile
:
pyinstaller.exe --onefile --windowed --icon=app.ico app.py
Google led me to this page while I was searching for an answer on how to set an icon for my .exe, so maybe it will help someone else.
The information here was found at this site: https://mborgerson.com/creating-an-executable-from-a-python-script
There are 2 different ways you can look for lowercase characters:
Use str.islower()
to find lowercase characters. Combined with a list comprehension, you can gather all lowercase letters:
lowercase = [c for c in s if c.islower()]
You could use a regular expression:
import re
lc = re.compile('[a-z]+')
lowercase = lc.findall(s)
The first method returns a list of individual characters, the second returns a list of character groups:
>>> import re
>>> lc = re.compile('[a-z]+')
>>> lc.findall('AbcDeif')
['bc', 'eif']
The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.
I'm not sure what changed, but I am unable to checkout a specific commit without the option --detach
. The full command that worked for me was:
git checkout --detach [commit hash]
To get back from the detached state I had to checkout my local branch: git checkout master
Use subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.
Just try beeprint
it prints something like this:
instance(Animal):
legs: 2,
name: 'Dog',
color: 'Spotted',
smell: 'Alot',
age: 10,
kids: 0,
I think is exactly what you need.
I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:
public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public VndApiJsonMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
}
}
Which can be used simply like the following:
HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");
List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());
var responseObject = await response.Content.ReadAsAsync<Person>(formatters);
Super simple and works exactly as I expected.
Use String.PadLeft like this:
var result = input.ToString().PadLeft(length, '0');
Welcome to 2017 these days will using vW
and vH
do the trick
html, body {_x000D_
margin: 0; padding: 0;_x000D_
width: 100%; height: 100%;_x000D_
}_x000D_
_x000D_
ul {_x000D_
background: #CCC;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
list-style-position: outside;_x000D_
margin: 0; padding: 0;_x000D_
}_x000D_
_x000D_
li {_x000D_
width: 100%;_x000D_
display: table;_x000D_
}_x000D_
_x000D_
img {_x000D_
width: 100%;_x000D_
height: 410px;_x000D_
}_x000D_
_x000D_
.outer-wrapper {_x000D_
position: absolute;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
top: 0;_x000D_
margin: 0; padding: 0;_x000D_
}_x000D_
_x000D_
.inner-wrapper {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
width: 100vw; /* only change is here "%" to "vw" ! */_x000D_
height: 100vh; /* only change is here "%" to "vh" ! */_x000D_
}
_x000D_
<ul>_x000D_
<li>_x000D_
<img src="#">_x000D_
<div class="outer-wrapper">_x000D_
<div class="inner-wrapper">_x000D_
<h1>My Title</h1>_x000D_
<h5>Subtitle</h5>_x000D_
</div>_x000D_
</div>_x000D_
</li>_x000D_
</ul>
_x000D_
I am using the WLST tool that comes with weblogic, and it doesn't implement the platform package.
wls:/offline> import os
wls:/offline> print os.name
java
wls:/offline> import sys
wls:/offline> print sys.platform
'java1.5.0_11'
Apart from patching the system javaos.py (issue with os.system() on windows 2003 with jdk1.5) (which I can't do, I have to use weblogic out of the box), this is what I use:
def iswindows():
os = java.lang.System.getProperty( "os.name" )
return "win" in os.lower()
Use your own HTTPS-to-HTTP reverse proxy.
If your use case is about a few, rarely changing URLs to embed into the iframe
, you can simply set up a reverse proxy for this on your own server and configure it so that one https
URL on your server maps to one http
URL on the proxied server. Since a reverse proxy is fully serverside, the browser cannot discover that it is "only" talking to a proxy of the real website, and thus will not complain as the connection to the proxy uses SSL properly.
If for example you use Apache2 as your webserver, then see these instructions to create a reverse proxy.
You need to set the timeout to "None" when you open the serial port:
ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False)
This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()
Once you have the data, it will return ASAP.
To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.
I came up with this noob simple version
def ip_checkv4(ip):
parts=ip.split(".")
if len(parts)<4 or len(parts)>4:
return "invalid IP length should be 4 not greater or less than 4"
else:
while len(parts)== 4:
a=int(parts[0])
b=int(parts[1])
c=int(parts[2])
d=int(parts[3])
if a<= 0 or a == 127 :
return "invalid IP address"
elif d == 0:
return "host id should not be 0 or less than zero "
elif a>=255:
return "should not be 255 or greater than 255 or less than 0 A"
elif b>=255 or b<0:
return "should not be 255 or greater than 255 or less than 0 B"
elif c>=255 or c<0:
return "should not be 255 or greater than 255 or less than 0 C"
elif d>=255 or c<0:
return "should not be 255 or greater than 255 or less than 0 D"
else:
return "Valid IP address ", ip
p=raw_input("Enter IP address")
print ip_checkv4(p)
You have forgotten to mark the getProducts return type as an array. In your getProducts it says that it will return a single product. So change it to this:
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
You JSON is not a valid string as P. Galbraith has told you above.
and here is the solution for it.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Use this code it will work for you.
Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)
use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";
This gives you:
14.05.2014