All styling including padding have to be added to a td not a span.
Another solution put the text into <p>text</p>
and define margins, and that should give the required padding.
For example:
<p style="margin-top: 10px; margin-bottom: 10; margin-right: 12; margin-left: 12;">text</p>
When you pass a string to the filter
function, the string is interpreted as SQL. Count is a SQL keyword and using count
as a variable confuses the parser. This is a small bug (you can file a JIRA ticket if you want to).
You can easily avoid this by using a column expression instead of a String:
df.groupBy("x").count()
.filter($"count" >= 2)
.show()
Basically, you just have to remove that constraint from the associated view. For instance, if is the height constraint giving warning, just remove it from your view; it will not affect the view.
Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch.
Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.
My solution is to pull on the other working copy and then do:
git log --pretty="format:" --name-only -n1 | xargs git checkout HEAD^1
which says get all the file paths in the latest comment, and check them out from the parent of HEAD. Job done.
<script>
if($(window).width() >= 1200){
(function($) {
var element = $('.to_move_content'),
originalY = element.offset().top;
// Space between element and top of screen (when scrolling)
var topMargin = 10;
// Should probably be set in CSS; but here just for emphasis
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + topMargin
}, 0);
});
})(jQuery);
}
Try this ! just add class .to_move_content to you div
Even though that this question was already answered I feel that there are missing examples in the answer that was answered.
Therefore I'll bring here what I wrote in a blog post "Android Log Levels"
Verbose
Is the lowest level of logging. If you want to go nuts with logging then you go with this level. I never understood when to use Verbose and when to use Debug. The difference sounded to me very arbitrary. I finally understood it once I was pointed to the source code of Android¹ “Verbose should never be compiled into an application except during development.” Now it is clear to me, whenever you are developing and want to add deletable logs that help you during the development it is useful to have the verbose level this will help you delete all these logs before you go into production.
Debug
Is for debugging purposes. This is the lowest level that should be in production. Information that is here is to help during development. Most times you’ll disable this log in production so that less information will be sent and only enable this log if you have a problem. I like to log in debug all the information that the app sends/receives from the server (take care not to log passwords!!!). This is very helpful to understand if the bug lies in the server or the app. I also make logs of entering and exiting of important functions.
Info
For informational messages that highlight the progress of the application. For example, when initialising of the app is finished. Add info when the user moves between activities and fragments. Log each API call but just little information like the URL , status and the response time.
Warning
When there is a potentially harmful situation.
This log is in my experience a tricky level. When do you have a potential harmful situation? In general or that it is OK or that it is an error. I personally don’t use this level much. Examples of when I use it are usually when stuff happens several times. For example, a user has a wrong password more than 3 times. This could be because he entered the password wrongly 3 times, it could also be because there is a problem with a character that isn’t being accepted in our system. Same goes with network connection problems.
Error
Error events. The application can still continue to run after the error. This can be for example when I get a null pointer where I’m not supposed to get one. There was an error parsing the response of the server. Got an error from the server.
WTF (What a Terrible Failure)
Fatal is for severe error events that will lead the application to exit. In Android the fatal is in reality the Error level, the difference is that it also adds the fullstack.
str.replace(new RegExp(".","gm")," ")
I'd use a 'where not exists' -- exactly as you suggest in your title:
SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
`voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
`voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
`household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND `Last_Name` LIKE '%Cumbee%'
AND `First_Name` LIKE '%John%'
AND NOT EXISTS (
SELECT * FROM `elimination`
WHERE `elimination`.`voter_id` = `voter`.`ID`
)
ORDER BY `Last_Name` ASC
LIMIT 30
That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.
If I ommit begin - end it is error. So for me this is working (nothing else needed):
set serveroutput on;
begin
DBMS_OUTPUT.PUT_LINE('testing');
end;
For me this code worked in JavaScript like a charm!
<%= session.getAttribute("variableName")%>
hope it helps...
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
Spring framework itself handles json conversion when controller is annotated properly.
For eg:
@PutMapping(produces = {"application/json"})
@ResponseBody
public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}
Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.
If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.
Eg:
ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);
You can change
Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
to
Range("B3:B65536").Copy
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues
BTW, if you have xls file (excel 2003), you would get an error if your lastrow
would be greater 3.
Try to use this code instead:
Sub Get_Data()
Dim lastrowDB As Long, lastrow As Long
Dim arr1, arr2, i As Integer
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")
For i = LBound(arr1) To UBound(arr1)
With Sheets("Sheet1")
lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
End With
Next
Application.CutCopyMode = False
End Sub
Note, above code determines last non empty row on DB
sheet in column A
(variable lastrowDB
). If you need to find lastrow for each destination column in DB
sheet, use next modification:
For i = LBound(arr1) To UBound(arr1)
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
End With
' NEXT CODE
Next
You could also use next approach instead Copy/PasteSpecial
. Replace
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
with
Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value
Its not possible to completely avoid RE but By making them more complex internally, you put make it more difficult for attackers to see the clear operation of the app, which may reduce the number of attack vectors.
If the application handles highly sensitive data, Various techniques exist which can increase the complexity of reverse engineering your code. One technique is to use C/C++ to limit easy runtime manipulation by the attacker. There are ample C and C++ libraries that are very mature and easy to integrate with Android offers JNI. An attacker must first circumvent the debugging restrictions in order to attack the application on a low level. This adds further complexity to an attack. Android applications should have android:debuggable=”false” set in the application manifest to prevent easy run time manipulation by an attacker or malware.
Trace Checking – An application can determine whether or not it is currently being traced by a debugger or other debugging tool. If being traced, the application can perform any number of possible attack response actions, such as discarding encryption keys to protect user data, notifying a server administrator, or other such type responses in an attempt to defend itself. This can be determined by checking the process status flags or using other techniques like comparing the return value of ptrace attach, checking parent process, blacklist debuggers in the process list or comparing timestamps on different places of the program.
Optimizations - To hide advanced mathematical computations and other types of complex logic, utilizing compiler optimizations can help obfuscate the object code so that it cannot easily be disassembled by an attacker, making it more difficult for an attacker to gain an understanding of the particular code. In Android this can more easily be achieved by utilizing natively compiled libraries with the NDK. In addition, using an LLVM Obfuscator or any protector SDK will provide better machine code obfuscation.
Stripping binaries – Stripping native binaries is an effective way to increase the amount of time and skill level required of an attacker in order to view the makeup of your application’s low level functions. By stripping a binary, the symbol table of the binary is stripped, so that an attacker cannot easily debug or reverse engineer an application.You can refer techniques used on GNU/Linux systems like sstriping or using UPX.
And at last you must be aware about obfuscation and tools like ProGuard.
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
Are you using the interactive interpreter? You can use
sys.argv[0]
You should read: How do I get the path of the current executed file in Python?
Option #1: Use ProvidePlugin
Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js
and build/webpack.prod.conf.js
so that jQuery becomes globally available to all your modules:
plugins: [
// ...
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
Option #2: Use Expose Loader module for webpack
As @TremendusApps suggests in his answer, add the Expose Loader package:
npm install expose-loader --save-dev
Use in your entry point main.js
like this:
import 'expose?$!expose?jQuery!jquery'
// ...
The following code fragment should return the size in bytes of any object passed to it, so long as it can be serialized. I got this from a colleague at Quixant to resolve a problem of writing to SRAM on a gaming platform. Hope it helps out. Credit and thanks to Carlo Vittuci.
/// <summary>
/// Calculates the lenght in bytes of an object
/// and returns the size
/// </summary>
/// <param name="TestObject"></param>
/// <returns></returns>
private int GetObjectSize(object TestObject)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
byte[] Array;
bf.Serialize(ms, TestObject);
Array = ms.ToArray();
return Array.Length;
}
The problem is
listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());
you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.
Try
private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
DefaultListModel lm1 = (DefaultListModel) listaRosa.getModel();
if(lm2 == null)
{
lm2 = new DefaultListModel();
listaTitolari.setModel(lm2);
}
lm2.addElement(listaTitolari.getSelectedValue());
lm1.removeElement(listaTitolari.getSelectedValue());
}
I had the same issue on Windows. Solved it by installing Numpy+MKL from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy (there it's recommended to install numpy+mkl before other packages that depend on it) as suggested by this answer.
Ok, you've declared junit
dependency for test
classes only (those that are in src/test/java
but you're trying to use it in main
classes (those that are in src/main/java
).
Either do not use it in main classes, or remove <scope>test</scope>
.
I resolved this problem by renaming the DLL. The DLL had been manually renamed when it was uploaded to its shared location (a version number was appended to the file name). Removing the version number from the downloaded file resolved the issue.
My solution is to cover all the range of diacritics:
([A-z0-9À-ž\s]){2,}
A-z
- this is for all latin characters
0-9
- this is for all digits
À-ž
- this is for all diacritics
\s
- this is for spaces
{2,}
- string needs to be at least 2 characters long
I got this error when I restored a database and didn't add the user account and privileges back in. Another site gave me an authentication error, so I didn't think to check that, but as soon as I added the user account back everything worked again!
SELECT * FROM Table_Name LIMIT 5;
I know the answers were correct at the time of asking the question - but since people (like me this minute) still happen to find them wondering why their WildFly 10 was behaving differently, I'd like to give an update for the current Hibernate 5.x version:
In the Hibernate 5.2 User Guide it is stated in chapter 11.2. Applying fetch strategies:
The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.
So Hibernate as well behaves like Ashish Agarwal stated above for JPA:
OneToMany: LAZY
ManyToOne: EAGER
ManyToMany: LAZY
OneToOne: EAGER
(see JPA 2.1 Spec)
Here is a function that recursively calculates the binomial coefficients using conditional expressions
def binomial(n,k):
return 1 if k==0 else (0 if n==0 else binomial(n-1, k) + binomial(n-1, k-1))
Since I can't duplicate the issue I can only suggest to try with a timeout on the ajax call. In jQuery you can set it with the $.ajaxSetup (and it will be global for all your $.ajax calls) or you can set it specifically for your call like this:
$.ajax({
type: 'GET',
url: 'http://www.mywebapp.com/keepAlive',
timeout: 15000,
success: function(data) {},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
})
JQuery will register a 15 seconds timeout on your call; after that without an http response code from the server jQuery will execute the error callback with the textStatus value set to "timeout". With this you can at least stop the ajax call but you won't be able to differentiate the real network issues from the loss of connections.
If the script only defines the functions and does nothing else, you can first execute the script within the context of the current shell using the source
or .
command and then simply call the function. See help source
for more information.
Another possible reason for this error for the Mega 2560 is if your code has three exclamation marks in a row. Perhaps in a recently added string.
3 bang marks in a row causes the Mega 2560 bootloader to go into Monitor mode from which it can not finish programming.
"!!!" <--- breaks Mega 2560 bootloader.
To fix, unplug the Arduino USB to reset the COM port and then recompile with only two exclamation points or with spaces between or whatever. Then reconnect the Arduino and program as usual.
Yes, this bit me yesterday and today I tracked down the culprit. Here is a link with more information: http://forum.arduino.cc/index.php?topic=132595.0
There is actual a hack which makes it possible to add multiline placeholders in Webkit browsers, Chrome used to work but in more recent versions they removed it:
First add the first line of your placeholder to the html5 as usual
<textarea id="text1" placeholder="Line 1" rows="10"></textarea>
then add the rest of the line by css:
#text1::-webkit-input-placeholder::after {
display:block;
content:"Line 2\A Line 3";
}
If you want to keep your lines at one place you can try the following. The downside of this is that other browsers than chrome, safari, webkit-etc. don't even show the first line:
<textarea id="text2" placeholder="." rows="10"></textarea>?
then add the rest of the line by css:
#text2::-webkit-input-placeholder{
color:transparent;
}
#text2::-webkit-input-placeholder::before {
color:#666;
content:"Line 1\A Line 2\A Line 3\A";
}
It would be very great, if s.o. could get a similar demo working on Firefox.
I'm also running XP SP2, and this works perfectly (from the command line...):
start control schedtasks
MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
int i = ds1.Tables[0].Rows.Count;
if (i > 0) {
// Exist
}
else {
// Add
}
Is there a step missing?
Yes. You need to create the directory:
mkdir ${HOME}/.ssh
Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:
% chmod 700 ~/.ssh
Should the
.ssh
dir be generated when I use thessh-keygen
command?
No. This command generates an SSH key pair but will fail if it cannot write to the required directory:
% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.
Once you've created your keys, you should also restrict who can read those key files to just yourself:
% chmod -R go-wrx ~/.ssh/*
I found this answer here: https://dba.stackexchange.com/questions/1558. In short using the following (or within my.cnf) will remove the timeout issue.
SET GLOBAL interactive_timeout = 180;
SET GLOBAL wait_timeout = 180;
This allows the connections to end if they remain in a sleep State for 3 minutes (or whatever you define).
Among other things, it can be used for security. If you have a "customer" table, you might want to give all of your sales people access to the name, address, zipcode, etc. fields, but not credit_card_number. You can create a view that only includes the columns they need access to and then grant them access on the view.
scrollTop() returns the number of pixels that are hidden from view from the scrollable area, so giving it:
$(document).height()
will actually overshoot the bottom of the page. For the scroll to actually 'stop' at the bottom of the page, the current height of the browser window needs subtracting. This will allow the use of easing if required, so it becomes:
$('html, body').animate({
scrollTop: $(document).height()-$(window).height()},
1400,
"easeOutQuint"
);
The answer clearly depends on the JVM implementation. Azul claim that their JVM
can scale ... to more than a 1/2 Terabyte of memory
By "can scale" they appear to mean "runs wells", as opposed to "runs at all".
The recommended way to do date/time manipulation is to use a Calendar
object:
Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();
Swift 3:
self.btn.sendActions(for: .touchUpInside)
You could also write
-Wl,-rpath=.
To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).
The toString()
implementation of java.util.Date
does not depend on the way the class is imported. It always returns a nice formatted date.
The toString()
you see comes from another class.
Specific import have precedence over wildcard imports.
in this case
import other.Date
import java.util.*
new Date();
refers to other.Date
and not java.util.Date
.
The odd thing is that
import other.*
import java.util.*
Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date
and java.util.Date
matches.
I recommend Derek Bruening's bar graph generator Perl script. Available at http://www.burningcutlery.com/derek/bargraph/
With MacOS Catalina, your iPhone will be displayed in the 'Locations' sidebar of Finder windows (as long as you've got the Finder preferences set up to show external devices) - you can then access the files via the 'Files' option which is available from the bar near the top of the window, just below the title (in my case I had to click the '>' at the right).
You cannot truncate a table if you don't drop the constraints. A disable also doesn't work. you need to Drop everything. i've made a script that drop all constrainsts and then recreate then.
Be sure to wrap it in a transaction ;)
SET NOCOUNT ON
GO
DECLARE @table TABLE(
RowId INT PRIMARY KEY IDENTITY(1, 1),
ForeignKeyConstraintName NVARCHAR(200),
ForeignKeyConstraintTableSchema NVARCHAR(200),
ForeignKeyConstraintTableName NVARCHAR(200),
ForeignKeyConstraintColumnName NVARCHAR(200),
PrimaryKeyConstraintName NVARCHAR(200),
PrimaryKeyConstraintTableSchema NVARCHAR(200),
PrimaryKeyConstraintTableName NVARCHAR(200),
PrimaryKeyConstraintColumnName NVARCHAR(200)
)
INSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)
SELECT
U.CONSTRAINT_NAME,
U.TABLE_SCHEMA,
U.TABLE_NAME,
U.COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME
WHERE
C.CONSTRAINT_TYPE = 'FOREIGN KEY'
UPDATE @table SET
PrimaryKeyConstraintName = UNIQUE_CONSTRAINT_NAME
FROM
@table T
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R
ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME
UPDATE @table SET
PrimaryKeyConstraintTableSchema = TABLE_SCHEMA,
PrimaryKeyConstraintTableName = TABLE_NAME
FROM @table T
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME
UPDATE @table SET
PrimaryKeyConstraintColumnName = COLUMN_NAME
FROM @table T
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME
--DROP CONSTRAINT:
DECLARE @dynSQL varchar(MAX);
DECLARE cur CURSOR FOR
SELECT
'
ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + ']
DROP CONSTRAINT ' + ForeignKeyConstraintName + '
'
FROM
@table
OPEN cur
FETCH cur into @dynSQL
WHILE @@FETCH_STATUS = 0
BEGIN
exec(@dynSQL)
print @dynSQL
FETCH cur into @dynSQL
END
CLOSE cur
DEALLOCATE cur
---------------------
--HERE GOES YOUR TRUNCATES!!!!!
--HERE GOES YOUR TRUNCATES!!!!!
--HERE GOES YOUR TRUNCATES!!!!!
truncate table your_table
--HERE GOES YOUR TRUNCATES!!!!!
--HERE GOES YOUR TRUNCATES!!!!!
--HERE GOES YOUR TRUNCATES!!!!!
---------------------
--ADD CONSTRAINT:
DECLARE cur2 CURSOR FOR
SELECT
'
ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + ']
ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ')
'
FROM
@table
OPEN cur2
FETCH cur2 into @dynSQL
WHILE @@FETCH_STATUS = 0
BEGIN
exec(@dynSQL)
print @dynSQL
FETCH cur2 into @dynSQL
END
CLOSE cur2
DEALLOCATE cur2
Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.
In 3 steps:
Generate new key php artisan key:generate
Clear the config php artisan config:clear
Update cache php artisan config:cache
Yes you can. The default location for script files is data/db
If you put any script there you can call it as
load("myjstest.js") // or
load("/data/db/myjstest.js")
you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".
I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.
Ballpark figure: there are about 1,000,000 English words, and if a hacker can compute about 10,000 SHA-512 hashes a second (update: see comment by CodesInChaos, this estimate is very low), 1,000,000 / 10,000 = 100 seconds. So it would take just over a minute to crack a single-word dictionary password for a single user. If the user concatenates two dictionary words, you're in the area of a few days, but still very possible if the attacker is cares enough. More than that and it starts getting tough.
If the password is a truly random sequence of alpha-numeric characters, upper and lower case, then the number of possible passwords of length N is 60^N (there are 60 possible characters). We'll do the calculation the other direction this time; we'll ask: What length of password could we crack given a specific length of time? Just use this formula:
N = Log60(t * 10,000)
where t is the time spent calculating hashes in seconds (again assuming 10,000 hashes a second).
1 minute: 3.2
5 minute: 3.6
30 minutes: 4.1
2 hours: 4.4
3 days: 5.2
So given a 3 days we'd be able to crack the password if it's 5 characters long.
This is all very ball-park, but you get the idea. Update: see comment below, it's actually possible to crack much longer passwords than this.
Let's clear up some misconceptions:
The salt doesn't make it slower to calculate hashes, it just means they have to crack each user's password individually, and pre-computed hash tables (buzz-word: rainbow tables) are made completely useless. If you don't have a precomputed hash-table, and you're only cracking one password hash, salting doesn't make any difference.
SHA-512 isn't designed to be hard to brute-force. Better hashing algorithms like BCrypt, PBKDF2 or SCrypt can be configured to take much longer to compute, and an average computer might only be able to compute 10-20 hashes a second. Read This excellent answer about password hashing if you haven't already.
update: As written in the comment by CodesInChaos, even high entropy passwords (around 10 characters) could be bruteforced if using the right hardware to calculate SHA-512 hashes.
The accepted answer as of September 2014 is incorrect and dangerously wrong:
In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack)... Finding a collision using a birthday attack takes O(2^n/2) time, where n is the output length of the hash function in bits.
The birthday attack is completely irrelevant to cracking a given hash. And this is in fact a perfect example of a preimage attack. That formula and the next couple of paragraphs result in dangerously high and completely meaningless values for an attack time. As demonstrated above it's perfectly possible to crack salted dictionary passwords in minutes.
The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords...
That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5...
Yes, please use an algorithm that is slow to compute, but what is "entropy-enducing"? Putting a low entropy password through a hash doesn't increase entropy. It should preserve entropy, but you can't make a rubbish password better with a hash, it doesn't work like that. A weak password put through PBKDF2 is still a weak password.
In case if you are the server and the user (e.g. you are creating an app which works via browser and you need to choose a folder) then try to call JFileChooser
from the server when some button is clicked in the browser
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
This code snipped is from here
Dictionary<string, MyType> myDico = GetDictionary();
var items = myDico.Select(d=> d.Value).ToList();
date only work with GNU date (usually comes with Linux)
for OS X, two choices:
change command (verified)
#!/bin/sh #DATE=20090801204150 #date -jf "%Y%m%d%H%M%S" $DATE "+date \"%A,%_d %B %Y %H:%M:%S\"" date "Saturday, 1 August 2009 20:41:50"
http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html
Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html
if your php version is Non-Thread-Safe (nts) you must use php extension with format example: extension=php_cl_dbg_5_2_nts.dll else if your php version is Thread-Safe (ts) you must use php extension with format example: extension=php_cl_dbg_5_2_ts.dll (notice bolded words)
So if get error like above. Firstly, check your PHP version is nts or ts, if is nts.
Then check in php.ini whether has any line like zend_extension_ts="C:\xammp\php\ext\php_dbg.dll-5.2.x" choose right version of php_dbg.dll-5.2.x from it homepage (google for it).
Change from zend_extension_ts to zend_extension_nts.
Hope this help.
For Swift 3+
Simply use UITableViewStyleGrouped
and set the footer's height to zero with the following:
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return .leastNormalMagnitude
}
Use ` backticks for MYSQL reserved words...
table name "table" is reserved word for MYSQL...
so your query should be as follows...
$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";
Index the list then the dict.
print L[1]['d']
This command works for me:
./mysql -u root -p
(PS: I'm working on mac through terminal)
For a
and b
as two DateTime
types:
DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();
SELECT * FROM sys.objects WHERE type='p' ORDER BY modify_date DESC
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
SELECT name, crdate, refdate
FROM sysobjects
WHERE type = 'P'
ORDER BY refdate desc
(I) Super Key – An attribute or a combination of attribute that is used to identify the records uniquely is known as Super Key. A table can have many Super Keys.
E.g. of Super Key
So on as any combination which can identify the records uniquely will be a Super Key.
(II) Candidate Key – It can be defined as minimal Super Key or irreducible Super Key. In other words an attribute or a combination of attribute that identifies the record uniquely but none of its proper subsets can identify the records uniquely.
E.g. of Candidate Key
For above table we have only two Candidate Keys (i.e. Irreducible Super Key) used to identify the records from the table uniquely. ID Key can identify the record uniquely and similarly combination of Name and Address can identify the record uniquely, but neither Name nor Address can be used to identify the records uniquely as it might be possible that we have two employees with similar name or two employees from the same house.
(III) Primary Key – A Candidate Key that is used by the database designer for unique identification of each row in a table is known as Primary Key. A Primary Key can consist of one or more attributes of a table.
E.g. of Primary Key - Database designer can use one of the Candidate Key as a Primary Key. In this case we have “ID” and “Name, Address” as Candidate Key, we will consider “ID” Key as a Primary Key as the other key is the combination of more than one attribute.
(IV) Foreign Key – A foreign key is an attribute or combination of attribute in one base table that points to the candidate key (generally it is the primary key) of another table. The purpose of the foreign key is to ensure referential integrity of the data i.e. only values that are supposed to appear in the database are permitted.
E.g. of Foreign Key – Let consider we have another table i.e. Department Table with Attributes “Department_ID”, “Department_Name”, “Manager_ID”, ”Location_ID” with Department_ID as an Primary Key. Now the Department_ID attribute of Employee Table (dependent or child table) can be defined as the Foreign Key as it can reference to the Department_ID attribute of the Departments table (the referenced or parent table), a Foreign Key value must match an existing value in the parent table or be NULL.
(V) Composite Key – If we use multiple attributes to create a Primary Key then that Primary Key is called Composite Key (also called a Compound Key or Concatenated Key).
E.g. of Composite Key, if we have used “Name, Address” as a Primary Key then it will be our Composite Key.
(VI) Alternate Key – Alternate Key can be any of the Candidate Keys except for the Primary Key.
E.g. of Alternate Key is “Name, Address” as it is the only other Candidate Key which is not a Primary Key.
(VII) Secondary Key – The attributes that are not even the Super Key but can be still used for identification of records (not unique) are known as Secondary Key.
E.g. of Secondary Key can be Name, Address, Salary, Department_ID etc. as they can identify the records but they might not be unique.
Yes, you'll need arrays.
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];
Or you can use the date.js library.
EDIT:
If you're going to use these frequently, you may want to extend Date.prototype
for accessibility.
(function() {
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ];
};
Date.prototype.getDayName = function() {
return days[ this.getDay() ];
};
})();
var now = new Date();
var day = now.getDayName();
var month = now.getMonthName();
Fastest way to do this would be:
int count = 0;
for(int i = 0; i < str.length(); i++) {
if(Character.isWhitespace(str.charAt(i))) count++;
}
This would catch all characters that are considered whitespace.
Regex solutions require compiling regex and excecuting it - with a lot of overhead. Getting character array requires allocation. Iterating over byte array would be faster, but only if you are sure that your characters are ASCII.
Do this
...
var el = document.getElementById('targetFrame');
var frame_win = getIframeWindow(el);
console.log(frame_win);
...
getIframeWindow is defined here
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
As you can see in the generated SQL statements the difference is not the "OR" as some may suspect. It is how the WHERE and JOIN is placed.
(example from https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships)
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
This will give you all the Blogs that have one entry with both (entry_headline_contains='Lennon') AND (entry__pub_date__year=2008), which is what you would expect from this query. Result: Book with {entry.headline: 'Life of Lennon', entry.pub_date: '2008'}
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
This will cover all the results from Example 1, but it will generate slightly more result. Because it first filters all the blogs with (entry_headline_contains='Lennon') and then from the result filters (entry__pub_date__year=2008).
The difference is that it will also give you results like: Book with {entry.headline: 'Lennon', entry.pub_date: 2000}, {entry.headline: 'Bill', entry.pub_date: 2008}
I think it is this one you need:
Book.objects.filter(inventory__user__profile__vacation=False, inventory__user__profile__country='BR')
And if you want to use OR please read: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
If sometimes a link! will not work. so create a temporary object and take all values from the writable object then change the value and assign it to the writable object. it should perfectly.
var globalObject = {
name:"a",
age:20
}
function() {
let localObject = {
name:'a',
age:21
}
this.globalObject = localObject;
}
I am a bit lazy, so I like simple things:
let users = await Users.find({}, null, {limit: 50});
Horizontal centering is as easy as:
text-align: center
Vertical centering when the container is a known height:
height: 100px;
line-height: 100px;
vertical-align: middle
Vertical centering when the container isn't a known height AND you can set the image in the background:
background: url(someimage) no-repeat center center;
A Dictionary is a Hash Table, so you have no idea the order of insertion!
If you want to know the last inserted key I would suggest extending the Dictionary to include a LastKeyInserted value.
E.g.:
public MyDictionary<K, T> : IDictionary<K, T>
{
private IDictionary<K, T> _InnerDictionary;
public K LastInsertedKey { get; set; }
public MyDictionary()
{
_InnerDictionary = new Dictionary<K, T>();
}
#region Implementation of IDictionary
public void Add(KeyValuePair<K, T> item)
{
_InnerDictionary.Add(item);
LastInsertedKey = item.Key;
}
public void Add(K key, T value)
{
_InnerDictionary.Add(key, value);
LastInsertedKey = key;
}
.... rest of IDictionary methods
#endregion
}
You will run into problems however when you use .Remove()
so to overcome this you will have to keep an ordered list of the keys inserted.
An ftl file could just have a series of html tags just as a JSP page or it can have freemarker template coding for representing the objects passed on from a controller java file.
But, its actual ability is to combine the contents of a java class and view/client side stuff(html/ JQuery/ javascript etc). It is quite similar to velocity. You could map a method or object of a class to a freemarker (.ftl) page and use it as if it is a variable or a functionality created in the very page.
Here is a new way to easily center your div using Flexbox display.
See this working fiddle: https://jsfiddle.net/5u0y5qL2/
Here is the CSS:
.layout-row {
box-sizing: border-box;
display: -webkit-box;
display: -webkit-flex;
display: flex;
-webkit-box-direction: normal;
-webkit-box-orient: horizontal;
-webkit-flex-direction: row;
flex-direction: row;
}
.layout-align-center-center {
-webkit-box-align: center;
-webkit-align-items: center;
-ms-grid-row-align: center;
align-items: center;
-webkit-align-content: center;
align-content: center;
-webkit-box-pack: center;
-webkit-justify-content: center;
justify-content: center;
}
This is achieved through URL rewriting, not through URL obfuscating, which can't be done.
Another way to do this, as has been mentioned is by changing the hashtag, with
window.location.hash = "/2131/"
You could use Timestamp.valueOf(String)
. The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...]
, so you might need to change the field separators in your incoming string.
Then again, if you're going to do that then you could just parse it yourself and use the setNanos
method to store the microseconds.
First enter "service mysqld start" and login
Like this:
int main()
{
int arr[2][5] =
{
{1,8,12,20,25},
{5,9,13,24,26}
};
}
This should be covered by your C++ textbook: which one are you using?
Anyway, better, consider using std::vector
or some ready-made matrix class e.g. from Boost.
The above methods are great, but sometimes you want to use a combination of functions for what your routine considers to be whitespace. In this case, using functors to combine operations can get messy so I prefer a simple loop I can modify for the trim. Here is a slightly modified trim function copied from the C version here on SO. In this example, I am trimming non alphanumeric characters.
string trim(char const *str)
{
// Trim leading non-letters
while(!isalnum(*str)) str++;
// Trim trailing non-letters
end = str + strlen(str) - 1;
while(end > str && !isalnum(*end)) end--;
return string(str, end+1);
}
With C# String formatting you can avoid the multiplication by 100 as it will make the code shorter and cleaner especially because of less brackets and also the rounding up code can be avoided.
(current / maximum).ToString("0.00%");
// Output - 16.67%
The following solution is fast and short enough to use in bulk operations and save extra bytes:
return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
Here is another one-line non-regexp universal solution:
return fname.slice((Math.max(0, fname.lastIndexOf(".")) || Infinity) + 1);
Both work correctly with names having no extension (e.g. myfile) or starting with .
dot (e.g. .htaccess):
"" --> ""
"name" --> ""
"name.txt" --> "txt"
".htpasswd" --> ""
"name.with.many.dots.myext" --> "myext"
If you care about the speed you may run the benchmark and check that the provided solutions are the fastest, while the short one is tremendously fast:
How the short one works:
String.lastIndexOf
method returns the last position of the substring (i.e. "."
) in the given string (i.e. fname
). If the substring is not found method returns -1
.-1
and 0
, which respectively refer to names with no extension (e.g. "name"
) and to names that start with dot (e.g. ".htaccess"
).>>>
) if used with zero affects negative numbers transforming -1
to 4294967295
and -2
to 4294967294
, which is useful for remaining the filename unchanged in the edge cases (sort of a trick here).String.prototype.slice
extracts the part of the filename from the position that was calculated as described. If the position number is more than the length of the string method returns ""
.If you want more clear solution which will work in the same way (plus with extra support of full path), check the following extended version. This solution will be slower than previous one-liners but is much easier to understand.
function getExtension(path) {
var basename = path.split(/[\\/]/).pop(), // extract file name from full path ...
// (supports `\\` and `/` separators)
pos = basename.lastIndexOf("."); // get last position of `.`
if (basename === "" || pos < 1) // if file name is empty or ...
return ""; // `.` not found (-1) or comes first (0)
return basename.slice(pos + 1); // extract extension ignoring `.`
}
console.log( getExtension("/path/to/file.ext") );
// >> "ext"
All three variants should work in any web browser on the client side and can be used in the server side NodeJS code as well.
How can I create a copy of an object in Python?
So, if I change values of the fields of the new object, the old object should not be affected by that.
You mean a mutable object then.
In Python 3, lists get a copy
method (in 2, you'd use a slice to make a copy):
>>> a_list = list('abc')
>>> a_copy_of_a_list = a_list.copy()
>>> a_copy_of_a_list is a_list
False
>>> a_copy_of_a_list == a_list
True
Shallow copies are just copies of the outermost container.
list.copy
is a shallow copy:
>>> list_of_dict_of_set = [{'foo': set('abc')}]
>>> lodos_copy = list_of_dict_of_set.copy()
>>> lodos_copy[0]['foo'].pop()
'c'
>>> lodos_copy
[{'foo': {'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]
You don't get a copy of the interior objects. They're the same object - so when they're mutated, the change shows up in both containers.
Deep copies are recursive copies of each interior object.
>>> lodos_deep_copy = copy.deepcopy(list_of_dict_of_set)
>>> lodos_deep_copy[0]['foo'].add('c')
>>> lodos_deep_copy
[{'foo': {'c', 'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]
Changes are not reflected in the original, only in the copy.
Immutable objects do not usually need to be copied. In fact, if you try to, Python will just give you the original object:
>>> a_tuple = tuple('abc')
>>> tuple_copy_attempt = a_tuple.copy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'copy'
Tuples don't even have a copy method, so let's try it with a slice:
>>> tuple_copy_attempt = a_tuple[:]
But we see it's the same object:
>>> tuple_copy_attempt is a_tuple
True
Similarly for strings:
>>> s = 'abc'
>>> s0 = s[:]
>>> s == s0
True
>>> s is s0
True
and for frozensets, even though they have a copy
method:
>>> a_frozenset = frozenset('abc')
>>> frozenset_copy_attempt = a_frozenset.copy()
>>> frozenset_copy_attempt is a_frozenset
True
Immutable objects should be copied if you need a mutable interior object copied.
>>> tuple_of_list = [],
>>> copy_of_tuple_of_list = tuple_of_list[:]
>>> copy_of_tuple_of_list[0].append('a')
>>> copy_of_tuple_of_list
(['a'],)
>>> tuple_of_list
(['a'],)
>>> deepcopy_of_tuple_of_list = copy.deepcopy(tuple_of_list)
>>> deepcopy_of_tuple_of_list[0].append('b')
>>> deepcopy_of_tuple_of_list
(['a', 'b'],)
>>> tuple_of_list
(['a'],)
As we can see, when the interior object of the copy is mutated, the original does not change.
Custom objects usually store data in a __dict__
attribute or in __slots__
(a tuple-like memory structure.)
To make a copyable object, define __copy__
(for shallow copies) and/or __deepcopy__
(for deep copies).
from copy import copy, deepcopy
class Copyable:
__slots__ = 'a', '__dict__'
def __init__(self, a, b):
self.a, self.b = a, b
def __copy__(self):
return type(self)(self.a, self.b)
def __deepcopy__(self, memo): # memo is a dict of id's to copies
id_self = id(self) # memoization avoids unnecesary recursion
_copy = memo.get(id_self)
if _copy is None:
_copy = type(self)(
deepcopy(self.a, memo),
deepcopy(self.b, memo))
memo[id_self] = _copy
return _copy
Note that deepcopy
keeps a memoization dictionary of id(original)
(or identity numbers) to copies. To enjoy good behavior with recursive data structures, make sure you haven't already made a copy, and if you have, return that.
So let's make an object:
>>> c1 = Copyable(1, [2])
And copy
makes a shallow copy:
>>> c2 = copy(c1)
>>> c1 is c2
False
>>> c2.b.append(3)
>>> c1.b
[2, 3]
And deepcopy
now makes a deep copy:
>>> c3 = deepcopy(c1)
>>> c3.b.append(4)
>>> c1.b
[2, 3]
It means that the type of the local being declared will be inferred by the compiler based upon its first assignment:
// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";
Notably, var
does not define a variable to be of a dynamic type. So this is NOT legal:
var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints
var
has only two uses:
var foo = new { Bar = "bar" };
You cannot use var
as the type of anything but locals. So you cannot use the keyword var
to declare field/property/parameter/return types.
first to check whether the key already exists
a={1:2,3:4}
a.get(1)
2
a.get(5)
None
then you can add the new key and value
Put this code where you define recycler view in activity.
rv_list.addOnItemTouchListener(
new RecyclerItemClickListener(activity, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View v, int position) {
Toast.makeText(activity, "" + position, Toast.LENGTH_SHORT).show();
}
})
);
Then make separate class and put this code:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
There's lots of FTP sites you can get into with the 'anonymous' account and download, but a 'public' site that allows anonymous uploads would be utterly swamped with pr0n and warez in short order.
It's easy enough to set up your own FTP server for testing uploads. There's plenty of them for most any desktop OS. There's one built into IIS, for instance.
i really disadvise you against using Thread.Sleep(2000)
, because of a several reasons (a few are described here), but most of all because its not useful when it comes to debugging/testing.
I recommend to use a C# Timer instead of Thread.Sleep()
. Timers let you perform methods frequently (if necessary) AND are much easiert to use in testing! There's a very nice example of how to use a timer right behind the hyperlink - just put your logic "what happens after 2 seconds" right into the Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
method.
Use a CASE statement instead of IF.
$('selector').attr( 'id', 'yourId' );
There are a lot of solutions. For example you can use at()
method.
*I assumed that you a looking for equivalent to []
operator.
This is a syntax issue, the jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.
jQuery(document).ready(function ($) {
By including the $ in parenthesis after the function call you can then use this shortcut within the code block.
For full details see WordPress Codex
Here is my simple but efficient algorithm (in C++) for calculating running median from a stream of integers:
#include<algorithm>
#include<fstream>
#include<vector>
#include<list>
using namespace std;
void runningMedian(std::ifstream& ifs, std::ofstream& ofs, const unsigned bufSize) {
if (bufSize < 1)
throw exception("Wrong buffer size.");
bool evenSize = bufSize % 2 == 0 ? true : false;
list<int> q;
vector<int> nums;
int n;
unsigned count = 0;
while (ifs.good()) {
ifs >> n;
q.push_back(n);
auto ub = std::upper_bound(nums.begin(), nums.end(), n);
nums.insert(ub, n);
count++;
if (nums.size() >= bufSize) {
auto it = std::find(nums.begin(), nums.end(), q.front());
nums.erase(it);
q.pop_front();
if (evenSize)
ofs << count << ": " << (static_cast<double>(nums[nums.size() / 2 - 1] +
static_cast<double>(nums[nums.size() / 2]))) / 2.0 << '\n';
else
ofs << count << ": " << static_cast<double>(nums[nums.size() / 2]);
}
}
}
The bufferSize
specifies the size of the numbers sequence, on which the running median must be calculated. When reading numbers from the input stream ifs
the vector of the size bufferSize
is maintained in sorted order. The median is calculated by taking the middle of the sorted vector, if bufferSize
is odd, or the sum of the two middle elements divided by 2, when bufferSize
is even. Additinally, I maintain a list of last bufferSize
elements read from input. When a new element is added, I put it in the right place in sorted vector and remove from the vector the element added bufferSize
steps before (the value of the element retained in the front of the list). In the same time I remove the old element from the list: every new element is placed on the back of the list, every old element is removed from the front. After reaching the bufferSize
, both the list and the vector stop to grow, and every insertion of a new element is compensated be deletion of an old element, placed in the list bufferSize
steps before. Note, I do not care, whether I remove from the vector exactly the element, placed bufferSize
steps before, or just an element that has the same value. For the value of median it does not matter.
All calculated median values are output in the output stream.
What about performance?
scope.applyAsync
to reduce overall digest cycles countfunction debounce(func, wait) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
func.apply(context, args);
};
if (!timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
angular.module('app.layout')
.directive('classScroll', function ($window) {
return {
restrict: 'A',
link: function (scope, element) {
function toggle() {
angular.element(element)
.toggleClass('class-scroll--scrolled',
window.pageYOffset > 0);
scope.$applyAsync();
}
angular.element($window)
.on('scroll', debounce(toggle, 50));
toggle();
}
};
});
3. If you don't need to trigger watchers/digests at all then use compile
.directive('classScroll', function ($window, utils) {
return {
restrict: 'A',
compile: function (element, attributes) {
function toggle() {
angular.element(element)
.toggleClass(attributes.classScroll,
window.pageYOffset > 0);
}
angular.element($window)
.on('scroll', utils.debounce(toggle, 50));
toggle();
}
};
});
And you can use it like <header class-scroll="header--scrolled">
The port was the easiest part, it is just a unique identifier for a socket. A socket is something processes can use to establish connections and to communicate with each other. Tall Jeff had a great telephone analogy which was not perfect, so I decided to fix it:
In terms of networking and security, the Backend is by far the most (should be) secure node.
The middle-end portion, usually being a web server, will be somewhat in the wild and cut off in many respects from a company's network. The middle-end node is usually placed in the DMZ and segmented from the network with firewall settings. Most of the server-side code parsing of web pages is handled on the middle-end web server.
Getting to the backend means going through the middle-end, which has a carefully crafted set of rules allowing/disallowing access to the vital nummies which are stored on the database (backend) server.
This one worked for me, in startup.bat
the following line needs to be added if it doesn't exist set JAVA_OPTS
with the value -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256
. The full line:
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256
Find elements:
var elements = document.getElementsByClassName('widget hover');
Since elements
is a live
array and reflects all dom changes you can remove all hover
classes with a simple while loop:
while(elements.length > 0){
elements[0].classList.remove('hover');
}
You could do this various different ways. It could be a subtle as a small status on the page saying "Loading...", or as loud as an entire element graying out the page while the new data is loading. The approach I'm taking below will show you how to accomplish both methods.
Let's start by getting us a nice "loading" animation from http://ajaxload.info I'll be using
Let's create an element that we can show/hide anytime we're making an ajax request:
<div class="modal"><!-- Place at bottom of page --></div>
Next let's give it some flair:
/* Start by setting display:none to make this hidden.
Then we position it in relation to the viewport window
with position:fixed. Width, height, top and left speak
for themselves. Background we set to 80% white with
our animation centered, and no-repeating */
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, .8 )
url('http://i.stack.imgur.com/FhHRx.gif')
50% 50%
no-repeat;
}
/* When the body has the loading class, we turn
the scrollbar off with overflow:hidden */
body.loading .modal {
overflow: hidden;
}
/* Anytime the body has the loading class, our
modal element will be visible */
body.loading .modal {
display: block;
}
Alright, on to the jQuery. This next part is actually really simple:
$body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
That's it! We're attaching some events to the body element anytime the ajaxStart
or ajaxStop
events are fired. When an ajax event starts, we add the "loading" class to the body. and when events are done, we remove the "loading" class from the body.
See it in action: http://jsfiddle.net/VpDUG/4952/
Try if this works for you. This works on FF, IE8+ and chrome. The else part applies for non-firefox browsers. Though this gives you a zoom effect, it does not actually modify the zoom value at browser level.
var currFFZoom = 1;
var currIEZoom = 100;
$('#plusBtn').on('click',function(){
if ($.browser.mozilla){
var step = 0.02;
currFFZoom += step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
} else {
var step = 2;
currIEZoom += step;
$('body').css('zoom', ' ' + currIEZoom + '%');
}
});
$('#minusBtn').on('click',function(){
if ($.browser.mozilla){
var step = 0.02;
currFFZoom -= step;
$('body').css('MozTransform','scale(' + currFFZoom + ')');
} else {
var step = 2;
currIEZoom -= step;
$('body').css('zoom', ' ' + currIEZoom + '%');
}
});
For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.
In [8]: arr
Out[8]:
array([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.]])
In [9]: arr*(arr % 2 == 0).astype(np.int)
Out[9]:
array([[ 0., 2., 0., 4., 0.],
[ 6., 0., 8., 0., 10.]])
Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2
...replaces ...
from checks import checklist(_list):
...with...
from checks import checklist
Blocks in regex are delineated by parenthesis (which are not preceded by a "\")
(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)
(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)
(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"
Then in the replace, just put the $1$2 to replace all three blocks with just the first two.
You have to call close()
on the GZIPOutputStream
before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush()
probably won't help ... though calling finish()
instead of close()
should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipTest {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String name = "/tmp/test";
GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
gz.write(10);
gz.close(); // Remove this to reproduce the reported bug
System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
}
}
(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)
A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:
(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) =
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) =
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38
I used this blog post to install it in my machine: http://luminite.wordpress.com/2012/09/06/installing-oracle-database-xe-11g-on-windows-7-64-bit-machine/
The only thing you have to do is replace a registry value during the installation, I've done it about three times already, and every time found a different reference on-line, none here on stackoverflow.
EDIT: as @kc2001 noted, regedit must be run as Administrator, and added this tutorial: (a bit more colorful): http://www.hanmiaojuan.com/2013/03/install-oracle-xe-11g-for-windows7-64bits.html
You can do it manually, by comparing with greater than or equal and less than or equal.
select * from table_name where created_at_column >= lower_date and created_at_column <= upper_date;
In our example, we need to retrieve data from a particular day to day. We will compare from the beginning of the day to the latest second in another day.
select * from table_name where created_at_column >= '2018-09-01 00:00:00' and created_at_column <= '2018-09-05 23:59:59';
The Visual Studio debugger comes with four standard visualizers. These are the text, HTML, and XML visualizers, all of which work on string objects, and the dataset visualizer, which works for DataSet, DataView, and DataTable objects.
To use it, break into your code, mouse over your DataSet, expand the quick watch, view the Tables, expand that, then view Table[0] (for example). You will see something like {Table1} in the quick watch, but notice that there is also a magnifying glass icon. Click on that icon and your DataTable will open up in a grid view.
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
ReDim Preserve arr (3)
arr(3)=newItem
for more info Redim
var myError = new Error('foo');
myError instanceof Error // true
var myString = "Whatever";
myString instanceof Error // false
Only problem with this is
myError instanceof Object // true
An alternative to this would be to use the constructor property.
myError.constructor === Object // false
myError.constructor === String // false
myError.constructor === Boolean // false
myError.constructor === Symbol // false
myError.constructor === Function // false
myError.constructor === Error // true
Although it should be noted that this match is very specific, for example:
myError.constructor === TypeError // false
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
Guideline: If you can succinctly provide an exact representation, format it as a Python expression (which implies that it can be both eval'd and copied directly into source code, in the right context). If providing an inexact representation, use <...>
format.
There are many possible representations for any value, but the one that's most interesting for Python programmers is an expression that recreates the value. Remember that those who understand Python are the target audience—and that's also why inexact representations should include relevant context. Even the default <XXX object at 0xNNN>
, while almost entirely useless, still provides type, id()
(to distinguish different objects), and indication that no better representation is available.
Time#localtime
will give you the time in the current time zone of the machine running the code:
> moment = Time.now.utc
=> 2011-03-14 15:15:58 UTC
> moment.localtime
=> 2011-03-14 08:15:58 -0700
Update: If you want to conver to specific time zones rather than your own timezone, you're on the right track. However, instead of worrying about EST vs EDT, just pass in the general Eastern Time zone -- it will know based on the day whether it is EDT or EST:
> Time.now.utc.in_time_zone("Eastern Time (US & Canada)")
=> Mon, 14 Mar 2011 11:21:05 EDT -04:00
> (Time.now.utc + 10.months).in_time_zone("Eastern Time (US & Canada)")
=> Sat, 14 Jan 2012 10:21:18 EST -05:00
you must parse JSON string to become object
var dataObject = jQuery.parseJSON(data);
so you can call it like:
success: function (data) {
var dataObject = jQuery.parseJSON(data);
if (dataObject.success == 1) {
var insertedGoalId = dataObject.inserted.goal_id;
...
...
}
}
The max length of a varchar in MySQL 5.6.12 is 4294967295.
The Collection#filter
method really does eager load all members.
Filtering at the SQL level will be added in doctrine 2.3.
Use JQuery keydown event.
$(document).keypress(function(){
if(event.which == 70){ //f
console.log("You have payed respect");
}
});
In JS; keyboard keys are identified by Javascript keycodes
It's in the python docs.
import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1),
datetime.time(10, 23))
returns
datetime.datetime(2011, 1, 1, 10, 23)
You could either access the element’s value by its name:
document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"
So:
<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />
Or you assign an ID to the element that then identifies it and you can access it with getElementById
:
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />
In JavaScript, you cannot pass variables by reference to a function. However you can pass an object by reference.
It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.
In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.
I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.
ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.
in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.
name, lastname, email in unpaidMembers.items() so you should refer data or your code might be
lastname, email in unpaidMembers.items() or name, email in unpaidMembers.items()
Thank you for your answers! They definitely led me on the right track. But none of them completely got me everything I wanted, so here's what I actually ended up doing.
The key piece of information I was missing was that I needed to put the data together in one big block, but I could still leave empty cells in it. Something like this:
Date Actual remaining Desired remaining
7/13/2009 7350 7350
7/15/2009 7100
7/21/2009 7150
7/23/2009 6600
7/27/2009 6550
8/8/2009 6525
8/16/2009 6200
11/3/2009 0
Now I have something Excel is a little better at charting. So long as I set the chart options to "Show empty cells as: Connect data points with line," it ends up looking pretty nice. Using the above test data:
Then I just needed my update macro to insert new rows above the last one to fill in new data whenever I want. My macro looks something like this:
' Find the last cell on the left going down. This will be the last cell
' in the "Date" column
Dim left As Range
Set left = Range("A1").End(xlDown)
' Move two columns to the right and select so we have the 3 final cells,
' including "Date", "Actual remaining", and "Desired remaining"
Dim bottom As Range
Set bottom = Range(left.Cells(1), left.Offset(0, 2))
' Insert a new blank row, and then move up to account for it
bottom.Insert (xlShiftDown)
Set bottom = bottom.Offset(-1)
' We are now sitting on some blank cells very close to the end of the data,
' and are ready to paste in new values for the date and new pages remaining
' (I do this by grabbing some other cells and doing a PasteSpecial into bottom)
Improvement suggestions on that macro are welcome. I just fiddled with it until it worked.
Now I have a pretty chart and I can nerd out all I want with my nerdy books for nerds.
What exactly do you want to know? ActiveRecord has methods that serialize records into JSON. For instance, open up your rails console and enter ModelName.all.to_json
and you will see JSON output. render :json
essentially calls to_json
and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback
option to specify the name of the callback you would like to call via JSONP.
For instance, lets say we have a User
model that looks like this: {name: 'Max', email:' [email protected]'}
We also have a controller that looks like this:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user
end
end
Now, if we do an AJAX call using jQuery like this:
$.ajax({
type: "GET",
url: "/users/5",
dataType: "json",
success: function(data){
alert(data.name) // Will alert Max
}
});
As you can see, we managed to get the User with id 5 from our rails app and use it in our JavaScript code because it was returned as a JSON object. The callback option just calls a JavaScript function of the named passed with the JSON object as the first and only argument.
To give an example of the callback
option, take a look at the following:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user, callback: "testFunction"
end
end
Now we can crate a JSONP request as follows:
function testFunction(data) {
alert(data.name); // Will alert Max
};
var script = document.createElement("script");
script.src = "/users/5";
document.getElementsByTagName("head")[0].appendChild(script);
The motivation for using such a callback is typically to circumvent the browser protections that limit cross origin resource sharing (CORS). JSONP isn't used that much anymore, however, because other techniques exist for circumventing CORS that are safer and easier.
In the mongo shell:
use [database];
db.dropDatabase();
And to remove the users:
db.dropAllUsers();
An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.
The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080
), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host
) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).
They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.
Just because it’s a really useful paper, here are some other figures. Please download it for full access.
Taking a look at Disk I/O:
Now looking at CPU overhead:
Now some examples of memory (read the paper for details, memory can be extra tricky):
After hours of trial and error, I've found a very easy way to put contents into scrollviews that are 'offscreen'. Tested with XCode 5 & iOS 7. You can do this almost entirely in Storyboard, using 2 small tricks/workarounds :
So far for the storyboard work, now you need to add a single line of code to the viewController's 'viewDidLoad' method to set the scrollViews contents so it contains the entire 'enclosing view'. I didn't find a way to do this in Storyboard:
- (void)viewDidLoad
{
[super viewDidLoad];
self.scrollView.contentSize = CGSizeMake(320, 800);
}
You can try doing this by adding a contentSize
keyPath as a size
to the scrollView in the Identity Inspector and setting it to (320, 1000).
I think Apple should make this easier in storyboard, in a TableViewController you can just scroll offscreen in Storyboard (just add 20 cells, and you'll see you can simply scroll), this should be possible with a ScrollViewController too.
There are some default or existing modules in node.js when you download and install node.js like http, sys etc.
Since they are already in node.js, when we want to use these modules we basically do like import modules, but why? because they are already present in the node.js. Importing is like taking them from node.js and putting them into your program. And then using them.
Whereas Exports is exactly the opposite, you are creating the module you want, let's say the module addition.js and putting that module into the node.js, you do it by exporting it.
Before I write anything here, remember, module.exports.additionTwo is same as exports.additionTwo
Huh, so that's the reason, we do like
exports.additionTwo = function(x)
{return x+2;};
Be careful with the path
Lets say you have created an addition.js module,
exports.additionTwo = function(x){
return x + 2;
};
When you run this on your NODE.JS command prompt:
node
var run = require('addition.js');
This will error out saying
Error: Cannot find module addition.js
This is because the node.js process is unable the addition.js since we didn't mention the path. So, we have can set the path by using NODE_PATH
set NODE_PATH = path/to/your/additon.js
Now, this should run successfully without any errors!!
One more thing, you can also run the addition.js file by not setting the NODE_PATH, back to your nodejs command prompt:
node
var run = require('./addition.js');
Since we are providing the path here by saying it's in the current directory ./
this should also run successfully.
Depends, Do you need the data to be loaded each time you open the view? or only once?
viewDidLoad:
Whatever processing you have that needs to be done once.
viewWilLAppear:
Whatever processing that needs to change every time the page is loaded.
Labels, icons, button titles or most dataInputedByDeveloper usually don't change. Names, photos, links, button status, lists (input Arrays for your tableViews or collectionView) or most dataInputedByUser usually do change.
If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.
void EnsureAuthenticated(string role)
{
string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
if (role != null && !Roles.IsUserInRole(parts[0], role))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}
From the client side, this helper creates a HttpClient
with the authentication header in place:
static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
return client;
}
It looks like the files npm
uses to edit its config files are not created on a clean install, as npm
has a default option for each one. This is why you can still get options with npm config get <option>
: having those files only overrides the defaults, it doesn't create the options from scratch.
I had never touched my npm config
stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc
(on a Windows 8.1 machine with Git Bash
), yet I could run npm config get <something>
and, if it was a correct npm
option, it returned a value. When I ran npm config set <option> <value>
, the file ~/.npmrc
seemed to be created automatically, with the option & its value as the only non-commented-out line.
As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc
is deleted, too, and recreated if you set
anything else later.
In your case (assuming it is still the same over a year later), it looks like you never set the proxy
option in npm
. Therefore, as npm
's config
help page says, it is set to whatever your http_proxy
(case-insensitive) environment variable is. This means there is nothing to delete
, unless you want to "delete" your HTTP proxy, although you could set
the option or environment variable to something else and hope neither breaks your set-up somehow.
Hope this one will meets your need. Supply the string to process as input and supply the words which should be bold/colored as input.
func attributedString(parentString:String, arrayOfStringToProcess:[String], color:UIColor) -> NSAttributedString
{
let parentAttributedString = NSMutableAttributedString(string:parentString, attributes:nil)
let parentStringWords = parentAttributedString.string.components(separatedBy: " ")
if parentStringWords.count != 0
{
let wordSearchArray = arrayOfStringToProcess.filter { inputArrayIndex in
parentStringWords.contains(where: { $0 == inputArrayIndex }
)}
for eachWord in wordSearchArray
{
parentString.enumerateSubstrings(in: parentString.startIndex..<parentString.endIndex, options: .byWords)
{
(substring, substringRange, _, _) in
if substring == eachWord
{
parentAttributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 15), range: NSRange(substringRange, in: parentString))
parentAttributedString.addAttribute(.foregroundColor, value: color, range: NSRange(substringRange, in: parentString))
}
}
}
}
return parentAttributedString
}
Thank you. Happy Coding.
This is a simple solution that worked for me with the same problem (I think):
mv /var/lib/mongodb /var/lib/mongodb_backup
mkdir /var/lib/mongodb
chmod 700 /var/lib/mongodb
chown mongodb:daemon /var/lib/mongodb
systemctl restart mongodb or service mongod restart
I think that I got a solution for this. You don't have to start monitor but you can use DDMS instead almost like in Eclipse.
Start Android Studio-> pick breakpoint-> Run-> Debug-> Go to %sdk\tools in Terminal window and run ddms.bat to run DDMS without Monitor running (since it won't let you run ADB). You can now start profiling or debug step-by-step.
Hope this helps you.
See image here
If you create a new Date object, by default it will be set to the current time:
import java.util.Date;
Date now = new Date();
Due to updates and changes overtime, version compatibility start causing issues with configuration.
Your webpack.config.js should be like this you can also configure how ever you dim fit.
var path = require('path');
var webpack = require("webpack");
module.exports = {
entry: './src/js/app.js',
devtool: 'source-map',
mode: 'development',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
output: {
path: path.resolve(__dirname, './src/vendor'),
filename: 'bundle.min.js'
}
};
Another Thing to notice it's the change of args, you should read babel documentation https://babeljs.io/docs/en/presets
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
NB: you have to make sure you have the above @babel/preset-env & @babel/preset-react installed in your package.json dependencies
In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:
var startTimeout = function(timeout, i){
setTimeout(function() {
myAsyncFunc(i).then(function(data){
console.log(data);
})
}, timeout);
}
var myFunc = function(){
timeout = 0;
i = 0;
while(i < 10){
// By calling a function, the i-value is going to be 1.. 10 and not always 10
startTimeout(timeout, i);
// Increase timeout by 1 sec after each call
timeout += 1000;
i++;
}
}
This examples waits 1 second after each request before sending the next one.
Here is a more concise version of the accepted answer which avoids repeating the NoteProperty identifiers and the [pscustomobject]
-cast:
$myItems = ("Joe",32,"something about him"), ("Sue",29,"something about her")
| ForEach-Object {[pscustomobject]@{name = $_[0]; age = $_[1]; info = $_[2]}}
Result:
> $myItems
name age info
---- --- ----
Joe 32 something about him
Sue 29 something about her
How can I make as "perfect" a subclass of dict as possible?
The end goal is to have a simple dict in which the keys are lowercase.
If I override
__getitem__
/__setitem__
, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?Am I preventing pickling from working, and do I need to implement
__setstate__
etc?Do I need repr, update and
__init__
?Should I just use
mutablemapping
(it seems one shouldn't useUserDict
orDictMixin
)? If so, how? The docs aren't exactly enlightening.
The accepted answer would be my first approach, but since it has some issues,
and since no one has addressed the alternative, actually subclassing a dict
, I'm going to do that here.
This seems like a rather simple request to me:
How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.
The accepted answer doesn't actually subclass dict
, and a test for this fails:
>>> isinstance(MyTransformedDict([('Test', 'test')]), dict)
False
Ideally, any type-checking code would be testing for the interface we expect, or an abstract base class, but if our data objects are being passed into functions that are testing for dict
- and we can't "fix" those functions, this code will fail.
Other quibbles one might make:
fromkeys
. The accepted answer also has a redundant __dict__
- therefore taking up more space in memory:
>>> s.foo = 'bar'
>>> s.__dict__
{'foo': 'bar', 'store': {'test': 'test'}}
dict
We can reuse the dict methods through inheritance. All we need to do is create an interface layer that ensures keys are passed into the dict in lowercase form if they are strings.
If I override
__getitem__
/__setitem__
, then get/set don't work. How do I make them work? Surely I don't need to implement them individually?
Well, implementing them each individually is the downside to this approach and the upside to using MutableMapping
(see the accepted answer), but it's really not that much more work.
First, let's factor out the difference between Python 2 and 3, create a singleton (_RaiseKeyError
) to make sure we know if we actually get an argument to dict.pop
, and create a function to ensure our string keys are lowercase:
from itertools import chain
try: # Python 2
str_base = basestring
items = 'iteritems'
except NameError: # Python 3
str_base = str, bytes, bytearray
items = 'items'
_RaiseKeyError = object() # singleton for no-default behavior
def ensure_lower(maybe_str):
"""dict keys can be any hashable object - only call lower if str"""
return maybe_str.lower() if isinstance(maybe_str, str_base) else maybe_str
Now we implement - I'm using super
with the full arguments so that this code works for Python 2 and 3:
class LowerDict(dict): # dicts take a mapping or iterable as their optional first argument
__slots__ = () # no __dict__ - that would be redundant
@staticmethod # because this doesn't make sense as a global function.
def _process_args(mapping=(), **kwargs):
if hasattr(mapping, items):
mapping = getattr(mapping, items)()
return ((ensure_lower(k), v) for k, v in chain(mapping, getattr(kwargs, items)()))
def __init__(self, mapping=(), **kwargs):
super(LowerDict, self).__init__(self._process_args(mapping, **kwargs))
def __getitem__(self, k):
return super(LowerDict, self).__getitem__(ensure_lower(k))
def __setitem__(self, k, v):
return super(LowerDict, self).__setitem__(ensure_lower(k), v)
def __delitem__(self, k):
return super(LowerDict, self).__delitem__(ensure_lower(k))
def get(self, k, default=None):
return super(LowerDict, self).get(ensure_lower(k), default)
def setdefault(self, k, default=None):
return super(LowerDict, self).setdefault(ensure_lower(k), default)
def pop(self, k, v=_RaiseKeyError):
if v is _RaiseKeyError:
return super(LowerDict, self).pop(ensure_lower(k))
return super(LowerDict, self).pop(ensure_lower(k), v)
def update(self, mapping=(), **kwargs):
super(LowerDict, self).update(self._process_args(mapping, **kwargs))
def __contains__(self, k):
return super(LowerDict, self).__contains__(ensure_lower(k))
def copy(self): # don't delegate w/ super - dict.copy() -> dict :(
return type(self)(self)
@classmethod
def fromkeys(cls, keys, v=None):
return super(LowerDict, cls).fromkeys((ensure_lower(k) for k in keys), v)
def __repr__(self):
return '{0}({1})'.format(type(self).__name__, super(LowerDict, self).__repr__())
We use an almost boiler-plate approach for any method or special method that references a key, but otherwise, by inheritance, we get methods: len
, clear
, items
, keys
, popitem
, and values
for free. While this required some careful thought to get right, it is trivial to see that this works.
(Note that haskey
was deprecated in Python 2, removed in Python 3.)
Here's some usage:
>>> ld = LowerDict(dict(foo='bar'))
>>> ld['FOO']
'bar'
>>> ld['foo']
'bar'
>>> ld.pop('FoO')
'bar'
>>> ld.setdefault('Foo')
>>> ld
{'foo': None}
>>> ld.get('Bar')
>>> ld.setdefault('Bar')
>>> ld
{'bar': None, 'foo': None}
>>> ld.popitem()
('bar', None)
Am I preventing pickling from working, and do I need to implement
__setstate__
etc?
And the dict subclass pickles just fine:
>>> import pickle
>>> pickle.dumps(ld)
b'\x80\x03c__main__\nLowerDict\nq\x00)\x81q\x01X\x03\x00\x00\x00fooq\x02Ns.'
>>> pickle.loads(pickle.dumps(ld))
{'foo': None}
>>> type(pickle.loads(pickle.dumps(ld)))
<class '__main__.LowerDict'>
__repr__
Do I need repr, update and
__init__
?
We defined update
and __init__
, but you have a beautiful __repr__
by default:
>>> ld # without __repr__ defined for the class, we get this
{'foo': None}
However, it's good to write a __repr__
to improve the debugability of your code. The ideal test is eval(repr(obj)) == obj
. If it's easy to do for your code, I strongly recommend it:
>>> ld = LowerDict({})
>>> eval(repr(ld)) == ld
True
>>> ld = LowerDict(dict(a=1, b=2, c=3))
>>> eval(repr(ld)) == ld
True
You see, it's exactly what we need to recreate an equivalent object - this is something that might show up in our logs or in backtraces:
>>> ld
LowerDict({'a': 1, 'c': 3, 'b': 2})
Should I just use
mutablemapping
(it seems one shouldn't useUserDict
orDictMixin
)? If so, how? The docs aren't exactly enlightening.
Yeah, these are a few more lines of code, but they're intended to be comprehensive. My first inclination would be to use the accepted answer, and if there were issues with it, I'd then look at my answer - as it's a little more complicated, and there's no ABC to help me get my interface right.
Premature optimization is going for greater complexity in search of performance.
MutableMapping
is simpler - so it gets an immediate edge, all else being equal. Nevertheless, to lay out all the differences, let's compare and contrast.
I should add that there was a push to put a similar dictionary into the collections
module, but it was rejected. You should probably just do this instead:
my_dict[transform(key)]
It should be far more easily debugable.
There are 6 interface functions implemented with the MutableMapping
(which is missing fromkeys
) and 11 with the dict
subclass. I don't need to implement __iter__
or __len__
, but instead I have to implement get
, setdefault
, pop
, update
, copy
, __contains__
, and fromkeys
- but these are fairly trivial, since I can use inheritance for most of those implementations.
The MutableMapping
implements some things in Python that dict
implements in C - so I would expect a dict
subclass to be more performant in some cases.
We get a free __eq__
in both approaches - both of which assume equality only if another dict is all lowercase - but again, I think the dict
subclass will compare more quickly.
MutableMapping
is simpler with fewer opportunities for bugs, but slower, takes more memory (see redundant dict), and fails isinstance(x, dict)
dict
is faster, uses less memory, and passes isinstance(x, dict)
, but it has greater complexity to implement.Which is more perfect? That depends on your definition of perfect.
Gradle version;
configurations.all {
exclude module: 'slf4j-log4j12'
}
To sort by MULTIPLE COLUMN (Sort by column_1
, and then sort by column_2
)
with open('unsorted.csv',newline='') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=";")
sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)
with open('sorted.csv', 'w') as f:
fieldnames = ['column_1', 'column_2', column_3]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in sortedlist:
writer.writerow(row)
The header function is used to send HTTP response headers back to the user (i.e. you cannot use it to create request headers.
May I ask why are you doing this? Why simulate a POST request when you can just right there and then act on the data someway? I'm assuming of course script.php resides on your server.
To create a POST request, open a up a TCP connection to the host using fsockopen(), then use fwrite() on the handler returned from fsockopen() with the same values you used in the header functions in the OP. Alternatively, you can use cURL.
I solved it by open a command prompt as an administrator and point to mysql folder -> bin -> mysql.exe. it works
Ok so I took Joshoun code and made it generic. I am not sure if I should implement singleton pattern on SynchronousPost class. Maybe someone more knowledgeble can help.
FileCategory x = new FileCategory { CategoryName = "Some Bs"};
SynchronousPost<FileCategory>test= new SynchronousPost<FileCategory>();
test.PostEntity(x, "/api/ApiFileCategories");
public class SynchronousPost<T>where T :class
{
public SynchronousPost()
{
Client = new WebClient { UseDefaultCredentials = true };
}
public void PostEntity(T PostThis,string ApiControllerName)//The ApiController name should be "/api/MyName/"
{
//this just determines the root url.
Client.BaseAddress = string.Format(
(
System.Web.HttpContext.Current.Request.Url.Port != 80) ? "{0}://{1}:{2}" : "{0}://{1}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port
);
Client.Headers.Add(HttpRequestHeader.ContentType, "application/json;charset=utf-8");
Client.UploadData(
ApiControllerName, "Post",
Encoding.UTF8.GetBytes
(
JsonConvert.SerializeObject(PostThis)
)
);
}
private WebClient Client { get; set; }
}
public class ApiFileCategoriesController : ApiBaseController
{
public ApiFileCategoriesController(IMshIntranetUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
public IEnumerable<FileCategory> GetFiles()
{
return UnitOfWork.FileCategories.GetAll().OrderBy(x=>x.CategoryName);
}
public FileCategory GetFile(int id)
{
return UnitOfWork.FileCategories.GetById(id);
}
//Post api/ApileFileCategories
public HttpResponseMessage Post(FileCategory fileCategory)
{
UnitOfWork.FileCategories.Add(fileCategory);
UnitOfWork.Commit();
return new HttpResponseMessage();
}
}
I am using ninject, and repo pattern with unit of work. Anyways, the generic class above really helps.
You can try something like this:
List<Book> books = new ArrayList<Book>();
Collections.sort(books, new Comparator<Book>(){
public int compare(Book o1, Book o2)
{
return o1.name.compareTo(o2.name);
}
});
All of the casting causes errors, nothing here I tried worked, so I fiddled around and got this to work.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value != null && (bool)row.Cells[0].Value)
{
Console.WriteLine(row.Cells[0].Value);
}
}
Why not implement your own replace?
void myReplace(std::string& str,
const std::string& oldStr,
const std::string& newStr)
{
std::string::size_type pos = 0u;
while((pos = str.find(oldStr, pos)) != std::string::npos){
str.replace(pos, oldStr.length(), newStr);
pos += newStr.length();
}
}
You should use like this:
body { background: url("img/debut_dark.png") repeat 0 0; } body { background: url("../img/debut_dark.png") repeat 0 0; } body { background-image: url("../img/debut_dark.png") repeat 0 0; }
or try Inspecting CSS Rules using Firefox Firebug tool.
Add as first row or last row in a table
To add as first row in table
$(".table tbody").append("<tr><td>New row</td></tr>");
To add as last row in table
$(".table tbody").prepend("<tr><td>New row</td></tr>");
Try this...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
.....
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_landing_page);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
.....
}
<button id="fwdbtn" style="color:red">Submit</button>
<v-container>
has to be right after <template>
, if there is a <div>
in between, the vertical align will just not work.
<template>
<v-container fill-height>
<v-row class="justify-center align-center">
<v-col cols="12" sm="4">
Centered both vertically and horizontally
</v-col>
</v-row>
</v-container>
</template>
To concatenate two strings in 2008 or prior:
SELECT ISNULL(FirstName, '') + ' ' + ISNULL(SurName, '')
good to use ISNULL because "String + NULL" will give you a NULL only
One more thing: Make sure you are concatenating strings otherwise use a CAST operator:
SELECT 2 + 3
Will give 5
SELECT '2' + '3'
Will give 23
For long time I was looking for a function able to properly decompose file path. For me this code is working perfectly for both Linux and Windows.
void decomposePath(const char *filePath, char *fileDir, char *fileName, char *fileExt)
{
#if defined _WIN32
const char *lastSeparator = strrchr(filePath, '\\');
#else
const char *lastSeparator = strrchr(filePath, '/');
#endif
const char *lastDot = strrchr(filePath, '.');
const char *endOfPath = filePath + strlen(filePath);
const char *startOfName = lastSeparator ? lastSeparator + 1 : filePath;
const char *startOfExt = lastDot > startOfName ? lastDot : endOfPath;
if(fileDir)
_snprintf(fileDir, MAX_PATH, "%.*s", startOfName - filePath, filePath);
if(fileName)
_snprintf(fileName, MAX_PATH, "%.*s", startOfExt - startOfName, startOfName);
if(fileExt)
_snprintf(fileExt, MAX_PATH, "%s", startOfExt);
}
Example results are:
[]
fileDir: ''
fileName: ''
fileExt: ''
[.htaccess]
fileDir: ''
fileName: '.htaccess'
fileExt: ''
[a.exe]
fileDir: ''
fileName: 'a'
fileExt: '.exe'
[a\b.c]
fileDir: 'a\'
fileName: 'b'
fileExt: '.c'
[git-archive]
fileDir: ''
fileName: 'git-archive'
fileExt: ''
[git-archive.exe]
fileDir: ''
fileName: 'git-archive'
fileExt: '.exe'
[D:\Git\mingw64\libexec\git-core\.htaccess]
fileDir: 'D:\Git\mingw64\libexec\git-core\'
fileName: '.htaccess'
fileExt: ''
[D:\Git\mingw64\libexec\git-core\a.exe]
fileDir: 'D:\Git\mingw64\libexec\git-core\'
fileName: 'a'
fileExt: '.exe'
[D:\Git\mingw64\libexec\git-core\git-archive.exe]
fileDir: 'D:\Git\mingw64\libexec\git-core\'
fileName: 'git-archive'
fileExt: '.exe'
[D:\Git\mingw64\libexec\git.core\git-archive.exe]
fileDir: 'D:\Git\mingw64\libexec\git.core\'
fileName: 'git-archive'
fileExt: '.exe'
[D:\Git\mingw64\libexec\git-core\git-archiveexe]
fileDir: 'D:\Git\mingw64\libexec\git-core\'
fileName: 'git-archiveexe'
fileExt: ''
[D:\Git\mingw64\libexec\git.core\git-archiveexe]
fileDir: 'D:\Git\mingw64\libexec\git.core\'
fileName: 'git-archiveexe'
fileExt: ''
I hope this helps you also :)
The easiest way to handle the Authentication Pop up is to enter the Credentials in Url Itself. For Example, I have Credentials like Username: admin
and Password: admin
:
WebDriver driver = new ChromeDriver();
driver.get("https://admin:admin@your website url");
As of Rails 4 you can't generate a migration to add a column to a table with a default value, The following steps add a new column to an existing table with default value true or false.
$ rails generate migration add_columnname_to_tablename columnname:boolean
The above command will add a new column in your table.
class AddColumnnameToTablename < ActiveRecord::Migration
def change
add_column :table_name, :column_name, :boolean, default: false
end
end
$ rake db:migrate
For several cases, or even just a few cases involving a lot of criteria, consider using a switch.
switch( true ){
case ( !empty($youtube) && !empty($link) ):{
// Nothing is empty...
break;
}
case ( !empty($youtube) && empty($link) ):{
// One is empty...
break;
}
case ( empty($youtube) && !empty($link) ):{
// The other is empty...
break;
}
case ( empty($youtube) && empty($link) ):{
// Everything is empty
break;
}
default:{
// Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
// That way if you change it, or miss a case, you have some default handler.
break;
}
}
If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.
Note that the { } around the cases aren't required, but they are nice for readability and code folding.
More about switch: http://php.net/manual/en/control-structures.switch.php
The C++ ? General ? Additional Include Directories parameter is for listing directories where the compiler will search for header files.
You need to tell the linker where to look for libraries to link to. To access this setting, right-click on the project name in the Solution Explorer window, then Properties ? Linker ? General ? Additional Library Directories. Enter <boost_path>\stage\lib
here (this is the path where the libraries are located if you build Boost using default options).
I had this in a new project on Windows. npm install
had created a node_modules
folder for me, but it had somehow created the folder without giving me full control over it. I gave myself full control over node_modules
and node_modules\.staging
and it worked after that.
var_dump($obj);
If you want more info you can use a ReflectionClass:
Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a SourceMap is, I suggest you check out this answer, where it explains how it's something that helps you debug:
The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.
First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jquery, font-awesome, preload and so on.. (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your js/css destination folder)
Second solution (the one I used): add the source files using a CDN (here all the advantages of using a CDN). Using the Content delivery network (CDN) you can simply add the cdn link, instead of the path to your folder. You can find cdn on official websites (Bootstrap, jquery, popper, etc..) or you can easily search on some websites like cloudflare, cdnjs, etc..
The \s
metacharacter matches whitespace characters.
By default reference types have reference equality (i.e. two instances are only equal if they are the same object).
You need to override Object.Equals
(and Object.GetHashCode
to match) to implement your own equality. (And it is then good practice to implement an equality, ==
, operator.)
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
private ViewPager viewPager;
viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
Your @drawable/list_divide
should look like this:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="line">
<stroke
android:height="1dp"
android:color="#8F8F8F"
android:dashWidth="1dp"
android:dashGap="1dp" />
</shape>
In your version you provide an android:width="1dp"
, simply change it to an android:height="1dp"
and it should work!
My issue was caused by missing bindings in IIS, in the left tree view "Connections", under Sites, Right click on your site > edit bindings > add > https
Choose 'IIS Express Development Certificate' and set port to 443 Then I added another binding to the webconfig:
<endpoint address="wsHttps" binding="wsHttpBinding" bindingConfiguration="DefaultWsHttpBinding" name="Your.bindingname" contract="Your.contract" />
Also added to serviceBehaviours:
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
And eventually it worked, none of the solutions I checked on stackoverflow for this error was applicable to my specific scenario, so including here in case it helps others
Be Careful while using INPUT. This event fires on focus and on blur in IE 11. But it is triggered on change in other browsers.
https://connect.microsoft.com/IE/feedback/details/810538/ie-11-fires-input-event-on-focus
To start redis with a config file all you need to do is specifiy the config file as an argument:
redis-server /root/config/redis.rb
Instead of using and killing PID's I would suggest creating an init script for your service
I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start
and service redis_server stop
to control your server.
I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.
Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?
As noted in another comment, SA() isn't returning anything explicitly.
http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html
Edit:
From Generating random number between [-1, 1] in C?
((float)rand())/RAND_MAX
returns a floating-point number in [0,1]
When I tried yorammi's solution I was taken to Slack, but not the channel I specified.
I had better luck with:
https://<organization>.slack.com/messages/#<channel>/
and
https://<organization>.slack.com/messages/<channel>/details/
Although, they were both still displayed in a browser window and not the app.
For me i put this codes in public\index.php
file. and it worked just fine for all CRUD operations.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");
given your example above - to find processes attached to shmid 98306
lsof | egrep "98306|COMMAND"
Whenever you face this issue, just define the web element once again above the line in which you are getting an Error.
WebElement button = driver.findElement(By.xpath("xpath"));
button.click();
//here you do something like update or save
//then you try to use the button WebElement again to click
button.click();
Since the DOM has changed e.g. through the update action, you are receiving a StaleElementReference
Error.
WebElement button = driver.findElement(By.xpath("xpath"));
button.click();
//here you do something like update or save
//then you define the button element again before you use it
WebElement button1 = driver.findElement(By.xpath("xpath"));
//that new element will point to the same element in the new DOM
button1.click();
My example
private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
My method
getUserByName(name: string): Observable<MyObject[]> {
//set request params
let params: URLSearchParams = new URLSearchParams();
params.set("name", name);
//params.set("surname", surname); for more params
this.options.search = params;
let url = "http://localhost:8080/test/user/";
console.log("url: ", url);
return this.http.get(url, this.options)
.map((resp: Response) => resp.json() as MyObject[])
.catch(this.handleError);
}
private handleError(err) {
console.log(err);
return Observable.throw(err || 'Server error');
}
in my component
userList: User[] = [];
this.userService.getUserByName(this.userName).subscribe(users => {
this.userList = users;
});
By postman
http://localhost:8080/test/user/?name=Ethem
The Global.asax can be used to handle events arising from the application. This link provides a good explanation: http://aspalliance.com/1114
xml4jQuery plugin gives sleep(ms,callback) method. Remaining chain would be executed after sleep period.
$(".toFill").html("Click here")
.$on('click')
.html('Loading...')
.sleep(1000)
.html( 'done')
.toggleClass('clickable')
.prepend('Still clickable <hr/>');
_x000D_
.toFill{border: dashed 2px palegreen; border-radius: 1em; display: inline-block;padding: 1em;}
.clickable{ cursor: pointer; border-color: blue;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.xml4jquery.com/ajax/libs/xml4jquery/1.1.2/xml4jquery.js"></script>
<div class="toFill clickable"></div>
_x000D_
$('input[type=checkbox]').change(function () {
alert('changed');
});
You could either use a lookahead assertion like others have suggested. Or, if you just want to use basic regular expression syntax:
^(.?$|[^m].+|m[^y].*)
This matches strings that are either zero or one characters long (^.?$
) and thus can not be my
. Or strings with two or more characters where when the first character is not an m
any more characters may follow (^[^m].+
); or if the first character is a m
it must not be followed by a y
(^m[^y]
).
Just Need to Start MySQL Service after installation:
For Ubuntu:
sudo service mysql start;
For CentOS or RHEL:
sudo service mysqld start;
There are a couple ways to do this.
First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:
E:\> openssl x509 -pubkey -noout -in cert.pem > pubkey.pem
If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.
openssl> x509 -pubkey -noout -in cert.pem
Output will look something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----
list = [1, 2, 3, 4, 5]
for i in list[0:-1]:
print(i, end=', ')
print(list[-1])
do for loops really take that much longer to run?
was trying to make something that printed all str values in a list separated by commas, inserting "and" before the last entry and came up with this:
spam = ['apples', 'bananas', 'tofu', 'cats']
for i in spam[0:-1]:
print(i, end=', ')
print('and ' + spam[-1])
Doesn't log4j just use the application root directory if you don't specify a root directory in your FileAppender's path property? So you should just be able to use:
log4j.appender.file.File=logs/MyLog.log
It's been awhile since I've done Java web development, but this seems to be the most intuitive, and also doesn't collide with other unfortunately named logs writing to the ${catalina.home}/logs directory.
<?php
$post = ['batch_id'=> "2"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch); // Close the connection
$new= $result->status;
if( $new =="1")
{
echo "<script>alert('Student list')</script>";
}
else
{
echo "<script>alert('Not Removed')</script>";
}
?>
I searched all over the internet for an answer for this question. none worked for me except this code. Guaranteed. It work perfectly.
$('body').on('hidden.bs.modal', '.modal', function () {
$('video').trigger('pause');
});
I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.
import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
, password="***"
, port="5432"
, database="myDB"
, host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()
myList = [...]
for item in myList:
cursor_psql.execute('''
-- The query goes here
''')
connection_psql.commit()
cursor_psql.close()
A modern approach for the best answer (without deprecated e.keyCode):
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent> event;
if (['Delete', 'Backspace', 'Tab', 'Escape', 'Enter', 'NumLock', 'ArrowLeft', 'ArrowRight', 'End', 'Home', '.'].indexOf(e.key) !== -1 ||
// Allow: Ctrl+A
(e.key === 'a' && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+C
(e.key === 'c' && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+V
(e.key === 'v' && (e.ctrlKey || e.metaKey)) ||
// Allow: Ctrl+X
(e.key === 'x' && (e.ctrlKey || e.metaKey))) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].indexOf(e.key) === -1)) {
e.preventDefault();
}
}
You can declare the books (on line 2) as an array:
title: any = 'List of books are represted in the bookstore';
books: any = [];
constructor(private service: AppService){
}
ngOnInit(){
this.getBookDetails();
}
getBookDetails() {
this.service.getBooks().subscribe(books => {
this.books = books.json();
console.log(this.books);
});
}
Just go to your app/storage/logs
there logs of error
available. Go to filename of today's date time and you will find latest error
in your application.
OR
Open app/config/app.php
and change setting
'debug' => false,
To
'debug' => true,
OR
Go to .env
file to your application and change the configuratuion
APP_LOG_LEVEL=debug
There is an algorithm that I studied in school that you can use to compute exact square roots (or of arbitrarily large precision if the root is an irrational number). It is definitely slower than Newton's algorithms but it is exact. Lets say you want to compute the square root of 531.3025
First thing is you divide your number starting from the decimal point into groups of 2 digits:
{5}{31}.{30}{25}
Then:
1) Find the closest square root for first group that is smaller or equal to the actual square root of first group: sqrt({5}) >= 2. This square root is the first digit of your final answer. Lets denote the digits we have already found of our final square root as B. So at the moment B = 2.
2) Next compute the difference between {5} and B^2: 5 - 4 = 1.
3) For all subsequent 2 digit groups do the following:
Multiply the remainder by 100, then add it to the second group: 100 + 31 = 131.
Find X - next digit of your root, such that 131 >=((B*20) + X)*X. X = 3. 43 * 3 = 129 < 131. Now B = 23. Also because you have no more 2-digit groups to the left of decimal points, you have found all integer digits of your final root.
4)Repeat the same for {30} and {25}. So you have:
{30} : 131 - 129 = 2. 2 * 100 + 30 = 230 >= (23*2*10 + X) * X -> X = 0 -> B = 23.0
{25} : 230 - 0 = 230. 230 * 100 + 25 = 23025. 23025 >= (230 * 2 * 10 + X) * X -> X = 5 -> B = 23.05
Final result = 23.05.
The algorithm looks complicated this way but it is much simpler if you do it on paper using the same notation you use for "long division" you have studied in school, except that you don't do division but instead compute the square root.
fetch("http://localhost:8988/api", {
//mode: "no-cors",
method: "GET",
headers: {
"Accept": "application/json"
}
})
.then(response => {
return response.json();
})
.then(data => {
return data;
})
.catch(error => {
return error;
});
This works for me.
Get the id of the div
whose content you want to change then assign the text as below:
var myDiv = document.getElementById("divId");
myDiv.innerHTML = "Content To Show";
Add this
node_modules/
to .gitignore
file to ignore all directories called node_modules
in current folder and any subfolders
If you need it to work in IE7, you can't use the undocumented, buggy, and unsupported {'width':'auto'}
option. Instead, add the following to your .dialog()
:
'open': function(){ $(this).dialog('option', 'width', this.scrollWidth) }
Whether .scrollWidth
includes the right-side padding depends on the browser (Firefox differs from Chrome), so you can either add a subjective "good enough" number of pixels to .scrollWidth
, or replace it with your own width-calculation function.
You might want to include width: 0
among your .dialog()
options, since this method will never decrease the width, only increase it.
Tested to work in IE7, IE8, IE9, IE10, IE11, Firefox 30, Chrome 35, and Opera 22.
There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. @interface MyClass ()
) called Class Extension. What's unique about a class extension is that the method implementations must go in the same @implementation MyClass
as the public methods. So I structure my classes like this:
In the .h file:
@interface MyClass {
// My Instance Variables
}
- (void)myPublicMethod;
@end
And in the .m file:
@interface MyClass()
- (void)myPrivateMethod;
@end
@implementation MyClass
- (void)myPublicMethod {
// Implementation goes here
}
- (void)myPrivateMethod {
// Implementation goes here
}
@end
I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction.
No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:
if (str != null && !str.isEmpty()) {
doSomethingWith(str.charAt(0));
}
or, the other way around
if (str == null || str.isEmpty()) {
complainAboutUnusableString();
} else {
doSomethingWith(str.charAt(0));
}
If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.
Adapting the PATH
should work. Just tried on my Git bash:
$ python --version
sh.exe": python: command not found
$ PATH=$PATH:/c/Python27/
$ python --version
Python 2.7.6
In particular, only provide the directory; don't specify the .exe
on the PATH
; and use slashes.
<div class="post_category">
<?php $category = get_the_category();
$allcategory = get_the_category();
foreach ($allcategory as $category) {
?>
<a class="btn"><?php echo $category->cat_name;; ?></a>
<?php
}
?>
</div>