I am using kue: https://github.com/learnboost/kue . It is pretty nice.
The official features and my comments:
Edit:
Zcron is available free for personal use.
Gantt chart is wrong... First process P3 has arrived so it will execute first. Since the burst time of P3 is 3sec after the completion of P3, processes P2,P4, and P5 has been arrived. Among P2,P4, and P5 the shortest burst time is 1sec for P2, so P2 will execute next. Then P4 and P5. At last P1 will be executed.
Gantt chart for this ques will be:
| P3 | P2 | P4 | P5 | P1 |
1 4 5 7 11 14
Average waiting time=(0+2+2+3+3)/5=2
Average Turnaround time=(3+3+4+7+6)/5=4.6
A daily task? Sounds like it should just be a scheduled task (control panel) - no need for a service here.
The Linux Kernel does not automatically change the IO Scheduler at run-time. By this I mean, the Linux kernel, as of today, is not able to automatically choose an "optimal" scheduler depending on the type of secondary storage devise. During start-up, or during run-time, it is possible to change the IO scheduler manually.
The default scheduler is chosen at start-up based on the contents in the file located at /linux-2.6 /block/Kconfig.iosched. However, it is possible to change the IO scheduler during run-time by echo
ing a valid scheduler name into the file located at /sys/block/[DEV]/queue/scheduler. For example, echo deadline > /sys/block/hda/queue/scheduler
If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
will give you a ScheduledExecutorService
with similar functionality to Timer
(i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer
class). Using a ScheduledExecutorService
also gives you advantages such as:
newScheduledThreadPoolExecutor()
or the ScheduledThreadPoolExecutor
class)About the only reasons for sticking to Timer
I can think of are:
In Workbook events:
Private Sub Workbook_Open()
RunEveryTwoMinutes
End Sub
In a module:
Sub RunEveryTwoMinutes()
//Add code here for whatever you want to happen
Application.OnTime Now + TimeValue("00:02:00"), "RunEveryTwoMinutes"
End Sub
If you only want the first piece of code to execute after the workbook opens then just add a delay of 2 minutes into the Workbook_Open
event
These days, you can leverage the .NET library from VBA. The following works for me in Excel 2016. Returns the hash as uppercase hex.
Public Function SHA1(ByVal s As String) As String
Dim Enc As Object, Prov As Object
Dim Hash() As Byte, i As Integer
Set Enc = CreateObject("System.Text.UTF8Encoding")
Set Prov = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")
Hash = Prov.ComputeHash_2(Enc.GetBytes_4(s))
SHA1 = ""
For i = LBound(Hash) To UBound(Hash)
SHA1 = SHA1 & Hex(Hash(i) \ 16) & Hex(Hash(i) Mod 16)
Next
End Function
If you are not limited to using ftplib
you can also give wget
module a try. Here, is the snippet
import wget
file_loc = 'http://www.website.com/foo.zip'
wget.download(file_loc)
The display:table
family of CSS properties is mostly there so that HTML tables can be defined in terms of them. Because they're so intimately linked to a specific tag structure, they don't see much use beyond that.
If you were going to use these properties in your page, you would need a tag structure that closely mimicked that of tables, even though you weren't actually using the <table>
family of tags. A minimal version would be a single container element (display:table
), with direct children that can all be represented as rows (display:table-row
), which themselves have direct children that can all be represented as cells (display:table-cell
). There are other properties that let you mimic other tags in the table
family, but they require analogous structures in the HTML. Without this, it's going to be very hard (if not impossible) to make good use of these properties.
var x = document.getElementsByClassName("class name");
if (x[0]) {
alert('has');
} else {
alert('no has');
}
Try this one:
class test {
public function newTest(){
$this->bigTest();
$this->smallTest();
}
private function bigTest(){
//Big Test Here
}
private function smallTest(){
//Small Test Here
}
public function scoreTest(){
//Scoring code here;
}
}
$testObject = new test();
$testObject->newTest();
$testObject->scoreTest();
If you want a default notification sound to be played, then you can use setDefaults(int) method of NotificationCompat.Builder
class:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(someText)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true);
I believe that's the easiest way to accomplish your task.
Here is my method to cast an object but not to a generic type variable, rather to a System.Type
dynamically:
I create a lambda expression at run-time using System.Linq.Expressions
, of type Func<object, object>
, that unboxes its input, performs the desired type conversion then gives the result boxed. A new one is needed not only for all types that get casted to, but also for the types that get casted (because of the unboxing step). Creating these expressions is highly time consuming, because of the reflection, the compilation and the dynamic method building that is done under the hood. Luckily once created, the expressions can be invoked repeatedly and without high overhead, so I cache each one.
private static Func<object, object> MakeCastDelegate(Type from, Type to)
{
var p = Expression.Parameter(typeof(object)); //do not inline
return Expression.Lambda<Func<object, object>>(
Expression.Convert(Expression.ConvertChecked(Expression.Convert(p, from), to), typeof(object)),
p).Compile();
}
private static readonly Dictionary<Tuple<Type, Type>, Func<object, object>> CastCache
= new Dictionary<Tuple<Type, Type>, Func<object, object>>();
public static Func<object, object> GetCastDelegate(Type from, Type to)
{
lock (CastCache)
{
var key = new Tuple<Type, Type>(from, to);
Func<object, object> cast_delegate;
if (!CastCache.TryGetValue(key, out cast_delegate))
{
cast_delegate = MakeCastDelegate(from, to);
CastCache.Add(key, cast_delegate);
}
return cast_delegate;
}
}
public static object Cast(Type t, object o)
{
return GetCastDelegate(o.GetType(), t).Invoke(o);
}
Note that this isn't magic. Casting doesn't occur in code, as it does with the dynamic
keyword, only the underlying data of the object gets converted. At compile-time we are still left to painstakingly figure out exactly what type our object might be, making this solution impractical. I wrote this as a hack to invoke conversion operators defined by arbitrary types, but maybe somebody out there can find a better use case.
This is not shorter, but it deals with detached branches as well:
git branch | awk -v FS=' ' '/\*/{print $NF}' | sed 's|[()]||g'
The answer is "no, you probably can't".
While there is stuff in there that might say who created a given object, there are a lot of "ifs" behind them. A quick (and not necessarily complete) review:
sys.objects (and thus sys.tables, sys.procedures, sys.views, etc.) has column principal_id. This value is a foreign key that relates to the list of database users, which in turn can be joined with the list of SQL (instance) logins. (All of this info can be found in further system views.)
But.
A quick check on our setup here and a cursory review of BOL indicates that this value is only set (i.e. not null) if it is "different from the schema owner". In our development system, and we've got dbo + two other schemas, everything comes up as NULL. This is probably because everyone has dbo rights within these databases.
This is using NT authentication. SQL authentication probably works much the same. Also, does everyone have and use a unique login, or are they shared? If you have employee turnover and domain (or SQL) logins get dropped, once again the data may not be there or may be incomplete.
You can look this data over (select * from sys.objects), but if principal_id is null, you are probably out of luck.
You can also user java Regular Expression. String.split() also uses the expression internally. Refer http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
At first install Pillow with
pip install Pillow
or as follows
c:\Python35>python -m pip install Pillow
Then in python code you may call
from PIL import Image
"Pillow is a fork of PIL, the Python Imaging Library, which is no longer maintained. However, to maintain backwards compatibility, the old module name is used." From pillow installed, but "no module named pillow" - python2.7 - Windows 7 - python -m install pillow
If a variable is not set then it is NULL
and if you try to divide something by null you will get a divides by zero error
There is a rails plugin called Annotate models, that will generate your model attributes on the top of your model files here is the link:
https://github.com/ctran/annotate_models
to keep the annotation in sync, you can write a task to re-generate annotate models after each deploy.
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
I hunted around for ages to find a decent easy solution to this and in the end found some ridiculously complicated CLR solutions so decided to write my own simple VB one. Simply create a new VB CLR project from the Database tab under Installed Templates, and then add a new SQL CLR VB User Defined Function. I renamed it to CLRGetFilesInDir.vb. Here's the code inside it...
Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.IO
-----------------------------------------------------------------------------
Public Class CLRFilesInDir
-----------------------------------------------------------------------------
<SqlFunction(FillRowMethodName:="FillRowFiles", IsDeterministic:=True, IsPrecise:=True, TableDefinition:="FilePath nvarchar(4000)")> _
Public Shared Function GetFiles(PathName As SqlString, Pattern As SqlString) As IEnumerable
Dim FileNames As String()
Try
FileNames = Directory.GetFiles(PathName, Pattern, SearchOption.TopDirectoryOnly)
Catch
FileNames = Nothing
End Try
Return FileNames
End Function
-----------------------------------------------------------------------------
Public Shared Sub FillRowFiles(ByVal obj As Object, ByRef Val As SqlString)
Val = CType(obj, String).ToString
End Sub
End Class
I also changed the Assembly Name in the Project Properties window to CLRExcelFiles, and the Default Namespace to CLRGetExcelFiles.
NOTE: Set the target framework to 3.5 if you are using anything less that SQL Server 2012.
Compile the project and then copy the CLRExcelFiles.dll from \bin\release to somewhere like C:\temp on the SQL Server machine, not your own.
In SSMS:-
CREATE ASSEMBLY <your assembly name in here - anything you like>
FROM 'C:\temp\CLRExcelFiles.dll';
CREATE FUNCTION dbo.fnGetFiles
(
@PathName NVARCHAR(MAX),
@Pattern NVARCHAR(MAX)
)
RETURNS TABLE (Val NVARCHAR(100))
AS
EXTERNAL NAME <your assembly name>."CLRGetExcelFiles.CLRFilesInDir".GetFiles;
GO
then call it
SELECT * FROM dbo.fnGetFiles('\\<SERVERNAME>\<$SHARE>\<folder>\' , '*.xls')
NOTE: Even though I changed the Permission Level to EXTERNAL_ACCESS on the SQLCLR tab under Project Properties, I still needed to run this every time I (re)created it.
ALTER ASSEMBLY [CLRFilesInDirAssembly]
WITH PERMISSION_SET = EXTERNAL_ACCESS
GO
and wullah! that should work.
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
You can use the pgrep command like in the following example
$ pgrep Keychain\ Access
44186
You can also use -S
, -D
or -P
which are equivalent of saving the package to an app dependency, a dev dependency or prod dependency. See more NPM shortcuts below:
-v: --version
-h, -?, --help, -H: --usage
-s, --silent: --loglevel silent
-q, --quiet: --loglevel warn
-d: --loglevel info
-dd, --verbose: --loglevel verbose
-ddd: --loglevel silly
-g: --global
-C: --prefix
-l: --long
-m: --message
-p, --porcelain: --parseable
-reg: --registry
-f: --force
-desc: --description
-S: --save
-P: --save-prod
-D: --save-dev
-O: --save-optional
-B: --save-bundle
-E: --save-exact
-y: --yes
-n: --yes false
ll and la commands: ls --long
This list of shortcuts can be obtained by running the following command:
$ npm help 7 config
For anyone who, like me, reads this because they need to update a giant legacy project to 5.6: as the answers here point out, there is no quick fix: you really do need to find each occurrence of the problem manually, and fix it.
The most convenient way I found to find all problematic lines in a project (short of using a full-blown static code analyzer, which is very accurate but I don't know any that take you to the correct position in the editor right away) was using Visual Studio Code, which has a nice PHP linter built in, and its search feature which allows searching by Regex. (Of course, you can use any IDE/Code editor for this that does PHP linting and Regex searches.)
Using this regex:
^(?!.*function).*(\&\$)
it is possible to search project-wide for the occurrence of &$
only in lines that are not a function definition.
This still turns up a lot of false positives, but it does make the job easier.
VSCode's search results browser makes walking through and finding the offending lines super easy: you just click through each result, and look out for those that the linter underlines red. Those you need to fix.
In my case, the file ~/.curlrc had a wrong proxy configured.
Look up the new HTML5 Input Types. These instruct browsers to perform client-side filtering of data, but the implementation is incomplete across different browsers. The pattern
attribute will do regex-style filtering, but, again, browsers don't fully (or at all) support it.
However, these won't block the input itself, it will simply prevent submitting the form with the invalid data. You'll still need to trap the onkeydown
event to block key input before it displays on the screen.
Font.Name
, Font.XYZProperty
, etc are readonly as Font
is an immutable object, so you need to specify a new Font
object to replace it:
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
Check the constructor of the Font
class for further options.
If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:
DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))
Use it like this:
for key, value in DICT_ITER_ITEMS(myDict):
# Do something with 'key' and/or 'value'.
Simple solution:
In AndroidManifest
in Activity
tag use
android:windowSoftInputMode="stateAlwaysHidden"
This article explains all the details http://kunststube.net/encoding/
WRITING TO BUFFER
if you write to a 4 byte buffer, symbol ?
with UTF8 encoding, your binary will look like this:
00000000 11100011 10000001 10000010
if you write to a 4 byte buffer, symbol ?
with UTF16 encoding, your binary will look like this:
00000000 00000000 00110000 01000010
As you can see, depending on what language you would use in your content this will effect your memory accordingly.
e.g. For this particular symbol: ?
UTF16 encoding is more efficient since we have 2 spare bytes to use for the next symbol. But it doesn't mean that you must use UTF16 for Japan alphabet.
READING FROM BUFFER
Now if you want to read the above bytes, you have to know in what encoding it was written to and decode it back correctly.
e.g. If you decode this :
00000000 11100011 10000001 10000010
into UTF16 encoding, you will end up with ?
not ?
Note: Encoding and Unicode are two different things. Unicode is the big (table) with each symbol mapped to a unique code point. e.g. ?
symbol (letter) has a (code point): 30 42 (hex). Encoding on the other hand, is an algorithm that converts symbols to more appropriate way, when storing to hardware.
30 42 (hex) - > UTF8 encoding - > E3 81 82 (hex), which is above result in binary.
30 42 (hex) - > UTF16 encoding - > 30 42 (hex), which is above result in binary.
It does this by default, you just need to look into the project's /dist
folder.
VBA functions treat the function name itself as a sort of variable. So instead of using a "return
" statement, you would just say:
test = 1
Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test
, and whatever the value is when you reach the end of the function will be the value returned.
You have to use escaping of characters. It's a solution of this chicken-and-egg problem: how do I write a ", if I need it to terminate a string literal? So, the C creators decided to use a special character that changes treatment of the next char:
printf("this is a \"quoted string\"");
Also you can use '\' to input special symbols like "\n", "\t", "\a", to input '\' itself: "\\" and so on.
This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.
var expression = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
This minimal CMakeLists.txt
file compiles a simple shared library:
cmake_minimum_required(VERSION 2.8)
project (test)
set(CMAKE_BUILD_TYPE Release)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
add_library(test SHARED src/test.cpp)
However, I have no experience copying files to a different destination with CMake. The file command with the COPY/INSTALL signature looks like it might be useful.
This is something I have done in the past.
Create a list of objects, and you can then have objects delete themselves with the list.remove()
method.
bullet_list = []
class Bullet:
def kill_self(self):
bullet_list.remove(self)
bullet_list += [Bullet()]
The second is preferred because it is far less likely to result in an accidental cross join by forgetting to put inthe where clause. A join with no on clause will fail the syntax check, an old style join with no where clause will not fail, it will do a cross join.
Additionally when you later have to a left join, it is helpful for maintenance that they all be in the same structure. And the old syntax has been out of date since 1992, it is well past time to stop using it.
Plus I have found that many people who exclusively use the first syntax don't really understand joins and understanding joins is critical to getting correct results when querying.
Your question is a little unclear. If you're generating hostDict
in a loop:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('\n')
If you mean you want each variable within hostDict
to be on a new line:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
When the indent
keyword argument is set it automatically adds newlines.
['class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost:3306;dbname=testdb',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',]
It's simple:
Just provide the port number along with the host name
and set default sock path to your mysql.sock
file path in php.ini
which the server is running on.
Not bad variant too)
var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];
var id = 1; //id to find
arr[_.find(arr, {id: id})].name = 'New Person';
Is it also possible to access the management port in a similar way, e.g.:
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
int randomServerPort;
@LocalManagementPort
int randomManagementPort;
A simple solution:
using (Form2 f2 = new Form2())
{
f2.Show();
f2.Update();
System.Threading.Thread.Sleep(2500);
} // f2 is closed and disposed here
And then substitute your Loading for the Sleep.
This blocks the UI thread, on purpose.
You use the String.format() method.
Merging several answers from above into an easy to use function
function GetScriptIfNotLoaded(scriptLocationAndName)
{
var len = $('script[src*="' + scriptLocationAndName +'"]').length;
//script already loaded!
if (len > 0)
return;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
In the rare cases I have wanted to test private functions, I have usually modified them to be protected instead, and the I have written a subclass with a public wrapper function.
The Class:
...
protected void APrivateFunction()
{
...
}
...
Subclass for testing:
...
[Test]
public void TestAPrivateFunction()
{
APrivateFunction();
//or whatever testing code you want here
}
...
use colspan="100%" in table cell and it's working fine.
colspan="100%"
_x000D_
A solution that:
...is this one-liner:
python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
Formatted for readability (rather than use as a one-liner), that looks like the following:
from distutils.sysconfig import get_python_lib
print(get_python_lib())
Source: an very old version of "How to Install Django" documentation (though this is useful to more than just Django installation)
You may need to clear the plugin
column for your root account. On my fresh install, all of the root user accounts had unix_socket
set in the plugin
column. This was causing the root sql account to be locked only to the root unix account, since only system root could login via socket.
If you update user set plugin='' where User='root';flush privileges;
, you should now be able to login to the root account from any localhost unix account (with a password).
See this AskUbuntu question and answer for more details.
Use CAST with following parameters:
Date
select Cast('2017-10-11 14:38:50.440' as date)
Output: 2017-10-11
Datetime
select Cast('2017-10-11 14:38:50.440' as datetime)
Output: 2017-10-11 14:38:50.440
SmallDatetime
select Cast('2017-10-11 14:38:50.440' as smalldatetime)
Output: 2017-10-11 14:39:00
DatetimeOffset
select Cast('2017-10-11 14:38:50.440' as datetimeoffset)
Output: 2017-10-11 14:38:50.4400000 +00:00
Datetime2
select Cast('2017-10-11 14:38:50.440' as datetime2)
Output: 2017-10-11 14:38:50.4400000
I could not make @Clockwork-Muse work actually. But I could make this variation work:
WITH Tmp AS (SELECT * FROM (VALUES (id1, newsPosX1, newPosY1),
(id2, newsPosX2, newPosY2),
......................... ,
(idN, newsPosXN, newPosYN)) d(id, px, py))
UPDATE t
SET posX = (SELECT px FROM Tmp WHERE t.id = Tmp.id),
posY = (SELECT py FROM Tmp WHERE t.id = Tmp.id)
FROM TableToUpdate t
I hope this works for you too!
Adding a branch
option in .gitmodule
is NOT related to the detached behavior of submodules at all. The old answer from @mkungla is incorrect, or obsolete.
From git submodule --help
, HEAD detached is the default behavior of git submodule update --remote
.
First, there's no need to specify a branch to be tracked. origin/master
is the default branch to be tracked.
--remote
Instead of using the superproject's recorded SHA-1 to update the submodule, use the status of the submodule's remote-tracking branch. The remote used is branch's remote (
branch.<name>.remote
), defaulting toorigin
. The remote branch used defaults tomaster
.
So why is HEAD detached after update
? This is caused by the default module update behavior: checkout
.
--checkout
Checkout the commit recorded in the superproject on a detached HEAD in the submodule. This is the default behavior, the main use of this option is to override
submodule.$name.update
when set to a value other thancheckout
.
To explain this weird update behavior, we need to understand how do submodules work?
Quote from Starting with Submodules in book Pro Git
Although sbmodule
DbConnector
is a subdirectory in your working directory, Git sees it as a submodule and doesn’t track its contents when you’re not in that directory. Instead, Git sees it as a particular commit from that repository.
The main repo tracks the submodule with its state at a specific point, the commit id. So when you update modules, you're updating the commit id to a new one.
If you want the submodule merged with remote branch automatically, use --merge
or --rebase
.
--merge
This option is only valid for the update command. Merge the commit recorded in the superproject into the current branch of the submodule. If this option is given, the submodule's HEAD will not be detached.
--rebase
Rebase the current branch onto the commit recorded in the superproject. If this option is given, the submodule's HEAD will not be detached.
All you need to do is,
git submodule update --remote --merge
# or
git submodule update --remote --rebase
Recommended alias:
git config alias.supdate 'submodule update --remote --merge'
# do submodule update with
git supdate
There's also an option to make --merge
or --rebase
as the default behavior of git submodule update
, by setting submodule.$name.update
to merge
or rebase
.
Here's an example about how to config the default update behavior of submodule update in .gitmodule
.
[submodule "bash/plugins/dircolors-solarized"]
path = bash/plugins/dircolors-solarized
url = https://github.com/seebi/dircolors-solarized.git
update = merge # <-- this is what you need to add
Or configure it in command line,
# replace $name with a real submodule name
git config -f .gitmodules submodule.$name.update merge
git submodule --help
You can try with this:
WITH CTE_A As (SELECT COUNT(*) as articleNumber,A.UserID as UserID FROM Articles A
Inner Join Users U
on A.userId = U.userId
Group By A.userId , U.userId ),
B as (Select us.registrationDate,
CASE
WHEN CTE_A.articleNumber < 2 THEN 'Ama'
WHEN CTE_A.articleNumber < 5 THEN 'SemiAma'
WHEN CTE_A.articleNumber < 7 THEN 'Good'
WHEN CTE_A.articleNumber < 9 THEN 'Better'
WHEN CTE_A.articleNumber < 12 THEN 'Best'
ELSE 'Outstanding'
END as Ranking,
us.hobbies, etc...
FROM USERS Us Inner Join CTE_A
on CTE_A.UserID=us.UserID)
Select * from B
This question has been answered already several times, I'll short summary for each of them, an example and insights as of September 2019:
Example: <h1>
tag inside <section>
by default Google Chrome will make smaller than the "expected" size of <h1>
tag. Microsoft Edge on the other hand is making the "expected" size of <h1>
tag. Normalize.css will make it consistent.
Current status: the npm repository shows that normalize.css package has currently more than 500k downloads per week. GitHub stars in the project of the repository are more than 36k.
Example: it would do something like that below:
html, body, div, span, ..., audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
Current status: it's much less popular than Normalize.css, the reset-css package shows it's something around 26k downloads per week. GitHub stars are only 200, as it can be noticed from the project's repository.
Short answer: Don't do it.
Longer answer: Use WCF. It's here to replace Asmx.
see this answer for example, or the first comment on this one.
John Saunders: ASMX is a legacy technology, and should not be used for new development. WCF or ASP.NET Web API should be used for all new development of web service clients and servers. One hint: Microsoft has retired the ASMX Forum on MSDN.
As for comment ... well, if you have to, you have to. I'll leave you in the competent hands of the other answers then. (Even though it's funny it has issues, and if it does, why are you doing it in VS2013 to begin with ?)
this should work:
setw -g mode-mouse on
then resource then config file
tmux source-file ~/.tmux.conf
or kill the server
You might want to take a look at the timeit
module:
http://docs.python.org/library/timeit.html
or the profile
module:
http://docs.python.org/library/profile.html
There are some additionally some nice tutorials here:
http://www.doughellmann.com/PyMOTW/profile/index.html
http://www.doughellmann.com/PyMOTW/timeit/index.html
And the time
module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:
Split a string on space, get a list, show its type, print it out:
el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"
>>> mylist = mystring.split(" ")
>>> print type(mylist)
<type 'list'>
>>> print mylist
['What', 'does', 'the', 'fox', 'say?']
If you have two delimiters next to each other, empty string is assumed:
el@apollo:~/foo$ python
>>> mystring = "its so fluffy im gonna DIE!!!"
>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']
Split a string on underscore and grab the 5th item in the list:
el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."
>>> mystring.split("_")[4]
"Kowalski's"
Collapse multiple spaces into one
el@apollo:~/foo$ python
>>> mystring = 'collapse these spaces'
>>> mycollapsedstring = ' '.join(mystring.split())
>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']
When you pass no parameter to Python's split method, the documentation states: "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".
Hold onto your hats boys, parse on a regular expression:
el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']
The regular expression "[a-m]+" means the lowercase letters a
through m
that occur one or more times are matched as a delimiter. re
is a library to be imported.
Or if you want to chomp the items one at a time:
el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"
>>> mytuple = mystring.partition(" ")
>>> print type(mytuple)
<type 'tuple'>
>>> print mytuple
('theres', ' ', 'coffee in that nebula')
>>> print mytuple[0]
theres
>>> print mytuple[2]
coffee in that nebula
I often use this workaround in CLI where instead of configuring my .gitignore
, I create a separate .include
file where I define the (sub)directories I want included in spite of directories directly or recursively ignored by .gitignore
.
Thus, I additionally use
git add `cat .include`
during staging, before committing.
To the OP, I suggest using a .include
which has these lines:
<parent_folder_path>/application/language/gr/*
NOTE: Using cat
does not allow usage of aliases (within .include
) for specifying $HOME (or any other specific directory). This is because the line homedir/app1/*
when passed to git add
using the above command appears as git add 'homedir/app1/*'
, and enclosing characters in single quotes ('') preserves the literal value of each character within the quotes, thus preventing aliases (such as homedir) from functioning (see Bash Single Quotes).
Here is an example of a .include
file I use in my repo here.
/home/abhirup/token.txt
/home/abhirup/.include
/home/abhirup/.vim/*
/home/abhirup/.viminfo
/home/abhirup/.bashrc
/home/abhirup/.vimrc
/home/abhirup/.condarc
My worry is if I say delete evertything with an ID (>79 AND < 296) then it may literally wipe the whole table...
That wont happen because you will have a where clause. What happens is that, if you have a statement like delete * from Table1 where id between 70 and 1296
, the first thing that sql query processor will do is to scan the table and look for those records in that range and then apply a delete.
For Finding All the ChildNodes you can use the below Snippet
List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));
for (WebElement e : childs)
{
System.out.println(e.getTagName());
}
Note that this will give all the Child Nodes at same level -> Like if you have structure like this :
<Html>
<body>
<div> ---suppose this is current WebElement
<a>
<a>
<img>
<a>
<img>
<a>
It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));
Hope That Helps !!
Well you seem to have mistaken them both for what they do.
$(window).height()
gets you an unit-less pixel value of the height of the (browser) window aka viewport. With respect to the web browsers the viewport here is visible portion of the canvas(which often is smaller than the document being rendered).
$(document).height()
returns an unit-less pixel value of the height of the document being rendered. However, if the actual document’s body height is less than the viewport height then it will return the viewport height instead.
Hope that clears things a little.
generateNumbers()
expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
You could simply add some random number with the CSS and JavaScript URL like
example.css?randomNo = Math.random()
struct node{
int position;
char name[30];
struct node * next;
};
void free_list(node * list){
node* next_node;
printf("\n\n Freeing List: \n");
while(list != NULL)
{
next_node = list->next;
printf("clear mem for: %s",list->name);
free(list);
list = next_node;
printf("->");
}
}
Since you have updated your label client side, you'll need a post-back in order for you're server side code to reflect the changes.
If you do not know how to do this, here is how I've gone about it in the past.
Create a hidden field:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
Create a button that has both client side and server side functions attached to it. You're client side function will populate your hidden field, and the server side will read it. Be sure you're client side is being called first.
<asp:Button ID="_Submit" runat="server" Text="Submit Button" OnClientClick="TestSubmit();" OnClick="_Submit_Click" />
Javascript Client Side Function:
function TestSubmit() {
try {
var message = "Message to Pass";
document.getElementById('__EVENTTARGET').value = message;
} catch (err) {
alert(err.message);
}
}
C# Server Side Function
protected void _Submit_Click(object sender, EventArgs e)
{
// Hidden Value after postback
string hiddenVal= Request.Form["__EVENTTARGET"];
}
Hope this helps!
i don't know what mistakes i did while implementing the above solutions, bt they were unsuccessful for me
txtDeck.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
txtDeck.setText("");
}
});
This works for me,
I use a function to echo and run the command:
#!/bin/bash
# Function to display commands
exe() { echo "\$ $@" ; "$@" ; }
exe echo hello world
Which outputs
$ echo hello world
hello world
For more complicated commands pipes, etc., you can use eval:
#!/bin/bash
# Function to display commands
exe() { echo "\$ ${@/eval/}" ; "$@" ; }
exe eval "echo 'Hello, World!' | cut -d ' ' -f1"
Which outputs
$ echo 'Hello, World!' | cut -d ' ' -f1
Hello
This seems issue with my node upgrade. How ever I solved it with the following approach.
First uninstall the cli, clear cashe, and reinstall with these commands
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli
Then install node-pre-gyp
npm install -g node-pre-gyp
Restart your terminal and see if the issue is solved.
If your jar file already has an absolute pathname as shown, it is particularly easy:
cd /where/you/want/it; jar xf /path/to/jarfile.jar
That is, you have the shell executed by Python change directory for you and then run the extraction.
If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar
can find it after the change of directory.
The only issues left to worry about are things like blanks in the path names.
public static class Employee
{
public static string SomeSetting
{
get
{
return ConfigurationManager.AppSettings["SomeSetting"];
}
}
}
Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.
If you feel that you must store a reference to appsettings, try
public static class Employee
{
private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;
public static NameValueCollection AppSettings { get { return _appSettings; } }
}
It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.
Once you have both branches in one repository you can do a git diff
. And getting them in one repository is as easy as
git fetch /the/other/repo/.git refs/heads/*:refs/remotes/other/*
If you have query like:
SELECT * FROM user WHERE id IN (1, 2, 3, 4 -- and thousands of another keys)
you may increase performace if rewrite your query like:
SELECT * FROM user WHERE id = ANY(VALUES (1), (2), (3), (4) -- and thousands of another keys)
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter
with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
Left shift <<
This is somehow easy and whenever you use the shift operator, it is always a bit-wise operation, so we can't use it with a double and float operation. Whenever we left shift one zero, it is always added to the least significant bit (LSB
).
But in right shift >>
we have to follow one additional rule and that rule is called "sign bit copy". Meaning of "sign bit copy" is if the most significant bit (MSB
) is set then after a right shift again the MSB
will be set if it was reset then it is again reset, means if the previous value was zero then after shifting again, the bit is zero if the previous bit was one then after the shift it is again one. This rule is not applicable for a left shift.
The most important example on right shift if you shift any negative number to right shift, then after some shifting the value finally reach to zero and then after this if shift this -1 any number of times the value will remain same. Please check.
I think you meant to do url[i] <- paste(...
instead of url[i] = paste(...
. If so replace =
with <-
.
There are several ways. One way is to use save()
to save the exact object. e.g. for data frame foo
:
save(foo,file="data.Rda")
Then load it with:
load("data.Rda")
You could also use write.table()
or something like that to save the table in plain text, or dput()
to obtain R code to reproduce the table.
For start Activity 2 from Activity 1 and get result, you could use startActivityForResult and implement onActivityResult in Activity 1 and use setResult in Activity2.
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(NUMERO1, numero1);
intent.putExtra(NUMERO2, numero2);
//startActivity(intent);
startActivityForResult(intent, MI_REQUEST_CODE);
Correción: 3-LEN
declare @t TINYINT
set @t =233
SELECT ISNULL(REPLICATE('0',3-LEN(@t)),'') + CAST(@t AS VARCHAR)
This is very straightforward with boolean arrays:
p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements
Option(getObject) foreach (QueueManager add)
You have to wait for TypeScript 2.0 with async
/await
for ES5 support as it now supported only for TS to ES6 compilation.
You would be able to create delay function with async
:
function delay(ms: number) {
return new Promise( resolve => setTimeout(resolve, ms) );
}
And call it
await delay(300);
Please note, that you can use await
only inside async
function.
If you can't (let's say you are building nodejs application), just place your code in the anonymous async
function. Here is an example:
(async () => {
// Do something before delay
console.log('before delay')
await delay(1000);
// Do something after
console.log('after delay')
})();
Example TS Application: https://github.com/v-andrew/ts-template
In OLD JS you have to use
setTimeout(YourFunctionName, Milliseconds);
or
setTimeout( () => { /*Your Code*/ }, Milliseconds );
However with every major browser supporting async
/await
it less useful.
Update: TypeScript 2.1 is here with
async/await
.
Just do not forget that you need Promise
implementation when you compile to ES5, where Promise is not natively available.
PS
You have to export the function if you want to use it outside of the original file.
EDIT
another way to deal with duplicate is you can do like this
var dic = slist.Select((element, index)=> new{element,index} )
.ToDictionary(ele=>ele.index.ToString(), ele=>ele.element);
or
easy way to do is
var res = list.ToDictionary(str => str, str=> str);
but make sure that there is no string is repeating...again otherewise above code will not work for you
if there is string is repeating than its better to do like this
Dictionary<string,string> dic= new Dictionary<string,string> ();
foreach(string s in Stringlist)
{
if(!dic.ContainsKey(s))
{
// dic.Add( value to dictionary
}
}
Okay I fixed this thing. Had to first convert the projects to Maven Projects, then remove them from the Eclipse workspace, and then re-import them.
Yes, we can use jQuery in ReactJs. Here I will tell how we can use it using npm.
step 1: Go to your project folder where the package.json
file is present via using terminal using cd command.
step 2: Write the following command to install jquery using npm : npm install jquery --save
step 3: Now, import $
from jquery
into your jsx file where you need to use.
Example:
write the below in index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
// react code here
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
// react code here
write the below in index.html
<!DOCTYPE html>
<html>
<head>
<script src="index.jsx"></script>
<!-- other scripting files -->
</head>
<body>
<!-- other useful tags -->
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<button>Get External Content</button>
</body>
</html>
This code is working for me either paste from right click or direct copy paste
$('.textbox').on('paste input propertychange', function (e) {
$(this).val( $(this).val().replace(/[^0-9.]/g, '') );
})
When i paste Section 1: Labour Cost
it becomes 1
in text box.
To allow only float value i use this code
//only decimal
$('.textbox').keypress(function(e) {
if(e.which == 46 && $(this).val().indexOf('.') != -1) {
e.preventDefault();
}
if (e.which == 8 || e.which == 46) {
return true;
} else if ( e.which < 48 || e.which > 57) {
e.preventDefault();
}
});
You can try something like this.
<button class="button" ng-disabled="(!data.var1 && !data.var2) ? false : true">
</button>
Its working fine for me.
According to Harry's linear-gradient solution (answered Oct 14 '15 at 9:55), it says that opacity background isn't possible, I tried it and yep, it isn't.
But! I found a workaround. No it's not super optimised, but it worked. So here's my solution. Since Harry doesn't use pseudo element, we can achieve this by creating one.
Set position relative to the container and create a pseudo element with the same linear-gradient properties. In other words, just clone it. Then put a transparent background for the container, and lets say a black background for the clone. Put a position absolute on it, a z-index of -1 and an opacity value (ie. 50%). It will do the job. Again it's a workaround and it's not perfect but it works just fine.
.cut-corner {_x000D_
position: relative;_x000D_
color: white;_x000D_
background-repeat: no-repeat;_x000D_
background-image: linear-gradient(white, white), linear-gradient(white, white), linear-gradient(white, white), linear-gradient(white, white), linear-gradient(to bottom left, transparent calc(50% - 1px), white calc(50% - 1px), white calc(50% + 1px), transparent calc(50% + 1px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);_x000D_
background-size: 2px 100%, 2px 100%, 100% 2px, 100% 2px, 25px 25px, 100% 100%, 100% 100%;_x000D_
background-position: 0% 0%, 100% 25px, -25px 0%, 0px 100%, 100% 0%, -25px 0%, 100% 25px;_x000D_
}_x000D_
.cut-corner:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
left: 0;_x000D_
bottom: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
z-index: -1;_x000D_
opacity: 0.5;_x000D_
background-repeat: no-repeat;_x000D_
background-image: linear-gradient(white, white), linear-gradient(white, white), linear-gradient(white, white), linear-gradient(white, white), linear-gradient(to bottom left, transparent calc(50% - 1px), white calc(50% - 1px), white calc(50% + 1px), black calc(50% + 1px)), linear-gradient(black, black), linear-gradient(black, black);_x000D_
background-size: 2px 100%, 2px 100%, 100% 2px, 100% 2px, 25px 25px, 100% 100%, 100% 100%;_x000D_
background-position: 0% 0%, 100% 25px, -25px 0%, 0px 100%, 100% 0%, -25px 0%, 100% 25px;_x000D_
}_x000D_
_x000D_
/* Just for demo */_x000D_
_x000D_
div {_x000D_
padding: 10px;_x000D_
}_x000D_
body{_x000D_
background-image: radial-gradient(circle, #3F9CBA 0%, #153346 100%);_x000D_
}
_x000D_
<div class="cut-corner">_x000D_
Some content<br>_x000D_
Some content<br>_x000D_
Some content<br>_x000D_
Some content _x000D_
</div>
_x000D_
Deploying Angular 2 in azure is easy
Run ng build --prod , which will generate a dist folder with everything bundled inside few files including index.html.
Create a resource group and a web app inside it.
Place your dist folders files using FTP. In azure it will look for index.html to the run the application.
That's it. Your app is running !
If you're using Homebrew /usr/local/bin should already be at the front of $PATH
or at least come before /usr/bin. If you now run brew link --force openssl
in your terminal window, open a new one and run which openssl
in it. It should now show openssl
under /usr/local/bin.
This is an ancient question, but both module private (one underscore) and class-private (two underscores) mangled variables are now covered in the standard documentation:
Usually a video stream is somewhat fault tolerant. So if some packages get lost (due to some router along the way being overloaded, for example), then it will still be able to display the content, but with reduced quality.
If your live stream was using TCP/IP, then it would be forced to wait for those dropped packages before it could continue processing newer data.
That's doubly bad:
If your goal is to display as up-to-date information as possible (and for a live-stream you usually want to be up-to-date, even if your frames look a bit worse), then TCP will work against you.
For a recorded stream the situation is slightly different: you'll probably be buffering a lot more (possibly several minutes!) and would rather have data re-transmitted than have some artifacts due to lost packages. In this case TCP is a good match (this could still be implemented in UDP, of course, but TCP doesn't have as much drawbacks as for the live stream case).
Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem
You can't.
The only way to get a list of all event listeners attached to a node is to intercept the listener attachment call.
Says
Append an event listener to the associated list of event listeners with type set to type, listener set to listener, and capture set to capture, unless there already is an event listener in that list with the same type, listener, and capture.
Meaning that an event listener is added to the "list of event listeners". That's all. There is no notion of what this list should be nor how you should access it.
Many different ways have already been described by the other answers. However, many of them either involved ShowDialog()
or that form1
stay open but hidden. The best and most intuitive way in my opinion is to simply close form1
and then create form2
from an outside location (i.e. not from within either of those forms). In the case where form1
was created in Main
, form2
can simply be created using Application.Run
just like form1
before. Here's an example scenario:
I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I'm using two forms: LogingForm
and MainForm
. The LoginForm
has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm
instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here's the code for this:
class LoginForm : Form
{
public bool UserSuccessfullyAuthenticated { get; private set; }
void LoginButton_Click(object s, EventArgs e)
{
if(AuthenticateUser(/* ... */))
{
UserSuccessfullyAuthenticated = true;
Close();
}
}
}
static class Program
{
[STAThread]
static void Main()
{
LoginForm loginForm = new LoginForm();
Application.Run(loginForm);
if(loginForm.UserSuccessfullyAuthenticated)
{
// MainForm is defined elsewhere
Application.Run(new MainForm());
}
}
}
Just another approach if you are fine using temp tables.I have personally tested this and it will not cause any exception (even if temp table does not have any data.)
CREATE TABLE #TempTable
(
ROWID int identity(1,1) primary key,
HIERARCHY_ID_TO_UPDATE int,
)
--create some testing data
--INSERT INTO #TempTable VALUES(1)
--INSERT INTO #TempTable VALUES(2)
--INSERT INTO #TempTable VALUES(4)
--INSERT INTO #TempTable VALUES(6)
--INSERT INTO #TempTable VALUES(8)
DECLARE @MAXID INT, @Counter INT
SET @COUNTER = 1
SELECT @MAXID = COUNT(*) FROM #TempTable
WHILE (@COUNTER <= @MAXID)
BEGIN
--DO THE PROCESSING HERE
SELECT @HIERARCHY_ID_TO_UPDATE = PT.HIERARCHY_ID_TO_UPDATE
FROM #TempTable AS PT
WHERE ROWID = @COUNTER
SET @COUNTER = @COUNTER + 1
END
IF (OBJECT_ID('tempdb..#TempTable') IS NOT NULL)
BEGIN
DROP TABLE #TempTable
END
The error message the OP is encountering is just an Eclipse feature. If you are willing to tie your code to a specific maker (and even version) of the JVM, you can effectively use method sun.reflect.Reflection.getCallerClass()
. You can then compile the code outside of Eclipse or configure it not to consider this diagnostic an error.
The worse Eclipse configuration is to disable all occurrences of the error by:
Project Properties
/ Java Compiler
/ Errors/Warnings
/ Enable project specific settings
set to checked / Deprecated and restrited API
/ Forbidden reference (access rules)
set to Warning
or Ignore
.
The better Eclipse configuration is to disable a specific occurrence of the error by:
Project Properties
/ Java Build Path
/ Libraries
/ JRE System Library
expand / Access rules:
select / Edit...
/ Add...
/ Resolution:
set to Discouraged
or Accessible
/ Rule Pattern
set to sun/reflect/Reflection
.
Source (Py v2.7.3) for traceback.format_exception() and called/related functions helps greatly. Embarrassingly, I always forget to Read the Source. I only did so for this after searching for similar details in vain. A simple question, "How to recreate the same output as Python for an exception, with all the same details?" This would get anybody 90+% to whatever they're looking for. Frustrated, I came up with this example. I hope it helps others. (It sure helped me! ;-)
import sys, traceback
traceback_template = '''Traceback (most recent call last):
File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n''' # Skipping the "actual line" item
# Also note: we don't walk all the way through the frame stack in this example
# see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
# (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)
try:
1/0
except:
# http://docs.python.org/2/library/sys.html#sys.exc_info
exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default
'''
Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
or if we do not delete the labels on (not much) older versions of Py, the
reference we created can linger.
traceback.format_exc/print_exc do this very thing, BUT note this creates a
temp scope within the function.
'''
traceback_details = {
'filename': exc_traceback.tb_frame.f_code.co_filename,
'lineno' : exc_traceback.tb_lineno,
'name' : exc_traceback.tb_frame.f_code.co_name,
'type' : exc_type.__name__,
'message' : exc_value.message, # or see traceback._some_str()
}
del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
# This still isn't "completely safe", though!
# "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
# with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
print
print traceback.format_exc()
print
print traceback_template % traceback_details
print
In specific answer to this query:
sys.exc_info()[0].__name__, os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename), sys.exc_info()[2].tb_lineno
You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier
.
Your method may look like this (provided that your only parameter is the Guid):
public static void StoreGuid(Guid guid)
{
using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandType = CommandType.StoredProcedure,
CommandText = "StoreGuid",
Parameters = {
new SqlParameter {
ParameterName = "@guid",
SqlDbType = SqlDbType.UniqueIdentifier, // right here
Value = guid
}
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
}
See also: SQL Server's uniqueidentifier
I had toolbar added in my xml. Then in my activity i was adding this statement:
setSupportActionBar(toolbar);
Removing this worked for me. I hope it helps someone.
if you have permission then
Alias /favicon.ico /var/www/aktel/workspace1/PyBot/PyBot/static/favicon.ico
add alias to your virtual host. (in apache config file ) similarly for robots.txt
Alias /robots.txt /var/www/---your path ---/PyBot/robots.txt
Return response headers with a reference parameter:
<?php
$data=array('device_token'=>'5641c5b10751c49c07ceb4',
'content'=>'????test'
);
$rtn=curl_to_host('POST', 'http://test.com/send_by_device_token', array(), $data, $resp_headers);
echo $rtn;
var_export($resp_headers);
function curl_to_host($method, $url, $headers, $data, &$resp_headers)
{$ch=curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $GLOBALS['POST_TO_HOST.LINE_TIMEOUT']?$GLOBALS['POST_TO_HOST.LINE_TIMEOUT']:5);
curl_setopt($ch, CURLOPT_TIMEOUT, $GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']?$GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']:20);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, 1);
if ($method=='POST')
{curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
foreach ($headers as $k=>$v)
{$headers[$k]=str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $k)))).': '.$v;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$rtn=curl_exec($ch);
curl_close($ch);
$rtn=explode("\r\n\r\nHTTP/", $rtn, 2); //to deal with "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK...\r\n\r\n..." header
$rtn=(count($rtn)>1 ? 'HTTP/' : '').array_pop($rtn);
list($str_resp_headers, $rtn)=explode("\r\n\r\n", $rtn, 2);
$str_resp_headers=explode("\r\n", $str_resp_headers);
array_shift($str_resp_headers); //get rid of "HTTP/1.1 200 OK"
$resp_headers=array();
foreach ($str_resp_headers as $k=>$v)
{$v=explode(': ', $v, 2);
$resp_headers[$v[0]]=$v[1];
}
return $rtn;
}
?>
New-style classes inherit from object
and must be written as such in Python 2.2 onwards (i.e. class Classname(object):
instead of class Classname:
). The core change is to unify types and classes, and the nice side-effect of this is that it allows you to inherit from built-in types.
Read descrintro for more details.
Can you place the #ulId in the document prior to the ajax load (with css display: none;), or wrap it in a containing div (with css display: none;), then just load the inner html during ajax page load, that way the scroll event will be linked to the div that is already there prior to the ajax?
Then you can use:
$('#ulId').on('scroll',function(){ console.log('Event Fired'); })
obviously replacing ulId with whatever the actual id of the scrollable div is.
Then set css display: block; on the #ulId (or containing div) upon load?
Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag
Example:
<video controls="controls" width="800" height="600"
name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>
This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)
Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)
When you do your #includes in main.c, put the #include reference to the file that contains the referenced function at the top of the include list. e.g. Say this is main.c and your referenced function is in "SSD1306_LCD.h"
#include "SSD1306_LCD.h"
#include "system.h" #include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h> // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h" // This has the 'BYTE' type definition
The above will not generate the "implicit declaration of function" error, but below will-
#include "system.h"
#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include <string.h>
#include <math.h>
#include <libpic30.h> // http://microchip.wikidot.com/faq:74
#include <stdint.h>
#include <stdbool.h>
#include "GenericTypeDefs.h" // This has the 'BYTE' type definition
#include "SSD1306_LCD.h"
Exactly the same #include list, just different order.
Well, it did for me.
You can just use Scanner to read word by word, Scanner.next() reads the next word
try {
Scanner s = new Scanner(new File(filename));
while (s.hasNext()) {
System.out.println("word:" + s.next());
}
} catch (IOException e) {
System.out.println("Error accessing input file!");
}
After several strange errors with relative paths in connectionstring I felt the need to post this here.
When using "|DataDirectory|" or "~" you are not allowed to step up and out using "../" !
Example is using several projects accessing the same localdb file placed in one of the projects.
" ~/../other" and " |DataDirectory|/../other" will fail
Even if it is clearly written at MSDN here the errors it gave where a bit unclear so hard to find and could not find it here at SO.
Try this
#include <stdio.h>
struct context;
struct funcptrs{
void (*func0)(struct context *ctx);
void (*func1)(void);
};
struct context{
struct funcptrs fps;
};
void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }
void getContext(struct context *con){
con->fps.func0 = func0;
con->fps.func1 = func1;
}
int main(int argc, char *argv[]){
struct context c;
c.fps.func0 = func0;
c.fps.func1 = func1;
getContext(&c);
c.fps.func0(&c);
getchar();
return 0;
}
Promises
don't "return" values, they pass them to a callback (which you supply with .then()).
It's probably trying to say that you're supposed to do resolve(someObject);
inside the promise implementation.
Then in your then
code you can reference someObject
to do what you want.
This is a late answer, but for completeness: it is difficult to get even close to fetching 90% all favicons.
A while ago I wrote a WordPress plugin which attempts to get closer to 100%.
This is how it works:
It starts by searching existing favicon repositories such as Google favicons and GetFavicons for the favicon.
If none of them returns an icon, the plugin attempts to get the icon itself. This involves traversing several pages on the domain.
The plugin then inspects the physical image file, because on some servers files get returned with the incorrect mime types.
The code is still not perfect because in the details you will find many weird situations: people have wrongly coded paths, e.g. img/favicon.ico
where img
is not in the root, duplicate headers in HTML output, different server responses from the head and body etc.
The core of the fetching part is here so you can reverse-engineer it, but be aware that validating the response should be done (checking image filetype, mime etc.).
You may also try downloading newest version of adb
http://developer.android.com/tools/help/adb.html
I have used POI.
If you use that, keep on eye those cell formatters: create one and use it several times instead of creating each time for cell, it isa huge memory consumption difference or large data.
#to get controller name:
<%= controller.controller_name %>
#=> 'users'
#to get action name, it is the method:
<%= controller.action_name %>
#=> 'show'
#to get id information:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
#=> '23'
# or display nicely
<%= debug Rails.application.routes.recognize_path(request.url) %>
The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.
UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this
???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????
If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this
???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????
You mean fast enumeration? You question is very unclear.
A normal for loop would look a bit like this:
unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{
// do loop stuff
id someObject = [someArray objectAtIndex:i];
}
And a loop with fast enumeration, which is optimized by the compiler, would look like this:
for(id someObject in someArray)
{
// do stuff with object
}
Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration
Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
This would change your serif latex font. You can also specify the sans-serif Helvetica like so
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
Other options are cursive
and monospace
with their respective font names.
Your label would then be
fig.gca().set_xlabel(r'wavelength $5000 \AA$')
If the font doesn't supply an Angstrom symbol you can try using \mathring{A}
the ordinary way (pun intended):
String[] myStringArray=new String[EMyEnum.values().length];
for(EMyEnum e:EMyEnum.values())myStringArray[e.ordinal()]=e.toString();
Try wrapping your entire select in brackets, then running a count(*) on that
select count(*)
from
(
select m.id
from Monitor as m
inner join Monitor_Request as mr
on mr.Company_ID=m.Company_id group by m.Company_id
having COUNT(m.Monitor_id)>=5
) myNewTable
Hasan Badshah's answer worked for me, but the method is slated to be deprecated and may be problematic for others going forward. Following the MDN web docs on alternative methods, I landed here: PerformanceNavigationTiming.type
if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
// back or forward button functionality
}
This doesn't directly solve for back button over the forward button, but was good enough for what I needed. In the docs they detail the available event data that may be helpful with solving your specific needs:
function print_nav_timing_data() {
// Use getEntriesByType() to just get the "navigation" events
var perfEntries = performance.getEntriesByType("navigation");
for (var i=0; i < perfEntries.length; i++) {
console.log("= Navigation entry[" + i + "]");
var p = perfEntries[i];
// dom Properties
console.log("DOM content loaded = " + (p.domContentLoadedEventEnd -
p.domContentLoadedEventStart));
console.log("DOM complete = " + p.domComplete);
console.log("DOM interactive = " + p.interactive);
// document load and unload time
console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
console.log("document unload = " + (p.unloadEventEnd -
p.unloadEventStart));
// other properties
console.log("type = " + p.type);
console.log("redirectCount = " + p.redirectCount);
}
}
According to the Docs at the time of this post it is still in a working draft state and is not supported in IE or Safari, but that may change by the time it is finished. Check the Docs for updates.
playing with globals() makes it possible:
import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
print '\n'.join(repr(u) for u in globals() if not u.startswith('__'))
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
print
print '\n'.join(repr((u,globals()[u])) for u in globals() if not u.startswith('__'))
one result:
'alphabet'
'random'
('hadmgoixzkcptsbwjfyrelvnqu', 'h')
('nzklv', 'o')
('alphabet', ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'))
('random', <module 'random' from 'G:\Python27\lib\random.pyc'>)
('ckpnwqguzyslmjveotxfbadh', 'f')
('i', 7)
('xwbujzkicyd', 'j')
('isjckyngxvaofdbeqwutl', 'n')
('wmt', 'g')
('aesyhvmw', 'q')
('azfjndwhkqgmtyeb', 'o')
I used random because you don't explain which names of "variables" to give, and which values to create. Because i don't think it's possible to create a name without making it binded to an object.
My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany
which explains how to do this with a @JoinColumn
annotation. In your case, i think you would want:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;
I've used a Set
rather than a List
, because the data itself is not ordered.
The above is using a defaulted referencedColumnName
, unlike the example in the wikibook. If that doesn't work, try an explicit one:
@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;
If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.
Try this snippet of code
private static boolean isStringInt(String s){
Scanner in=new Scanner(s);
return in.hasNextInt();
}
As you can see by reading the other answers, there are a lot of options available. If you are just doing < 10k rows you should go with the second option.
In short, for approx > 10k all the way to say a <100k. It is kind of a gray area. A lot of old geezers will bark at big rollback segments. But honestly hardware and software have made amazing progress to where you may be able to get away with option 2 for a lot of records if you only run the code a few times. Otherwise you should probably commit every 1k-10k or so rows. Here is a snippet that I use. I like it because it is short and I don't have to declare a cursor. Plus it has the benefits of bulk collect and forall.
begin
for r in (select rownum rn, t.* from foo t) loop
insert into bar (A,B,C) values (r.A,r.B,r.C);
if mod(rn,1000)=0 then
commit;
end if;
end;
commit;
end;
I found this link from the oracle site that illustrates the options in more detail.
Vlookup
is good if the reference values (column A, sheet 1) are in ascending order. Another option is Index and Match, which can be used no matter the order (As long as the values in column a, sheet 1 are unique)
This is what you would put in column B on sheet 2
=INDEX(Sheet1!A$1:B$6,MATCH(A1,Sheet1!A$1:A$6),2)
Setting Sheet1!A$1:B$6
and Sheet1!A$1:A$6
as named ranges makes it a little more user friendly.
Instead of using width
(which is a suggestion when using flexbox), you could use flex: 0 0 230px;
which means:
0
= don't grow (shorthand for flex-grow
)0
= don't shrink (shorthand for flex-shrink
)230px
= start at 230px
(shorthand for flex-basis
)which means: always be 230px
.
See fiddle, thanks @TylerH
Oh, and you don't need the justify-content
and align-items
here.
img {
max-width: 100%;
}
#container {
display: flex;
x-justify-content: space-around;
x-align-items: stretch;
max-width: 1200px;
}
.column.left {
width: 230px;
flex: 0 0 230px;
}
.column.right {
width: 230px;
flex: 0 0 230px;
border-left: 1px solid #eee;
}
.column.center {
border-left: 1px solid #eee;
}
If other whitespace characters are possible, then you'd want:
testString.split("\\s+");
Set following php parameters to same value in seconds:
session.cookie_lifetime
session.gc_maxlifetime
in php.ini, .htaccess or for example with
ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400);
for a day.
Links:
This is not a bug in your code. It is coming from .Net's Socket implementation. If you use the overloaded implementation of EndReceive as below you will not get this exception.
SocketError errorCode;
int nBytesRec = socket.EndReceive(ar, out errorCode);
if (errorCode != SocketError.Success)
{
nBytesRec = 0;
}
Adding manifest.file=manifest.mf into project.properties and creating manifest.mf file in the project directory works fine in NB 6.9 and should work also in NB 6.8.
If you're traversing an actual JSON string then you can use a reviver function.
function traverse (json, callback) {
JSON.parse(json, function (key, value) {
if (key !== '') {
callback.call(this, key, value)
}
return value
})
}
traverse('{"a":{"b":{"c":{"d":1}},"e":{"f":2}}}', function (key, value) {
console.log(arguments)
})
When traversing an object:
function traverse (obj, callback, trail) {
trail = trail || []
Object.keys(obj).forEach(function (key) {
var value = obj[key]
if (Object.getPrototypeOf(value) === Object.prototype) {
traverse(value, callback, trail.concat(key))
} else {
callback.call(obj, key, value, trail)
}
})
}
traverse({a: {b: {c: {d: 1}}, e: {f: 2}}}, function (key, value, trail) {
console.log(arguments)
})
Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:
GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();
and here is a more complete example.
You can't use PHP to prevent a timeout issued by nginx.
To configure nginx to allow more time see the proxy_read_timeout
directive.
Your condition id !== 0
will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block
is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null
error.
Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.
window.onload = function loadContIcons() {
var elem = document.createElement("img");
elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
elem.setAttribute("class", "up_icon");
var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
if (container !== null) {
container.appendChild(elem);
} else console.log("aaaaa");
var elem1 = document.createElement("img");
elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
elem1.setAttribute("class", "down_icon");
container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
if (container !== null) {
container.appendChild(elem1);
} else console.log("aaaaa");
}
Check out this blog post from Nemikor, which should do what you want.
http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/
Basically, before calling 'open', you 'load' the content from the other page first.
jQuery('#dialog').load('path to my page').dialog('open');
The above answer is useful but in graphs, it is difficult to distinguish between darker gradients of black. One alternative I found is to use gradients of gray colors as follows
palette(gray.colors(10, 0.9, 0.4))
plot(rep(1,10),col=1:10,pch=19,cex=3))
More info on gray scale here.
Added
When I used the code above for different colours like blue and black, the gradients were not that clear.
heat.colors()
seems more useful.
This document has more detailed information and options. pdf
from datetime import timedelta
try:
next = (x.replace(day=1) + timedelta(days=31)).replace(day=x.day)
except ValueError: # January 31 will return last day of February.
next = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)
If you simply want the first day of the next month:
next = (x.replace(day=1) + timedelta(days=31)).replace(day=1)
// Just simply add border around the image view or view
<ImageView
android:id="@+id/imageView2"
android:layout_width="90dp"
android:layout_height="70dp"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@+id/imageView1"
android:background="@android:color/white"
android:padding="5dip" />
// After that dynamically put color into your view or image view object
objView.setBackgroundColor(Color.GREEN);
//VinodJ/Abhishek
Add this method to a static class:
public static Rect GetAbsolutePlacement(this FrameworkElement element, bool relativeToScreen = false)
{
var absolutePos = element.PointToScreen(new System.Windows.Point(0, 0));
if (relativeToScreen)
{
return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
}
var posMW = Application.Current.MainWindow.PointToScreen(new System.Windows.Point(0, 0));
absolutePos = new System.Windows.Point(absolutePos.X - posMW.X, absolutePos.Y - posMW.Y);
return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
}
Set relativeToScreen
paramater to true
for placement from top left corner of whole screen or to false
for placement from top left corner of application window.
If you deleted multiple files locally and did not commit the changes, go to your local repository path, open the git shell and type.
$ git checkout HEAD .
All the deleted files before the last commit will be recovered.
Adding "." will recover all the deleted the files in the current repository, to their respective paths.
For more details checkout the documentation.
It's as easy as using select:
Get-Content file.txt | Select -Index (line - 1)
E.g. to get line 5
Get-Content file.txt | Select -Index 4
Or you can use:
(Get-Content file.txt)[4]
If you have Python installed, you can do
python -c "import datetime;print(datetime.date.today().strftime('%Y-%m-%d'))"
You can easily adapt the format string to your needs.
The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.
Your current way(@grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.
If you know the count of your columns (f.e. it's equal to a collection list). You can simply use this one liner to adjust all columns of one sheet (if you use at least java 8):
IntStream.range(0, columnCount).forEach((columnIndex) -> sheet.autoSizeColumn(columnIndex));
Type the following command to import sql data file:
$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql
In this example, import 'data.sql' file into 'blog' database using vivek as username:
$ mysql -u vivek -p -h localhost blog < data.sql
If you have a dedicated database server, replace localhost hostname with with actual server name or IP address as follows:
$ mysql -u username -p -h 202.54.1.10 databasename < data.sql
To export a database, use the following:
mysqldump -u username -p databasename > filename.sql
Note the <
and >
symbols in each case.
For windows, unix, or Mac? On the Mac or *nix you can use command line or GUI versions of emacs or vim.
For the Mac: TextWrangler to handle big files well. I'm not versed enough on the Windows landscape to help out there.
Pass the id that you want to remove from the array to the given function
from the controller( Function can be in the same controller but prefer to keep it in a service)
function removeInfo(id) {
let item = bdays.filter(function(item) {
return bdays.id=== id;
})[0];
let index = bdays.indexOf(item);
data.device.splice(indexOfTabDetails, 1);
}
I suspect that this occurs after an attempt to undeploy your app. Do you ever kill off that thread that you've initialised during the init()
process ? I would do this in the corresponding destroy()
method.
i found an easy solution, export the database, edit it what you want to edit in a text editor, then import it. Done
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
Add following codesnippet in your cofig file
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
In addition of github/hub
, which acts as a proxy to Git, you now (February 2020) have cli/cli
:
See "Supercharge your command line experience: GitHub CLI is now in beta"
Create a pull request
Create a branch, make several commits to fix the bug described in the issue, and use gh to create a pull request to share your contribution.
By using GitHub CLI to create pull requests, it also automatically creates a fork when you don’t already have one, and it pushes your branch and creates your pull request to get your change merged.
And in April 2020: "GitHub CLI now supports autofilling pull requests and custom configuration"
GitHub CLI 0.7 is out with several of the most highly requested enhancements from the feedback our beta users have provided.
Since the last minor release, 0.6, there are three main features:
- Configure
gh
to use your preferred editor withgh config set editor [editor]
.- Configure
gh
to default to SSH withgh config set git_protocol ssh
.
The default Git protocol is HTTPS.- Autofill the title and body of a pull request from your commits with
gh pr create --fill
.
So:
gh pr create --fill
Do not include bin in your JAVA_HOME env variable
You can do this in jEdit, by using the "Return value of a BeanShell snippet" option in jEdit's find and replace dialog. Just search for " [a-z]"
and replace it by " _0.toUpperCase()"
(without quotes)
In my case, this happen because of I deleted the Main.storyboard
and in general tab Main Interface
property cleared and added custom one as Start
. After I Change the Main Interface
to Start.storyboard
except Start
it's working.
remove the range
.
for i in myList
range takes in an integer. you want for each element in the list.
Most of the answers here are more or less related to application programming. Here is an example from embedded systems programming. For example below is an excerpt from the reference manual of NXP's Kinetis KL13 series microcontroller, this code snippet is used to run bootloader, which resides in ROM, from firmware:
" To get the address of the entry point, the user application reads the word containing the pointer to the bootloader API tree at offset 0x1C of the bootloader's vector table. The vector table is placed at the base of the bootloader's address range, which for the ROM is 0x1C00_0000. Thus, the API tree pointer is at address 0x1C00_001C.
The bootloader API tree is a structure that contains pointers to other structures, which have the function and data addresses for the bootloader. The bootloader entry point is always the first word of the API tree. "
uint32_t runBootloaderAddress;
void (*runBootloader)(void * arg);
// Read the function address from the ROM API tree.
runBootloaderAddress = **(uint32_t **)(0x1c00001c);
runBootloader = (void (*)(void * arg))runBootloaderAddress;
// Start the bootloader.
runBootloader(NULL);
bool exists = arr.Contains("One");
If using Vagrant try reloading your box. This solved my issue.
http://developer.android.com/reference/android/location/Location.html
Look into distanceTo or distanceBetween. You can create a Location object from a latitude and longitude:
Location location = new Location("");
location.setLatitude(lat);
location.setLongitude(lon);
setTimeout(expression, timeout);
runs the code/function once after the timeout.
setInterval(expression, timeout);
runs the code/function in intervals, with the length of the timeout between them.
Example:
var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.
setTimeout(alert, 1000); // Will alert once, after a second.
At the beginning of your file you set raw_input
to 0. Do not do this, at it modifies the built-in raw_input()
function. Therefore, whenever you call raw_input()
, it is essentially calling 0()
, which raises the error. To remove the error, remove the first line of your code:
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
Since I can't comment on answer, beware to use following solution:
$db = new PDO($dsn, $user, $password);
$sql = file_get_contents('file.sql');
$qr = $db->exec($sql);
There is a bug in PHP PDO https://bugs.php.net/bug.php?id=61613
db->exec('SELECT 1; invalidstatement; SELECT 2');
won't error out or return false (tested on PHP 5.5.14).
If you really need to check then it's better to use abstract base classes rather than concrete classes. For an integer that would mean:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
This doesn't restrict the check to just int
, or just int
and long
, but also allows other user-defined types that behave as integers to work.
Here is the code to read the excel data by column.
public ArrayList<String> extractExcelContentByColumnIndex(int columnIndex){
ArrayList<String> columndata = null;
try {
File f = new File("sample.xlsx")
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){ //To filter column headings
if(cell.getColumnIndex() == columnIndex){// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(columndata);
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
If it were about committed changes, you should have a look at git-rebase, but as pointed out in comment by VonC, as you're talking about local changes, git-stash would certainly be the good way to do this.
Building on @Tim's example to make a self-contained method:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Shell {
/** Returns null if it failed for some reason.
*/
public static ArrayList<String> command(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null )
output.add(line);
//There should really be a timeout here.
if (0 != process.waitFor())
return null;
return output;
} catch (Exception e) {
//Warning: doing this is no good in high quality applications.
//Instead, present appropriate error messages to the user.
//But it's perfectly fine for prototyping.
return null;
}
}
public static void main(String[] args) {
test("which bash");
test("find . -type f -printf '%T@\\\\t%p\\\\n' "
+ "| sort -n | cut -f 2- | "
+ "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");
}
static void test(String cmdline) {
ArrayList<String> output = command(cmdline, ".");
if (null == output)
System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
else
for (String line : output)
System.out.println(line);
}
}
(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)
By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.
Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.
If you are locked out and WiFi is turned off in your Androud device then one solution is to connect your phone to a PC (connected to internet) and try to login with your google account. - it worked for me.
Sounds like you probably want a simple method like this:
public String getValueOrDefault(String value, String defaultValue) {
return isNotNullOrEmpty(value) ? value : defaultValue;
}
Then:
String result = getValueOrDefault(System.getProperty("XYZ"), "default");
At this point, you don't need temp
... you've effectively used the method parameter as a way of initializing the temporary variable.
If you really want temp
and you don't want an extra method, you can do it in one statement, but I really wouldn't:
public class Test {
public static void main(String[] args) {
String temp, result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
System.out.println("result: " + result);
System.out.println("temp: " + temp);
}
private static boolean isNotNullOrEmpty(String str) {
return str != null && !str.isEmpty();
}
}
Here's a decent explanation of clone()
if you end up needing it...
Use tabs, they work when inputting file paths in vim escape mode!
We created this util method while working on Phonetradr which can give you type-safe access to deep properties with Typescript:
/**_x000D_
* Type-safe access of deep property of an object_x000D_
*_x000D_
* @param obj Object to get deep property_x000D_
* @param unsafeDataOperation Function that returns the deep property_x000D_
* @param valueIfFail Value to return in case if there is no such property_x000D_
*/_x000D_
export function getInSafe<O,T>(obj: O, unsafeDataOperation: (x: O) => T, valueIfFail?: any) : T {_x000D_
try {_x000D_
return unsafeDataOperation(obj)_x000D_
} catch (error) {_x000D_
return valueIfFail;_x000D_
}_x000D_
}_x000D_
_x000D_
//Example usage:_x000D_
getInSafe(sellTicket, x => x.phoneDetails.imeiNumber, '');_x000D_
_x000D_
//Example from above_x000D_
getInSafe(foo, x => x.bar.check, null);
_x000D_
if you want your datetime.now()
precise till the minute , you can use
datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')
similarly for hour it will be
datetime.strptime(datetime.now().strftime('%Y-%m-%d %H'), '%Y-%m-%d %H')
It is kind of a hack, if someone has a better solution, I am all ears
Sounds like you might want a light box,and since you didnt tag your question with jQuery included is a pure JS example of how to make one.
JS
var opener = document.getElementById("opener");
opener.onclick = function(){
var lightbox = document.getElementById("lightbox"),
dimmer = document.createElement("div");
dimmer.style.width = window.innerWidth + 'px';
dimmer.style.height = window.innerHeight + 'px';
dimmer.className = 'dimmer';
dimmer.onclick = function(){
document.body.removeChild(this);
lightbox.style.visibility = 'hidden';
}
document.body.appendChild(dimmer);
lightbox.style.visibility = 'visible';
lightbox.style.top = window.innerHeight/2 - 50 + 'px';
lightbox.style.left = window.innerWidth/2 - 100 + 'px';
return false;
}
Markup
<div id="lightbox">Testing out the lightbox</div>
<a href="#" id="opener">Click me</a>
CSS
#lightbox{
visibility:hidden;
position:absolute;
background:red;
border:2px solid #3c3c3c;
color:white;
z-index:100;
width: 200px;
height:100px;
padding:20px;
}
.dimmer{
background: #000;
position: absolute;
opacity: .5;
top: 0;
z-index:99;
}
In my case above mentioned methods work fine with php but when i try to upload files with these methods in node.js then i have some problem. So instead of using $http({..,..,...}) use the normal jquery ajax.
For select file use this
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)"/>
And in controller
$scope.uploadFile = function(element) {
var data = new FormData();
data.append('file', $(element)[0].files[0]);
jQuery.ajax({
url: 'brand/upload',
type:'post',
data: data,
contentType: false,
processData: false,
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorMessage) {
alert('Error uploading: ' + errorMessage);
}
});
};
If you are allowing anonymous users as well as those logged in with email you can use firebase.auth().currentUser.isAnonymous
, which will return either true
or false
.
@Before
(JUnit4) -> @BeforeEach
(JUnit5) - method is called before every test
@After
(JUnit4) -> @AfterEach
(JUnit5) - method is called after every test
@BeforeClass
(JUnit4) -> @BeforeAll
(JUnit5) - static method is called before executing all tests in this class. It can be a large task as starting server, read file, making db connection...
@AfterClass
(JUnit4) -> @AfterAll
(JUnit5) - static method is called after executing all tests in this class.
J(2)EE, strictly speaking, is a set of API
s (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.
In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!
J2EE was a marketing construct.
Another option is to use diffutil . It will compare the original list against the new list and use the new list as the update if there is a change.
Basically, we can use DiffUtil to compare the old data vs new data and let it call notifyItemRangeRemoved, and notifyItemRangeChanged and notifyItemRangeInserted on your behalf.
A quick example of using diffUtil instead of notifyDataSetChanged:
DiffResult diffResult = DiffUtil
.calculateDiff(new MyDiffUtilCB(getItems(), items));
//any clear up on memory here and then
diffResult.dispatchUpdatesTo(this);
//and then, if necessary
items.clear()
items.addAll(newItems)
I do the calculateDiff work off the main thread in case it's a big list.
I wrote a program with wpf
and used Database for showing images and this is my code:
SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
Initial Catalog=Payam;
Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from news", con);
DataTable dt = new DataTable();
da.Fill(dt);
string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;
Try SELECT CAST(field1 AS DECIMAL(10,2)) field1
and replace 10,2
with whatever precision you need.
You can simply use the jQuery Validate plugin as follows.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
DEMO: http://jsfiddle.net/xs5vrrso/
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js
file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension
refer to http://www.w3schools.com/php/php_mysql_select.asp . If you are a beginner and want to learn, w3schools is a good place.
<?php
$con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM employee");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
echo "<br />";
}
mysqli_close($con);
?>
You can similarly echo
it inside your table
<?php
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
}
echo "</table>";
mysqli_close($con);
?>
In the Android Studio go to File
then Close Project
. Then take the folder (in the workspace folder) of the project and copy it to a flash memory or whatever. Then when you get comfortable at home, copy this folder in the workspace folder you've already created, open the Android Studio and go to File
then Open
and import this project into your workspace.
The problem you have with this is that you're searching for the wrong term here, because in Android, exporting a project means compiling it to .apk
file (not exporting the project). Import/Export is used for the .apk
management, what you need is Open/Close project, the other thing is just copy/paste.
This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.
ALTER TRIGGER [dbo].[TR_person_AUDIT]
ON [dbo].[person]
FOR UPDATE
AS
DECLARE @bit INT,
@field INT,
@maxfield INT,
@char INT,
@fieldname VARCHAR(128),
@TableName VARCHAR(128),
@PKCols VARCHAR(1000),
@sql VARCHAR(2000),
@UpdateDate VARCHAR(21),
@UserName VARCHAR(128),
@Type CHAR(1),
@PKSelect VARCHAR(1000)
--You will need to change @TableName to match the table to be audited.
-- Here we made GUESTS for your example.
SELECT @TableName = 'PERSON'
SELECT @UserName = SYSTEM_USER,
@UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)
-- Action
IF EXISTS (
SELECT *
FROM INSERTED
)
IF EXISTS (
SELECT *
FROM DELETED
)
SELECT @Type = 'U'
ELSE
SELECT @Type = 'I'
ELSE
SELECT @Type = 'D'
-- get list of columns
SELECT * INTO #ins
FROM INSERTED
SELECT * INTO #del
FROM DELETED
-- Get primary key columns for full outer join
SELECT @PKCols = COALESCE(@PKCols + ' and', ' on')
+ ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
-- Get primary key select for insert
SELECT @PKSelect = COALESCE(@PKSelect + '+', '')
+ '''<[' + COLUMN_NAME
+ ']=''+convert(varchar(100),
coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
IF @PKCols IS NULL
BEGIN
RAISERROR('no PK on table %s', 16, -1, @TableName)
RETURN
END
SELECT @field = 0,
-- @maxfield = MAX(COLUMN_NAME)
@maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
MAX(
COLUMNPROPERTY(
OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
COLUMN_NAME,
'ColumnID'
)
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
WHILE @field < @maxfield
BEGIN
SELECT @field = MIN(
COLUMNPROPERTY(
OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
COLUMN_NAME,
'ColumnID'
)
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND COLUMNPROPERTY(
OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
COLUMN_NAME,
'ColumnID'
) > @field
SELECT @bit = (@field - 1)% 8 + 1
SELECT @bit = POWER(2, @bit - 1)
SELECT @char = ((@field - 1) / 8) + 1
IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
OR @Type IN ('I', 'D')
BEGIN
SELECT @fieldname = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND COLUMNPROPERTY(
OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
COLUMN_NAME,
'ColumnID'
) = @field
SELECT @sql =
'
insert into Audit ( Type,
TableName,
PK,
FieldName,
OldValue,
NewValue,
UpdateDate,
UserName)
select ''' + @Type + ''','''
+ @TableName + ''',' + @PKSelect
+ ',''' + @fieldname + ''''
+ ',convert(varchar(1000),d.' + @fieldname + ')'
+ ',convert(varchar(1000),i.' + @fieldname + ')'
+ ',''' + @UpdateDate + ''''
+ ',''' + @UserName + ''''
+ ' from #ins i full outer join #del d'
+ @PKCols
+ ' where i.' + @fieldname + ' <> d.' + @fieldname
+ ' or (i.' + @fieldname + ' is null and d.'
+ @fieldname
+ ' is not null)'
+ ' or (i.' + @fieldname + ' is not null and d.'
+ @fieldname
+ ' is null)'
EXEC (@sql)
END
END
You can use:
ls -lh
Using this command you'll see the apparent space of the directory and true space of the files and in details the names of the files displayed, besides the size and creation date of each.
It would be too tedious to alter function usages in all html pages to return false
.
So here is a tested solution that patches only the function itself:
function callmymethod(myVal) {
// doing custom things with myVal
// cancel default event action
var event = window.event || callmymethod.caller.arguments[0];
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
return false;
}
This correctly prevents IE6, IE11 and latest Chrome from visiting href="#"
after onclick event handler completes.
Credits:
In python member function of a class need explicit self
argument. Same as implicit this
pointer in C++. For more details please check out this page.
(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP
from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
I don't think this point has been added and since I just spent some time hunting this down I hope it can help.
I am working with IIS 7 and using the ASP.NET v4 Framework.
In my case it was important that an entry be added to both the and section of the entry in the web.config file.
My web.config file has a lot of handlers and in my case it was easiest to add the ScriptResources entry to the top of the handlers section. Most importantly, it needs to be placed before any entry that will act as a wildcard and capture the request. Adding it after a wildcard entry will cause it to be ignored and the error will still appear.
The module can be added to the top or bottom of the section.
Web.config Sample:
<system.webServer>
<handlers>
<clear />
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<!-- Make sure wildcard rules are below the ScriptResource tag -->
</handlers>
<modules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<!-- Other modules are added here -->
</modules>
</system.webServer>
BrenBarn is correct. The error means you tried to do something like None[5]
. In the backtrace, it says self.imageDef=self.values[2]
, which means that your self.values
is None
.
You should go through all the functions that update self.values
and make sure you account for all the corner cases.
Here is a version that uses a sequence or numbers table rather than a loop. You can modify the WHERE clause to suite your personal rules for when to convert a character to upper case. I have just included a simple set that will upper case any letter that is proceeded by a non-letter with the exception of apostrophes. This does how ever mean that 123apple would have a match on the "a" because "3" is not a letter. If you want just white-space (space, tab, carriage-return, line-feed), you can replace the pattern '[^a-z]'
with '[' + Char(32) + Char(9) + Char(13) + Char(10) + ']'
.
CREATE FUNCTION String.InitCap( @string nvarchar(4000) ) RETURNS nvarchar(4000) AS
BEGIN
-- 1. Convert all letters to lower case
DECLARE @InitCap nvarchar(4000); SET @InitCap = Lower(@string);
-- 2. Using a Sequence, replace the letters that should be upper case with their upper case version
SELECT @InitCap = Stuff( @InitCap, n, 1, Upper( SubString( @InitCap, n, 1 ) ) )
FROM (
SELECT (1 + n1.n + n10.n + n100.n + n1000.n) AS n
FROM (SELECT 0 AS n UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS n1
CROSS JOIN (SELECT 0 AS n UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40 UNION SELECT 50 UNION SELECT 60 UNION SELECT 70 UNION SELECT 80 UNION SELECT 90) AS n10
CROSS JOIN (SELECT 0 AS n UNION SELECT 100 UNION SELECT 200 UNION SELECT 300 UNION SELECT 400 UNION SELECT 500 UNION SELECT 600 UNION SELECT 700 UNION SELECT 800 UNION SELECT 900) AS n100
CROSS JOIN (SELECT 0 AS n UNION SELECT 1000 UNION SELECT 2000 UNION SELECT 3000) AS n1000
) AS Sequence
WHERE
n BETWEEN 1 AND Len( @InitCap )
AND SubString( @InitCap, n, 1 ) LIKE '[a-z]' /* this character is a letter */
AND (
n = 1 /* this character is the first `character` */
OR SubString( @InitCap, n-1, 1 ) LIKE '[^a-z]' /* the previous character is NOT a letter */
)
AND (
n < 3 /* only test the 3rd or greater characters for this exception */
OR SubString( @InitCap, n-2, 3 ) NOT LIKE '[a-z]''[a-z]' /* exception: The pattern <letter>'<letter> should not capatolize the letter following the apostrophy */
)
-- 3. Return the modified version of the input
RETURN @InitCap
END
Use time
Let's say you have the initial dates as strings like these:
date1 = "31/12/2015"
date2 = "01/01/2016"
You can do the following:
newdate1 = time.strptime(date1, "%d/%m/%Y")
and newdate2 = time.strptime(date2, "%d/%m/%Y")
to convert them to python's date format. Then, the comparison is obvious:
newdate1 > newdate2
will return False
newdate1 < newdate2
will return True
For window user, Please run complete command to convert *.dot file to png:
C:\Program Files (x86)\Graphviz2.38\bin\dot.exe" -Tpng sampleTest.dot > sampletest.png.....
I have found a bug in solgraph that it is utilizing older version of solidity-parser that does not seem to be intelligent enough to capture new enhancement done for solidity programming language itself e.g. emit keyword for Event
After two dozens of comments to understand the situation, it was found that the libhdf5.so.7
was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.
For future reference: other than checking LD_LIBRARY_PATH
, it's always a good idea to check a library with nm -D
to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum
revealed that the files were actually different.
size_t is the size of a pointer.
So in 32 bits or the common ILP32 (integer, long, pointer) model size_t is 32 bits. and in 64 bits or the common LP64 (long, pointer) model size_t is 64 bits (integers are still 32 bits).
There are other models but these are the ones that g++ use (at least by default)
If you have a <script>
tag anywhere on your page (even in the HTML, even if it is an empty tag with a src
), then a transition
must be activated by some event (it won't fire automatically when the page loads).
If you are using TextEditingController then set the text to it, like below
TextEditingController _controller = new TextEditingController();
_controller.text = 'your initial text';
final your_text_name = TextFormField(
autofocus: false,
controller: _controller,
decoration: InputDecoration(
hintText: 'Hint Value',
),
);
and if you are not using any TextEditingController then you can directly use initialValue like below
final last_name = TextFormField(
autofocus: false,
initialValue: 'your initial text',
decoration: InputDecoration(
hintText: 'Last Name',
),
);
For more reference TextEditingController
I faced the same issue.
String.Replace('\\.','')
is not valid statement and throws the same error.
Thanks to C# we can use double quotes instead of single quotes and following works
String.Replace("\\.","")
You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.
For getting the result you have to add a lil things in your script like
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
//echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
This will give you result;
Do a git status
to find out if your file is actually in your index or the commit.
It is easy as a beginner to misunderstand the index/staging area.
I view it as a 'progress pinboard'. I therefore have to add
the file to the pinboard before I can commit
it (i.e. a copy of the complete pinboard), I have to update the pinboard when required, and I also have to deliberately remove files from it when I've finished with them - simply creating, editing or deleting a file doesn't affect the pinboard. It's like 'storyboarding'.
Edit: As others noted, You should do the edits locally and then push the updated repo, rather than attempt to edit directly on github.
There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).
Modern¹ compilers come with the handy -fsanitize=address
flag, adding some compile time and run time overhead which does more error checking.
According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:
int main() {
volatile int *ptr = (int*)0;
*ptr = 0;
}
$ gcc -g -fsanitize=address main.c
$ ./a.out
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)
==4848==The signal is caused by a WRITE memory access.
==4848==Hint: address points to the zero page.
#0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3
#1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
#2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main
==4848==ABORTING
The output is slightly more complicated than what gdb would output but there are upsides:
There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.
ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.
¹ That is Clang 3.1+ and GCC 4.8+.