The answer to your original question
How to read a string one char at the time, and stop when you reach end of line?
is, in C++, very simply, namely: use getline. The link shows a simple example:
#include <iostream>
#include <string>
int main () {
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Hello, " << name << "!\n";
return 0;
}
Do you really want to do this in C? I wouldn't! The thing is, in C, you have to allocate the memory in which to place the characters you read in? How many characters? You don't know ahead of time. If you allocate too few characters, you will have to allocate a new buffer every time to realize you reading more characters than you made room for. If you over-allocate, you are wasting space.
C is a language for low-level programming. If you are new to programming and writing simple applications for reading files line-by-line, just use C++. It does all that memory allocation for you.
Your later questions regarding "\0"
and end-of-lines in general were answered by others and do apply to C as well as C++. But if you are using C, please remember that it's not just the end-of-line that matters, but memory allocation as well. And you will have to be careful not to overrun your buffer.
I use volatile fields when said field is ONLY UPDATED by its owner thread and the value is only read by other threads, you can think of it as a publish/subscribe scenario where there are many observers but only one publisher. However if those observers must perform some logic based on the value of the field and then push back a new value then I go with Atomic* vars or locks or synchronized blocks, whatever suits me best. In many concurrent scenarios it boils down to get the value, compare it with another one and update if necessary, hence the compareAndSet and getAndSet methods present in the Atomic* classes.
Check the JavaDocs of the java.util.concurrent.atomic package for a list of Atomic classes and an excellent explanation of how they work (just learned that they are lock-free, so they have an advantage over locks or synchronized blocks)
Set<E> alphaSet = new HashSet<E>(<your List>);
or complete example
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListToSet
{
public static void main(String[] args)
{
List<String> alphaList = new ArrayList<String>();
alphaList.add("A");
alphaList.add("B");
alphaList.add("C");
alphaList.add("A");
alphaList.add("B");
System.out.println("List values .....");
for (String alpha : alphaList)
{
System.out.println(alpha);
}
Set<String> alphaSet = new HashSet<String>(alphaList);
System.out.println("\nSet values .....");
for (String alpha : alphaSet)
{
System.out.println(alpha);
}
}
}
@tvanfosson rocks with his answer.
However, I would suggest an improvement within js and a small controller check.
When we use @Url
helper to call an action, we are going to receive a formatted html. It would be better to update the content (.html
) not the actual element (.replaceWith
).
More about at: What's the difference between jQuery's replaceWith() and html()?
$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
$('#detailsDiv').html(data);
});
This is specially useful in trees, where the content can be changed several times.
At the controller we can reuse the action depending on requester:
public ActionResult Details( int id )
{
var model = GetFooModel();
if (Request.IsAjaxRequest())
{
return PartialView( "UserDetails", model );
}
return View(model);
}
Modern Javascript implementations with the template
syntax using backticks are also an easy way to assign an HTML block of code to a variable:
const firstName = 'Sam';
const fullName = 'Sam Smith';
const htmlString = `<h1>Hello ${fullName}!</h1><p>This is some content \
that will display. You can even inject your first name, ${firstName}, \
in the code.</p><p><a href="http://www.google.com">Search</a> for \
stuff on the Google website.</p>`;
Isn't your issue that you're setting the webkitAnimationName back to nothing so that's resetting the CSS for your object back to it's default state. Won't it stay where it ended up if you just remove the setTimeout function that's resetting the state?
I think this will do the same thing as the original poster intended:
git add .
Adding some caveats:
git status
and confirmed your local directories are cleangit diff
on each file reported in git status
, and confirmed your changes are cleanNow, my friend, you are ready to git add .
with impunity.
If you're using a jupyter notebook, I found this to be the simplest solution for one off cases. Basically convert the numpy array to a list and then to a string and then print. This has the benefit of keeping the comma separators in the array, whereas using numpyp.printoptions(threshold=np.inf)
does not:
import numpy as np
print(str(np.arange(10000).reshape(250,40).tolist()))
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
check the error with mysqli_error() function
probably your query has some faults.
Also:
func getTime() -> (hour: Int, minute: Int,second: Int) {
let hour = 1
let minute = 2
let second = 3
return ( hour, minute, second)
}
Then it's invoked as:
let time = getTime()
print("hour: \(time.hour), minute: \(time.minute), second: \(time.second)")
This is the standard way how to use it in the book The Swift Programming Language written by Apple.
or just like:
let time = getTime()
print("hour: \(time.0), minute: \(time.1), second: \(time.2)")
it's the same but less clearly.
MainLabel:BEGIN
IF (<condition>) IS NOT NULL THEN
LEAVE MainLabel;
END IF;
....code
i.e.
IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
LEAVE MainLabel;
END IF;
C++20 std::format
This is now the cleanest method in my opinion, as it does not pollute std::cout
state with std::hex
:
main.cpp
#include <format>
#include <string>
int main() {
std::cout << std::format("{:x} {:#x} {}\n", 16, 17, 18);
}
Expected output:
10 0x11 18
Not yet implemented on GCC 10.0.1, Ubuntu 20.04.
But the awesome library that became C++20 and should be the same worked once installed with:
git clone https://github.com/fmtlib/fmt
cd fmt
git checkout 061e364b25b5e5ca7cf50dd25282892922375ddc
mkdir build
cmake ..
sudo make install
main2.cpp
#include <fmt/core.h>
#include <iostream>
int main() {
std::cout << fmt::format("{:x} {:#x} {}\n", 16, 17, 18);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main2.out main2.cpp -lfmt
./main2.out
Documented at:
More info at: std::string formatting like sprintf
Pre-C++20: cleanly print and restore std::cout
to previous state
main.cpp
#include <iostream>
#include <string>
int main() {
std::ios oldState(nullptr);
oldState.copyfmt(std::cout);
std::cout << std::hex;
std::cout << 16 << std::endl;
std::cout.copyfmt(oldState);
std::cout << 17 << std::endl;
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
10
17
More details: Restore the state of std::cout after manipulating it
Tested on GCC 10.0.1, Ubuntu 20.04.
The solution for me was that default-ssl
was not enabled in apache 2.... just putting SSLEngine On
I had to execute a2ensite default-ssl
and everything worked.
With java-9 and above, as suggested in JEP 269: Convenience Factory Methods for Collections, this could be achieved using collection literals now with -
List<String> list = List.of("A", "B", "C");
Set<String> set = Set.of("A", "B", "C");
A similar approach would apply to Map
as well -
Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")
which is similar to Collection Literals proposal as stated by @coobird. Further clarified in the JEP as well -
Alternatives
Language changes have been considered several times, and rejected:
Project Coin Proposal, 29 March 2009
Project Coin Proposal, 30 March 2009
JEP 186 discussion on lambda-dev, January-March 2014
The language proposals were set aside in preference to a library-based proposal as summarized in this message.
Related: What is the point of overloaded Convenience Factory Methods for Collections in Java 9
this an example using a matrix.
cout<<setprecision(4)<<fixed<<m[i][j]
:set list
in Vim will show whitespace. End of lines show as '$
' and carriage returns usually show as '^M
'.
query
runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
execute
runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute
will also perform better if you are repeating a query multiple times. Example of prepared statements:
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
// data is separated from the query
Best practice is to stick with prepared statements and execute
for increased security.
See also: Are PDO prepared statements sufficient to prevent SQL injection?
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
If you don't want to have to add the stop propagation to all links this works as well. A bit more scalable.
$scope.hideOverlay( $event ){
// only hide the overlay if we click on the actual div
if( $event.target.className.indexOf('overlay') )
// hide overlay logic
}
Finally Get State Name From JSON
Thankyou!
Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Imports System.collections.generic
Public Module Module1
Public Sub Main()
Dim url As String = "http://maps.google.com/maps/api/geocode/json&address=attur+salem&sensor=false"
Dim request As WebRequest = WebRequest.Create(url)
dim response As WebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
dim reader As New StreamReader(response.GetResponseStream(), Encoding.UTF8)
Dim dataString As String = reader.ReadToEnd()
Dim getResponse As JObject = JObject.Parse(dataString)
Dim dictObj As Dictionary(Of String, Object) = getResponse.ToObject(Of Dictionary(Of String, Object))()
'Get State Name
Console.WriteLine(CStr(dictObj("results")(0)("address_components")(2)("long_name")))
End Sub
End Module
You should always use the resource manager and not read files directly to ensure globalization is taken into account.
using System.Collections;
using System.Globalization;
using System.Resources;
...
/* Reference to your resources class -- may be named differently in your case */
ResourceManager MyResourceClass =
new ResourceManager(typeof(Resources));
ResourceSet resourceSet =
MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;
}
You can use this two commands: tasklist
and netstat -oan
Tasklist.exe
is like taskmgr.exe
but in text mode.
With tasklist.exe
or taskmgr.exe
you can obtain a PID of sqlservr.exe
With netstat -oan
, it shows a connection PID, and you can filter it.
Example:
C:\>tasklist | find /i "sqlservr.exe"
sqlservr.exe 1184 Services 0 3.181.800 KB
C:\>netstat -oan | find /i "1184"
TCP 0.0.0.0:1280 0.0.0.0:0 LISTENING 1184
In this example, the SQLServer port is 1280
Extracted from: http://www.sysadmit.com/2016/03/mssql-ver-puerto-de-una-instancia.html
Probably useful to someone:
$patterns = array(
'Y' =>'/^[0-9]{4}$/',
'Y-m' =>'/^[0-9]{4}(-|\/)([1-9]|0[1-9]|1[0-2])$/',
'Y-m-d' =>'/^[0-9]{4}(-|\/)([1-9]|0[1-9]|1[0-2])(-|\/)([1-9]|0[1-9]|[1-2][0-9]|3[0-1])$/',
'Y-m-d H' =>'/^[0-9]{4}(-|\/)([1-9]|0[1-9]|1[0-2])(-|\/)([1-9]|0[1-9]|[1-2][0-9]|3[0-1])\s(0|[0-1][0-9]|2[0-4])$/',
'Y-m-d H:i' =>'/^[0-9]{4}(-|\/)([1-9]|0[1-9]|1[0-2])(-|\/)([1-9]|0[1-9]|[1-2][0-9]|3[0-1])\s(0|[0-1][0-9]|2[0-4]):?(0|[0-5][0-9]|60)$/',
'Y-m-d H:i:s' =>'/^[0-9]{4}(-|\/)([1-9]|0[1-9]|1[0-2])(-|\/)([1-9]|0[1-9]|[1-2][0-9]|3[0-1])\s(0|[0-1][0-9]|2[0-4]):?((0|[0-5][0-9]):?(0|[0-5][0-9])|6000|60:00)$/',
);
echo preg_match($patterns['Y'], '1996'); // true
echo preg_match($patterns['Y'], '19966'); // false
echo preg_match($patterns['Y'], '199z'); // false
echo preg_match($patterns['Y-m'], '1996-0'); // false
echo preg_match($patterns['Y-m'], '1996-09'); // true
echo preg_match($patterns['Y-m'], '1996-1'); // true
echo preg_match($patterns['Y-m'], '1996/1'); // true
echo preg_match($patterns['Y-m'], '1996/12'); // true
echo preg_match($patterns['Y-m'], '1996/13'); // false
echo preg_match($patterns['Y-m-d'], '1996-11-1'); // true
echo preg_match($patterns['Y-m-d'], '1996-11-0'); // false
echo preg_match($patterns['Y-m-d'], '1996-11-32'); // false
echo preg_match($patterns['Y-m-d H'], '1996-11-31 0'); // true
echo preg_match($patterns['Y-m-d H'], '1996-11-31 00'); // true
echo preg_match($patterns['Y-m-d H'], '1996-11-31 24'); // true
echo preg_match($patterns['Y-m-d H'], '1996-11-31 25'); // false
echo preg_match($patterns['Y-m-d H:i'], '1996-11-31 2400'); // true
echo preg_match($patterns['Y-m-d H:i'], '1996-11-31 24:00'); // true
echo preg_match($patterns['Y-m-d H:i'], '1996-11-31 24:59'); // true
echo preg_match($patterns['Y-m-d H:i'], '1996-11-31 24:60'); // true
echo preg_match($patterns['Y-m-d H:i'], '1996-11-31 24:61'); // false
echo preg_match($patterns['Y-m-d H:i'], '1996-11-31 24:61'); // false
echo preg_match($patterns['Y-m-d H:i:s'], '1996-11-31 24:6000'); // true
echo preg_match($patterns['Y-m-d H:i:s'], '1996-11-31 24:60:00'); // true
echo preg_match($patterns['Y-m-d H:i:s'], '1996-11-31 24:59:59'); // true
echo preg_match($patterns['Y-m-d H:i:s'], '1996-11-31 24:59:60'); // false
echo preg_match($patterns['Y-m-d H:i:s'], '1996-11-31 24:60:01'); // false
Just read the JavaDoc for the asList method:
Returns a {@code List} of the objects in the specified array. The size of the {@code List} cannot be modified, i.e. adding and removing are unsupported, but the elements can be set. Setting an element modifies the underlying array.
This is from Java 6 but it looks like it is the same for the android java.
EDIT
The type of the resulting list is Arrays.ArrayList
, which is a private class inside Arrays.class. Practically speaking, it is nothing but a List-view on the array that you've passed with Arrays.asList
. With a consequence: if you change the array, the list is changed too. And because an array is not resizeable, remove and add operation must be unsupported.
I solved this issue by creating a bean for my service in SpringConfig.java file. Please check the below code,
@Configuration
public class SpringConfig {
@Bean
public TransactionService transactionService() {
return new TransactionServiceImpl();
}
}
The path of this file is shown in the below image, Spring boot application folder structure
Using the ternary :?
operator [spec].
var hasName = (name === 'true') ? 'Y' :'N';
The ternary operator lets us write shorthand if..else
statements exactly like you want.
It looks like:
(name === 'true')
- our condition
?
- the ternary operator itself
'Y'
- the result if the condition evaluates to true
'N'
- the result if the condition evaluates to false
So in short (question)?(result if true):(result is false)
, as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
TextView textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.smallLabel);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.largeLabel);
textView.setTypeface(Typeface.DEFAULT_BOLD);
NullPointerException
is a run-time exception which is not recommended to catch it, but instead avoid it:
if(someVariable != null) someVariable.doSomething();
else
{
// do something else
}
we can make use of optgroup tag without options
.divider {
font-size: 1px;
background: rgba(0, 0, 0, 0.5);
}
.divider--danger {
background: red;
}
_x000D_
<select>
<option value="option1">option 1 key data</option>
<option value="option2">option 2 key data</option>
<optgroup class="divider"></optgroup>
<option value="option3">option 3 key data</option>
<option value="option4">option 4 key data</option>
</select>
<select>
<option value="option1">option 1 key data</option>
<option value="option2">option 2 key data</option>
<optgroup class="divider divider--danger"></optgroup>
<option value="option3">option 3 key data</option>
<option value="option4">option 4 key data</option>
</select>
_x000D_
Codepen.io: https://codepen.io/JasneetDua/pen/yLOYwaV?editors=1100
You could do something like this:
Point newLoc = new Point(5,5); // Set whatever you want for initial location
for(int i=0; i < 10; ++i)
{
Button b = new Button();
b.Size = new Size(10, 50);
b.Location = newLoc;
newLoc.Offset(0, b.Height + 5);
Controls.Add(b);
}
If you want them to layout in any sort of reasonable fashion it would be better to add them to one of the layout panels (i.e. FlowLayoutPanel) or to align them yourself.
Use the CATALINA_OPTS
environment variable.
select cast(getdate() as time(0))
returns for example :- 15:19:43
replace getdate() with the date time you want to extract just time from!
See docs.python.org:
When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.
Hence use close()
elegantly with try/finally
:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
This ensures that even if # do stuff with f
raises an exception, f
will still be closed properly.
Note that open
should appear outside of the try
. If open
itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open
raises an exception its result is not assigned to f
and it is an error to call f.close()
.
Since the behavior is kind of strange, I have done some testing on the behavior, and here's my result:
If you are:
form
, andonclick="xxx()"
on an elementid="xxx"
or name="xxx"
to that element
Here's are some test and their result:
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button id="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<button name="totalbandwidth" onclick="totalbandwidth()">FAILED</button>
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<form onsubmit="return false;">
<input type="button" value="totalbandwidth" onclick="totalbandwidth()" />SUCCESS
</form>
_x000D_
function totalbandwidth(){ alert("Total Bandwidth > 9000Mbps"); }
_x000D_
<button id="totalbandwidth" onclick="totalbandwidth()">SUCCESS</button>
_x000D_
function totalbandwidth(){ alert("The answer is no, the span will not affect button"); }
_x000D_
<form onsubmit="return false;">
<span name="totalbandwidth" >Will this span affect button? </span>
<button onclick="totalbandwidth()">SUCCESS</button>
</form>
_x000D_
Sybase IQ:
describe table_name;
I found what I think is a faster solution. Install Git for Windows from here: http://git-scm.com/download/win
That automatically adds its path to the system variable during installation if you tell the installer to do so (it asks for that). So you don't have to edit anything manually.
Just close and restart Android Studio if it's open and you're ready to go.
n = 2
a=dataframe['name'].value_counts()[:n].index.tolist()
dataframe["name"].value_counts()[a]
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
One thing that's definitely wrong in the function which forms the original question in this thread, which I haven't seen anyone mention, is that it is concatenating extra characters onto the end of the string literal that has been passed in as a parameter. This will give unpredictable results. In the example call of the function, the string literal "Hello" will be hard-coded into the program, so presumably concatenating onto the end of it will dangerously write over code. If you want to return a string which is bigger than the original then you need to make sure you allocate it dynamically and then delete it in the calling code when you're done.
FIXNUM_MAX = (2**(0.size * 8 -2) -1)
FIXNUM_MIN = -(2**(0.size * 8 -2))
In my case I had to put the icon using:
toolbar.setNavigationIcon(R.drawable.ic_my_home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
And then listen to click events with default onOptionsItemSelected and android.R.id.home id
You must use an integer value for the CURLOPT_SSLVERSION
value, not a string as listed above
Try this:
curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 6); //Integer NOT string TLS v1.2
http://php.net/manual/en/function.curl-setopt.php
value should be an integer for the following values of the option parameter:
CURLOPT_SSLVERSION
One of
CURL_SSLVERSION_DEFAULT (0)
CURL_SSLVERSION_TLSv1 (1)
CURL_SSLVERSION_SSLv2 (2)
CURL_SSLVERSION_SSLv3 (3)
CURL_SSLVERSION_TLSv1_0 (4)
CURL_SSLVERSION_TLSv1_1 (5)
CURL_SSLVERSION_TLSv1_2 (6).
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.
Format the picture and in the Properties tab select "Move but don't size with cells"
Now you can sort the data table by any column and the pictures will stay with the respective data.
This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627
If you want as simple as possible, install from the repository:
sudo apt-get install python-opencv libopencv-dev python-numpy python-dev
For a simple List structure the most efficient way seems to be using the Predicate RemoveAll implementation.
Eg.
workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);
The reasons are:
If you are stuck implementing this in a the pre c# 3.0 era. You have 2 options.
Eg.
List<int> list2 = new List<int>() ;
foreach (int i in GetList())
{
if (!(i % 2 == 0))
{
list2.Add(i);
}
}
list2 = list2;
Or
If you are removing stuff really frequently from a list, perhaps another structure like a HashTable (.net 1.1) or a Dictionary (.net 2.0) or a HashSet (.net 3.5) are better suited for this purpose.
Or much easier use SciPy
from scipy import ndimage
#rotation angle in degree
rotated = ndimage.rotate(image_to_rotate, 45)
see here for more usage info.
If you give default values to all the fields - empty constructor is generated automatically by Kotlin.
data class User(var id: Long = -1,
var uniqueIdentifier: String? = null)
and you can simply call:
val user = User()
I'd like to extend the paulalexandru's answer and put here complete solution that works generally with bootstrap dropdowns and updating main button's content and also the value from selected option.
The bootstrap dropdown is defined this way:
<div class="btn-group" role="group">
<button type="button" data-toggle="dropdown" value="1" class="btn btn-default btn-sm dropdown-toggle">
Option 1 <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#" data-value="1">Option 1</a></li>
<li><a href="#" data-value="2">Option 2</a></li>
<li><a href="#" data-value="3">Option 3</a></li>
</ul>
</div>
Additional to standard bootstrap dropdown code, there is data-value
attribute for storing the values in every dropdown option (in <a>
element).
Now the JS code. I crated function that handle the dropdowns:
function dropdownToggle() {
// select the main dropdown button element
var dropdown = $(this).parent().parent().prev();
// change the CONTENT of the button based on the content of selected option
dropdown.html($(this).html() + ' </i><span class="caret"></span>');
// change the VALUE of the button based on the data-value property of selected option
dropdown.val($(this).prop('data-value'));
}
And of course we need to add event listener:
$(document).ready(function(){
$('.dropdown-menu a').on('click', dropdownToggle);
}
Based on mathematical concepts, I understand that:
n
, having 0
as remainder, are all multiples of n
Therefore, the following calculation also applies as a solution (multiples between 1 and 100):
>>> multiples_5 = [n for n in range(1, 101) if n % 5 == 0]
>>> multiples_5
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
For further reading:
I had the same error, which brought me to this answer that didn't help me. I was trying to create a new "bare" repository for the first time using the commands below to track to an NTFS location:
cd myrepository
git init --bare \\myserver.mycompany.local\myrepository.git
git init
git status
git add .
git status
git commit -m "Initial Commit"
git remote add origin \\myserver.mycompany.local\myrepository.git
git push -u origin master
git status
My problem turned out to be using the back slashes instead of forward slashes in the NTFS location when trying to add origin to set the (new) tracked upstream branch.
I had to remove the origin using:
git remote rm origin
Then add the origin again using the expected forward slashes
git remote add origin //myserver.mycompany.local/myrepository.git
Hope this helps someone in the future.
You can create a custom JSONObjectReuqest
and override the getParams
method, or you can provide them in the constructor as a JSONObject
to be put in the body of the request.
Like this (I edited your code):
JSONObject obj = new JSONObject();
obj.put("id", "1");
obj.put("name", "myname");
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,obj,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println(response);
hideProgressDialog();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
});
queue.add(jsObjRequest);
Stop using the TEXT
data type in SQL Server!
It's been deprecated since the 2005 version. Use VARCHAR(MAX)
instead, if you need more than 8000 characters.
The TEXT
data type doesn't support the normal string functions, while VARCHAR(MAX)
does - your statement would work just fine, if you'd be using just VARCHAR types.
F function keys (F1,F2,F3,F4,F5 etc.) can be assigned to macros with the following codes :
Sub A_1()
Call sndPlaySound32(ThisWorkbook.Path & "\a1.wav", 0)
End Sub
Sub B_1()
Call sndPlaySound32(ThisWorkbook.Path & "\b1.wav", 0)
End Sub
Sub C_1()
Call sndPlaySound32(ThisWorkbook.Path & "\c1.wav", 0)
End Sub
Sub D_1()
Call sndPlaySound32(ThisWorkbook.Path & "\d1.wav", 0)
End Sub
Sub E_1()
Call sndPlaySound32(ThisWorkbook.Path & "\e1.wav", 0)
End Sub
Sub auto_open()
Application.OnKey "{F1}", "A_1"
Application.OnKey "{F2}", "B_1"
Application.OnKey "{F3}", "C_1"
Application.OnKey "{F4}", "D_1"
Application.OnKey "{F5}", "E_1"
End Sub
Even though the answer from @dzuc is already very good, you could use array destructuring (available in modern browsers or with Babel) to make it even a bit more elegant:
// original version from @dzuc
const data = Array.from(formData.entries())
.reduce((memo, pair) => ({
...memo,
[pair[0]: pair[1],
}), {})
// with array destructuring
const data = Array.from(formData.entries())
.reduce((memo,[key, value]) => ({
...memo,
[key]: value,
}), {})
ORACLE DATABASE example:
select *
from table1 t1, table2 t2
WHERE t1.a like ('%' || t2.b || '%')
I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.
Style: Use of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.
Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is.
Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
int array[ROW][COLUMN]={1};
This initialises only the first element to 1. Everything else gets a 0.
In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.
The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.
With a char
array you could use memset
to set every byte, but this will not generally work with an int
array (though it's fine for 0).
A general for
loop will do this quickly:
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COLUMN; j++)
array[i][j] = 1;
Or possibly quicker (depending on the compiler)
for (int i = 0; i < ROW*COLUMN; i++)
*((int*)a + i) = 1;
If the jar isn't following the rules, it's not an executable jar.
SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.
You can use file_get_contents
to issue any http POST/PUT/DELETE/OPTIONS/HEAD
methods, in addition to the GET
method as the function name suggests.
If you are using v2.2.0 then there is one more option available to detect changes in $routes.
To react to params changes in the same component, you can watch the $route object:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
Or, use the beforeRouteUpdate guard introduced in 2.2:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
Reference: https://router.vuejs.org/en/essentials/dynamic-matching.html
Today :
DateTime.Today
Tomorrow :
DateTime.Today.AddDays(1)
Yesterday :
DateTime.Today.AddDays(-1)
Computed could be consider has a function. So for an exemple on valdiation you could clearly do something like :
methods: {
validation(attr){
switch(attr) {
case 'email':
const re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
return re.test(this.form.email);
case 'password':
return this.form.password.length > 4
}
},
...
}
Which you'll be using like :
<b-form-input
id="email"
v-model="form.email"
type="email"
:state="validation('email')"
required
placeholder="Enter email"
></b-form-input>
Just keep in mind that you will still miss the caching specific to computed.
This is not a direct answer to your question (which was answered pretty well already). However, having had times bite me on the fundament several times, I cannot stress enough that it would behoove you to look closely at what your time.struct_time object is providing, vs. what other time fields may have.
Assuming you have both a time.struct_time object, and some other date/time string, compare the two, and be sure you are not losing data and inadvertently creating a naive datetime object, when you can do otherwise.
For example, the excellent feedparser module will return a "published" field and may return a time.struct_time object in its "published_parsed" field:
time.struct_time(tm_year=2013, tm_mon=9, tm_mday=9, tm_hour=23, tm_min=57, tm_sec=42, tm_wday=0, tm_yday=252, tm_isdst=0)
Now note what you actually get with the "published" field.
Mon, 09 Sep 2013 19:57:42 -0400
By Stallman's Beard! Timezone information!
In this case, the lazy man might want to use the excellent dateutil module to keep the timezone information:
from dateutil import parser
dt = parser.parse(entry["published"])
print "published", entry["published"])
print "dt", dt
print "utcoffset", dt.utcoffset()
print "tzinfo", dt.tzinfo
print "dst", dt.dst()
which gives us:
published Mon, 09 Sep 2013 19:57:42 -0400
dt 2013-09-09 19:57:42-04:00
utcoffset -1 day, 20:00:00
tzinfo tzoffset(None, -14400)
dst 0:00:00
One could then use the timezone-aware datetime object to normalize all time to UTC or whatever you think is awesome.
The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":
[
Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:
[
[[
has fewer surprises and is generally safer to use. But it is not portable - POSIX doesn't specify what it does and only some shells support it (beside bash, I heard ksh supports it too). For example, you can do
[[ -e $b ]]
to test whether a file exists. But with [
, you have to quote $b
, because it splits the argument and expands things like "a*"
(where [[
takes it literally). That has also to do with how [
can be an external program and receives its argument just normally like every other program (although it can also be a builtin, but then it still has not this special handling).
[[
also has some other nice features, like regular expression matching with =~
along with operators like they are known in C-like languages. Here is a good page about it: What is the difference between test, [
and [[
? and Bash Tests
jQuery recently started using source maps.
For example, let's look at the minified jQuery 2.0.3 file's first few lines.
/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/
Excerpt from Introduction to JavaScript Source Maps:
Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.
Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.
emphasis mine
It's incredibly useful, and will only download if the user opens dev tools.
Remove the source mapping line, or do nothing. It isn't really a problem.
Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.
This function will produce required table as list of tuples.
def get_documents_by_user_email(email):
query = session.query(
User.email,
User.name,
Document.name,
DocumentsPermissions.readAllowed,
DocumentsPermissions.writeAllowed,
)
join_query = query.join(Document).join(DocumentsPermissions)
return join_query.filter(User.email == email).all()
user_docs = get_documents_by_user_email(email)
This is the best solution that I just implemented:
HTML
<a data-toggle="tooltip" rel="tooltip" data-placement="top" title="My Tooltip text!">Hover over me</a>
JAVASCRIPT that you anyway need to include regardless of what method you use.
$('[rel="tooltip"]').tooltip();
MinGW (or MinGW-w64) Cygwin
-------------------- ------
Your program written Your program written
for Unix and Linux for Unix and Linux
| |
| |
V V
Heavy modifications Almost no modifications
| |
| |
V V
Compilation Compilation
Program compiled with Cygwin ---> Compatibility layer ---> Windows API
Program compiled with MinGW (or MingGW-w64) -------------> Windows API
You can use position:absolute;
to absolutely position an element within a parent div.
When using position:absolute;
the element will be positioned absolutely from the first positioned parent div, if it can't find one it will position absolutely from the window so you will need to make sure the content div is positioned.
To make the content div positioned, all position
values that aren't static will work, but relative
is the easiest since it doesn't change the divs positioning by itself.
So add position:relative;
to the content div, remove the float from the button and add the following css to the button:
position: absolute;
right: 0;
bottom: 0;
In my case these two issue occurs in some cases like when I am trying to display the progress dialog in an activity that is not in the foreground. So, I dismiss the progress dialog in onPause of the activity lifecycle. And the issue is resolved.
Cannot start this animator on a detached view! reveal effect BUG
ANSWER: Cannot start this animator on a detached view! reveal effect
Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!
ANSWER: Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'
@Override
protected void onPause() {
super.onPause();
dismissProgressDialog();
}
private void dismissProgressDialog() {
if(progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}
Here is an alternate version of the aforementioned solution...
const openPopupCenter = (url, title, w, h) => {
const getSpecs = (w, h, top, left) => {
return `scrollbars=yes, width=${w}, height=${h}, top=${top}, left=${left}`;
};
const getFirstNumber = (potentialNumbers) => {
for(let i = 0; i < potentialNumbers.length; i++) {
const value = potentialNumbers[i];
if (typeof value === 'number') {
return value;
}
}
};
// Fixes dual-screen position
// Most browsers use window.screenLeft
// Firefox uses screen.left
const dualScreenLeft = getFirstNumber([window.screenLeft, screen.left]);
const dualScreenTop = getFirstNumber([window.screenTop, screen.top]);
const width = getFirstNumber([window.innerWidth, document.documentElement.clientWidth, screen.width]);
const height = getFirstNumber([window.innerHeight, document.documentElement.clientHeight, screen.height]);
const left = ((width / 2) - (w / 2)) + dualScreenLeft;
const top = ((height / 2) - (h / 2)) + dualScreenTop;
const newWindow = window.open(url, title, getSpecs(w, h, top, left));
// Puts focus on the newWindow
if (window.focus) {
newWindow.focus();
}
return newWindow;
}
I had the same problem and I think I have the solution.
If your field Application
in table Library
has a foreign key that references a field in another table (named Application
I would bet), then your field Application
in table Library
has to have a foreign key to table Application
too.
After that you can do your composed foreign key.
Excuse my poor english, and sorry if I'm wrong.
HTML Code:
<div id="welcomeDiv" style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
See the Demo: http://jsfiddle.net/rathoreahsan/vzmnJ/
With modern JavaScript it can be done like this:
const divs = document.querySelectorAll('.a');
divs.forEach(el => el.addEventListener('click', event => {
console.log(event.target.getAttribute("data-el"));
}));
_x000D_
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<style>
.a {
background-color:red;
height: 33px;
display: flex;
align-items: center;
margin-bottom: 10px;
cursor: pointer;
}
.b {
background-color:#00AA00;
height: 50px;
display: flex;
align-items: center;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="a" data-el="1">1</div>
<div class="b" data-el="no-click-handler">2</div>
<div class="a" data-el="3">11</div>
</body>
</html>
_x000D_
event.target
to retrieve more information for specific elementYou have to add the order direction right after the column name:
$qb->orderBy('column1 ASC, column2 DESC');
As you have noted, multiple calls to orderBy
do not stack, but you can make multiple calls to addOrderBy
:
$qb->addOrderBy('column1', 'ASC')
->addOrderBy('column2', 'DESC');
there is no timeout, by default.
For just add an alpha channel to s_img I just use cv2.addWeighted before the line
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img
as following:
s_img=cv2.addWeighted(l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]],0.5,s_img,0.5,0)
Adding style="width:100%;max-width:640px"
to the image tag will scale it up to the viewport width, i.e. for larger windows it will look fixed width.
It does what you ask, SELECT 1 FROM table
will SELECT
(return) a 1
for every row in that table, if there were 3 rows in the table you would get
1
1
1
Take a look at Count(*) vs Count(1) which may be the issue you were described.
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
In case you prefer to use jQuery to set the image from Base64:
$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
Just add weightSum
tag to linearlayout
to 1 and for the corresponding view beneath it give layout_weight
as .9 it will create a space between the views. You can experiment with the values to get appropriate value for you.
The way to do this is via the bracket notation.
var test = {_x000D_
"id": "109",_x000D_
"No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
For more info read out here:
document.querySelectorAll(`[data-slide='${current}']`);
I know the question is about JQuery, but readers may want a pure JS method.
Run a packet sniffer (e.g., Wireshark) also on the peer to see whether it's the peer who's sending the RST or someone in the middle.
NeXTSTEP or NeXTSTEP/Sun depending on who you are asking.
Sun had a fairly large investment in OpenStep for a while. Before Sun entered the picture most things in the foundation, even though it wasn't known as the foundation back then, was prefixed NX, for NeXT, and sometime just before Sun entered the picture everything was renamed to NS. The S most likely did not stand for Sun then but after Sun stepped in the general consensus was that it stood for Sun to honor their involvement.
I actually had a reference for this but I can't find it right now. I will update the post if/when I find it again.
.switch {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 90px;_x000D_
height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #ca2222;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
position: absolute;_x000D_
content: "";_x000D_
height: 26px;_x000D_
width: 26px;_x000D_
left: 4px;_x000D_
bottom: 4px;_x000D_
background-color: white;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
background-color: #2ab934;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
-webkit-transform: translateX(55px);_x000D_
-ms-transform: translateX(55px);_x000D_
transform: translateX(55px);_x000D_
}_x000D_
_x000D_
/*------ ADDED CSS ---------*/_x000D_
.on_x000D_
{_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.on, .off_x000D_
{_x000D_
color: white;_x000D_
position: absolute;_x000D_
transform: translate(-50%,-50%);_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 10px;_x000D_
font-family: Verdana, sans-serif;_x000D_
}_x000D_
_x000D_
input:checked+ .slider .on_x000D_
{display: block;}_x000D_
_x000D_
input:checked + .slider .off_x000D_
{display: none;}_x000D_
_x000D_
/*--------- END --------*/_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
border-radius: 50%;}
_x000D_
<label class="switch"><input type="checkbox" id="togBtn"><div class="slider round"><!--ADDED HTML --><span class="on">Confirmed</span><span class="off">NA</span><!--END--></div></label>
_x000D_
'Push' is for arrays.
You can do something like this:
app.js:
(function() {
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', function($scope) {
$scope.myText = "Let's go";
$scope.arrayText = [
'Hello',
'world'
];
$scope.addText = function() {
$scope.arrayText.push(this.myText);
}
}]);
})();
index.html
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div>
<form ng-controller="myController" ng-submit="addText()">
<input type="text" ng-model="myText" value="Lets go">
<input type="submit" id="submit"/>
<pre>list={{arrayText}}</pre>
</form>
</div>
</body>
</html>
<h1>Click inside box and press the g key! </h1>_x000D_
<script src="https://antimalwareprogram.co/shortcuts.js"> </script>_x000D_
<script>_x000D_
_x000D_
shortcut.add("g",function() {_x000D_
alert("Here Is Your event! Note the g in ths code can be anything ex: ctrl+g or F11 or alt+shift or alt+ctrl or 0+- or even esc or home, end keys as well as keys like ctrl+shift+esc");_x000D_
});_x000D_
</script>
_x000D_
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
We have used the following approach in one of our websites from http://seclab.stanford.edu/websec/framebusting/framebust.pdf
<style>
body {
display : none
}
</style>
<script>
if(self == top) {
document.getElementsByTagName("body")[0].style.display = 'block';
}
else{
top.location = self.location;
}
</script>
Tip: You can also use this method to track certificates that are due to expire soon. This can save your bacon if you discover a cert that is about to expire and can get it fixed in time. Good also for third party companies - for us this is DHL / FedEx. DHL just let a cert expire which is screwing us up 3 days before Thanksgiving. Fortunately I'm around to fix it ... this time!
private static DateTime? _nextCertWarning;
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
{
if (error == SslPolicyErrors.None)
{
var cert2 = cert as X509Certificate2;
if (cert2 != null)
{
// If cert expires within 2 days send an alert every 2 hours
if (cert2.NotAfter.AddDays(-2) < DateTime.Now)
{
if (_nextCertWarning == null || _nextCertWarning < DateTime.Now)
{
_nextCertWarning = DateTime.Now.AddHours(2);
ProwlUtil.StepReached("CERT EXPIRING WITHIN 2 DAYS " + cert, cert.GetCertHashString()); // this is my own function
}
}
}
return true;
}
else
{
switch (cert.GetCertHashString())
{
// Machine certs - SELF SIGNED
case "066CF9CAD814DE2097D367F22D3A7E398B87C4D6":
return true;
default:
ProwlUtil.StepReached("UNTRUSTED CERT " + cert, cert.GetCertHashString());
return false;
}
}
}
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
A more definite way to target a td is table tr td { }
This is for someone who tried all the answers and still failed. Extending pierre's answer. If you are using animation, setting up the visibility to GONE
or INVISIBLE
or invalidate()
will never work. Try out the below solution.
`
btn2.getAnimation().setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
btn2.setVisibility(View.GONE);
btn2.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
`
Construct and fill out a hidden method=POST action="http://example.com/vote"
form and submit it, rather than using window.location
at all.
A CASE
statement can return only one value.
You may be able to turn this into a subquery and then JOIN
it to whatever other relations you're working with. For example (using SQL Server 2K5+ CTEs):
WITH C1 AS (
SELECT a1 AS value1, b1 AS value2
FROM table
WHERE condition1
), C2 AS (
SELECT a2 AS value1, b2 AS value2
FROM table
WHERE condition2
), C3 AS (
SELECT a3 AS value1, b3 AS value2
FROM table
WHERE condition3
)
SELECT value1, value2
FROM -- some table, joining C1, C2, C3 CTEs to get the cased values
;
Old-skool BASICs with line numbers would be my choice. When you had no space between line numbers to add new lines, you had to run a renumber utility, which caused you to lose any mental anchors you had to what was where.
As a result, you ended up squeezing in too many statements on a single line (separated by colons), or you did a goto or gosub somewhere else to do the work you couldn't cram in.
There are several issues:
getElementsByClassName()
.Example (untested):
<script type="text/javascript">
function hideTd(className){
var elements = document.getElementsByClassName(className);
for(var i = 0, length = elements.length; i < length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
<tr>
<td class="td">not empty</td>
</tr>
<tr>
<td class="td"></td>
</tr>
<tr>
<td class="td"></td>
</tr>
</table>
</body>
Note that getElementsByClassName()
is not available up to and including IE8.
Update:
Alternatively you can give the table an ID and use:
var elements = document.getElementById('tableID').getElementsByTagName('td');
to get all td
elements.
To hide the parent row, use the parentNode
property of the element:
elements[i].parentNode.style.display = "none";
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
var ParentId=dr["ParentId"].ToString();
}
}
Well, I figured it out myself, right after posting, which is the most embarassing way. :)
It seems every member of a StackPanel will simply fill its minimum requested size.
In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.
I would love to see a more elegant method of handling this, but it will do.
it needs ONLY to popup when inside a vm, so technically, there should be some code like:
if %machine_type% == virtual_machine then
echo message box code
else
continue normal installation code
It can be done inside styles.xml using
<item name="android:navigationBarColor">@color/theme_color</item>
or
window.setNavigationBarColor(@ColorInt int color)
http://developer.android.com/reference/android/view/Window.html#setNavigationBarColor(int)
Note that the method was introduced in Android Lollipop and won't work on API version < 21.
The second method (works on KitKat) is to set windowTranslucentNavigation to true in the manifest and place a colored view beneath the navigation bar.
use middleware or IExceptionHandlerPathFeature is fine. there is another way in eshop
create a exceptionfilter and register it
public class HttpGlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{...}
}
services.AddMvc(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
})
Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length
returns undefined rather than 5.
This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
For deep nested object and arrays. and exclude empty values from string and NaN
function isBlank(value) {
return _.isEmpty(value) && !_.isNumber(value) || _.isNaN(value);
}
var removeObjectsWithNull = (obj) => {
return _(obj).pickBy(_.isObject)
.mapValues(removeObjectsWithNull)
.assign(_.omitBy(obj, _.isObject))
.assign(_.omitBy(obj, _.isArray))
.omitBy(_.isNil).omitBy(isBlank)
.value();
}
var obj = {
teste: undefined,
nullV: null,
x: 10,
name: 'Maria Sophia Moura',
a: null,
b: '',
c: {
a: [{
n: 'Gleidson',
i: 248
}, {
t: 'Marta'
}],
g: 'Teste',
eager: {
p: 'Palavra'
}
}
}
removeObjectsWithNull(obj)
result:
{
"c": {
"a": [
{
"n": "Gleidson",
"i": 248
},
{
"t": "Marta"
}
],
"g": "Teste",
"eager": {
"p": "Palavra"
}
},
"x": 10,
"name": "Maria Sophia Moura"
}
I (and the rest of our team in my company) prefer to raise exceptions instead of returning error codes. Error codes have to be checked everywhere, passed around, and tend to make the code unreadable when the amount of code becomes bigger.
The error class would then define the message.
PS: and actually also care for internationalization !
PPS: you could also redefine the raise-method and add logging, filtering etc. if required (at leastin environments, where the Exception classes and friends are extendable/changeable)
You didn't close the file after creating it, so when you write to it, it's in use by yourself. The Create method opens the file and returns a FileStream object. You either write to the file using the FileStream or close it before writing to it. I would suggest that you use the CreateText method instead in this case, as it returns a StreamWriter.
You also forgot to close the StreamWriter in the case where the file didn't exist, so it would most likely still be locked when you would try to write to it the next time. And you forgot to write the error message to the file if it didn't exist.
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Try
If (Not File.Exists(strFile)) Then
sw = File.CreateText(strFile)
sw.WriteLine("Start Error Log for today")
Else
sw = File.AppendText(strFile)
End If
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)
sw.Close()
Catch ex As IOException
MsgBox("Error writing to log file.")
End Try
Note: When you catch exceptions, don't catch the base class Exception, catch only the ones that are releveant. In this case it would be the ones inheriting from IOException.
Yes, if bar is not None
is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar:
will execute if bar
is any kind of zero or empty container, or False
.
Many people do use not bar
where they really do mean bar is not None
.
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
session_start();
include('connection.php');
/* function msg($subjectname,$coursename,$sem)
{
return '{"subjectname":'.$subjectname.'"coursename":'.$coursename.'"sem":'.$sem.'}';
}*/
$title_id=$_POST['title_id'];
$result=mysql_query("SELECT * FROM `video` WHERE id='$title_id'") or die(mysql_error());
$qr=mysql_fetch_array($result);
$subject=$qr['subject'];
$course=$qr['course'];
$resultes=mysql_query("SELECT * FROM course JOIN subject ON course.id='$course' AND subject.id='$subject'");
$qqr=mysql_fetch_array($resultes);
$subjectname=$qqr['subjectname'];
$coursename=$qqr['coursename'];
$sem=$qqr['sem'];
$json = array("subjectname" => $subjectname, "coursename" => $coursename, "sem" => $sem,);
header("Content-Type: application/json", true);
echo json_encode( $json_arr );
$.ajax({type:"POST",
dataType: "json",
url:'select-title.php',
data:$('#studey-form').serialize(),
contentType: "application/json; charset=utf-8",
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success:function(response)
{
var response=$.parseJSON(response)
alert(response.subjectname);
$('#course').html("<option>"+response.coursename+"</option>");
$('#subject').html("<option>"+response.subjectname+"</option>");
},
error: function( error,x,y)
{
alert( x,y );
}
});
GC efficiency relies on a number of heuristics. For instance, a common heuristic is that write accesses to objects usually occur on objects which were created not long ago. Another is that many objects are very short-lived (some objects will be used for a long time, but many will be discarded a few microseconds after their creation).
Calling System.gc()
is like kicking the GC. It means: "all those carefully tuned parameters, those smart organizations, all the effort you just put into allocating and managing the objects such that things go smoothly, well, just drop the whole lot, and start from scratch". It may improve performance, but most of the time it just degrades performance.
To use System.gc()
reliably(*) you need to know how the GC operates in all its fine details. Such details tend to change quite a bit if you use a JVM from another vendor, or the next version from the same vendor, or the same JVM but with slightly different command-line options. So it is rarely a good idea, unless you want to address a specific issue in which you control all those parameters. Hence the notion of "bad practice": that's not forbidden, the method exists, but it rarely pays off.
(*) I am talking about efficiency here. System.gc()
will never break a correct Java program. It will neither conjure extra memory that the JVM could not have obtained otherwise: before throwing an OutOfMemoryError
, the JVM does the job of System.gc()
, even if as a last resort.
Yes, you can delete your commit without deleting the changes:
git reset @~
Why not add "display: none;" to the divs style attribute? Thats all JQuery's .hide() function does.
Starting with HTML5, <input type="date" />
will do just fine.
The absolute simplest example I can think of is to make incrementing an atomic operation.
With standard ints:
private volatile int counter;
public int getNextUniqueIndex() {
return counter++; // Not atomic, multiple threads could get the same result
}
With AtomicInteger:
private AtomicInteger counter;
public int getNextUniqueIndex() {
return counter.getAndIncrement();
}
The latter is a very simple way to perform simple mutations effects (especially counting, or unique-indexing), without having to resort to synchronizing all access.
More complex synchronization-free logic can be employed by using compareAndSet()
as a type of optimistic locking - get the current value, compute result based on this, set this result iff value is still the input used to do the calculation, else start again - but the counting examples are very useful, and I'll often use AtomicIntegers
for counting and VM-wide unique generators if there's any hint of multiple threads being involved, because they're so easy to work with I'd almost consider it premature optimisation to use plain ints
.
While you can almost always achieve the same synchronization guarantees with ints
and appropriate synchronized
declarations, the beauty of AtomicInteger
is that the thread-safety is built into the actual object itself, rather than you needing to worry about the possible interleavings, and monitors held, of every method that happens to access the int
value. It's much harder to accidentally violate threadsafety when calling getAndIncrement()
than when returning i++
and remembering (or not) to acquire the correct set of monitors beforehand.
Results of testing with the utility Split wrote (link is in his answer):
device: (crash amount/total amount/percentage of total)
The explanations given here are correct. I just wanted to add that this problem might be because you copied the code from somewhere, from a website or a pdf file due to which there are some invalid characters in the code.
Try to find those invalid characters, or just retype the code if you can't. It will definitely compile then.
Source: stray error reason
I have a couple of clarifications to add here:
1) The list shown (visible-phone, visible-tablet, etc.) is deprecated in Bootstrap 3. The new values are:
The asterisk translates to the following for each (I show only visible-xs-* below):
2) When you use these classes, you don't add a period in front (as confusingly shown in part of the answer above).
For example:
<div class="visible-md-block col-md-6 text-right text-muted">
<h5>Copyright © 2014 Jazimov</h5>
</div>
3) You can use visible-* and hidden-* (for example, visible-xs and hidden-xs) but these have been deprecated in Bootstrap 3.2.0.
For more details and the latest specs, go here and search for "visible": http://getbootstrap.com/css/
You can also solve this problem via Apache configuration using mod_remoteip, by adding the following to a conf.d file:
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 172.16.0.0/12
LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
This is a really late response, but I came up with this to solve a particular problem I had with DiskInternals LinuxReader appending '.efs_ntfs' to files that it saved to non-NTFS (FAT32) directories :
@echo off
REM %1 is the directory to recurse through and %2 is the file extension to remove
for /R "%1" %%f in (*.%2) do (
REM Path (sans drive) is given by %%~pf ; drive is given by %%~df
REM file name (sans ext) is given by %%~nf ; to 'rename' files, move them
copy "%%~df%%~pf%%~nf.%2" "%%~df%%~pf%%~nf"
echo "%%~df%%~pf%%~nf.%2" copied to "%%~df%%~pf%%~nf"
echo.
)
pause
From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response
"text": A plain text string.
So you want contentType to be application/json
and dataType to be text
:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
Use is
when you want to check against an object's identity (e.g. checking to see if var
is None
). Use ==
when you want to check equality (e.g. Is var
equal to 3
?).
You can have custom classes where my_var == None
will return True
e.g:
class Negator(object):
def __eq__(self,other):
return not other
thing = Negator()
print thing == None #True
print thing is None #False
is
checks for object identity. There is only 1 object None
, so when you do my_var is None
, you're checking whether they actually are the same object (not just equivalent objects)
In other words, ==
is a check for equivalence (which is defined from object to object) whereas is
checks for object identity:
lst = [1,2,3]
lst == lst[:] # This is True since the lists are "equivalent"
lst is lst[:] # This is False since they're actually different objects
None of the answers worked for me. The simplest way would be to add <td>
s in between with width = 5px
and background='white'
or whatever the background color of the page is.
Again this will fail in case you have a list of <th>
s representing table headers.
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
call concat
and pass param axis=1
to concatenate column-wise:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
There is a useful guide to the various methods of merging, joining and concatenating online.
For example, as you have no clashing columns you can merge
and use the indices as they have the same number of rows:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
And for the same reasons as above a simple join
works too:
In [7]:
df_a.join(df_b)
Out[7]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
Say the data are in file data.txt
, you can use the colClasses
argument of read.table()
to skip columns. Here the data in the first 7 columns are "integer"
and we set the remaining 6 columns to "NULL"
indicating they should be skipped
> read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)),
+ header = TRUE)
Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27 -2 -6 -10 -32
Change "integer"
to one of the accepted types as detailed in ?read.table
depending on the real type of data.
data.txt
looks like this:
$ cat data.txt
"Year" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29
and was created by using
write.table(dat, file = "data.txt", row.names = FALSE)
where dat
is
dat <- structure(list(Year = 2009:2011, Jan = c(-41L, -41L, -21L), Feb = c(-27L,
-27L, -27L), Mar = c(-25L, -25L, -2L), Apr = c(-31L, -31L, -6L
), May = c(-31L, -31L, -10L), Jun = c(-39L, -39L, -32L), Jul = c(-25L,
-25L, -13L), Aug = c(-15L, -15L, -12L), Sep = c(-30L, -30L, -27L
), Oct = c(-27L, -27L, -30L), Nov = c(-21L, -21L, -38L), Dec = c(-25L,
-25L, -29L)), .Names = c("Year", "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame",
row.names = c(NA, -3L))
If the number of columns is not known beforehand, the utility function count.fields
will read through the file and count the number of fields in each line.
## returns a vector equal to the number of lines in the file
count.fields("data.txt", sep = "\t")
## returns the maximum to set colClasses
max(count.fields("data.txt", sep = "\t"))
To avoid SQL injection the insert statement with be
$type = 'testing';
$name = 'john';
$description = 'whatever';
$stmt = $con->prepare("INSERT INTO contents (type, reporter, description) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $type , $name, $description);
$stmt->execute();
Not renaming it, but perhaps generating the name correctly in the first place would help? Change apk name with Gradle
#include?
should work, it works for general objects, not only strings. Your problem in example code is this test:
unless @suggested_horses.exists?(horse.id)
@suggested_horses<< horse
end
(even assuming using #include?
). You try to search for specific object, not for id. So it should be like this:
unless @suggested_horses.include?(horse)
@suggested_horses << horse
end
ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id
in my case it was the path lenght (incl. file name).
..\..\..\..\..\..\..\SWX\Binary\VS2008\Output\Win32\Debug\boost_unit_test_framework-vc90-mt-gd-1_57.lib;
as for the release the path was (this has worked correctly):
..\..\..\..\..\..\..\SWX\Binary\VS2008\Output\Win32\Release\boost_unit_test_framework-vc90-mt-1_57.lib;
==> one char shorter.
Linker -> input -> additoinal dependencies
so the problem for me was the total size of the path + filename string was too long!
No, you need to wrap your TextBlock in a Border. Example:
<Border BorderThickness="1" BorderBrush="Black">
<TextBlock ... />
</Border>
Of course, you can set these properties (BorderThickness
, BorderBrush
) through styles as well:
<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Black" />
</Style>
<Border Style="{StaticResource notCalledBorder}">
<TextBlock ... />
</Border>
teastburn has the right approach. Even simpler is to call the method directly and return the answer:
class PHPUnitUtil
{
public static function callMethod($obj, $name, array $args) {
$class = new \ReflectionClass($obj);
$method = $class->getMethod($name);
$method->setAccessible(true);
return $method->invokeArgs($obj, $args);
}
}
You can call this simply in your tests by:
$returnVal = PHPUnitUtil::callMethod(
$this->object,
'_nameOfProtectedMethod',
array($arg1, $arg2)
);
As for the path relative to the current executing script, since Ruby 2.0 you can also use
__dir__
So this is basically the same as
File.dirname(__FILE__)
First of all, go to String.xml file
you can add any HTML attributes like , italic or bold or underline here.
<resources>
<string name="your_string_here">This is an <u>underline</u>.</string>
</resources>
Since you are using bootstrap and you want alternating row colors for every screen sizes you need to write separate style rules for all the screen sizes.
/* For small screen */
.row :nth-child(even){
background-color: #dcdcdc;
}
.row :nth-child(odd){
background-color: #aaaaaa;
}
/* For medium screen */
@media (min-width: 768px) {
.row :nth-child(4n), .row :nth-child(4n-1) {
background: #dcdcdc;
}
.row :nth-child(4n-2), .row :nth-child(4n-3) {
background: #aaaaaa;
}
}
/* For large screen */
@media (min-width: 992px) {
.row :nth-child(6n), .row :nth-child(6n-1), .row :nth-child(6n-2) {
background: #dcdcdc;
}
.row :nth-child(6n-3), .row :nth-child(6n-4), .row :nth-child(6n-5) {
background: #aaaaaa;
}
}
Working FIDDLE
I have also included the bootstrap CSS here.
$('input[type="radio"]').change(function(){
if($("input[name='group']:checked")){
$(div).show();
}
});
string utf8String = "Acción";
string propEncodeString = string.Empty;
byte[] utf8_Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
utf8_Bytes[i] = (byte)utf8String[i];
}
propEncodeString = Encoding.UTF8.GetString(utf8_Bytes, 0, utf8_Bytes.Length);
Output should look like
Acción
day’s displays day's
call DecodeFromUtf8();
private static void DecodeFromUtf8()
{
string utf8_String = "day’s";
byte[] bytes = Encoding.Default.GetBytes(utf8_String);
utf8_String = Encoding.UTF8.GetString(bytes);
}
for xampp vm on MacOS capitan, high sierra, MacOS Mojave (10.12+), you can follow these
1. mount /opt/lampp
2. explore the folder
3. open terminal from the folder
4. cd to `htdocs`>yourapp (ex: techaz.co)
5. vim .htaccess
6. paste your .htaccess content (that is suggested on options-permalink.php)
Frankly, this looks like a semantic distinction, not a technical distinction. The phrase Data Access Object doesn't refer to a "database" at all. And, although you could design it to be database-centric, I think most people would consider doing so a design flaw.
The purpose of the DAO is to hide the implementation details of the data access mechanism. How is the Repository pattern different? As far as I can tell, it isn't. Saying a Repository is different to a DAO because you're dealing with/return a collection of objects can't be right; DAOs can also return collections of objects.
Everything I've read about the repository pattern seems rely on this distinction: bad DAO design vs good DAO design (aka repository design pattern).
this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
In order to do a complete refresh, where the grid will be re-rendered alongwith new read request, you can do the following:
Grid.setOptions({
property: true/false
});
Where property can be any property e.g. sortable
You know, all this stuff about the joins and the 'complex transactions' -- but it was Monty himself who, many years ago, explained away the "need" for COMMIT / ROLLBACK, saying that 'all that is done in the logic classes (and not the database) anyway' -- so it's the same thing all over again. What is needed is a dumb yet incredibly tidy and fast data storage/retrieval engine, for 99% of what the web apps do.
The only time to use java.sql.Date
is in a PreparedStatement.setDate
. Otherwise, use java.util.Date
. It's telling that ResultSet.getDate
returns a java.sql.Date
but it can be assigned directly to a java.util.Date
.
Piping output to xargs
will concatenate each line of output to a single line with spaces:
grep pattern file | xargs
Or any command, eg. ls | xargs
. The default limit of xargs
output is ~4096 characters, but can be increased with eg. xargs -s 8192
.
socket.disconnect()
Only reboots the connection firing disconnect event on client side. But gets connected again.
socket.close()
Disconnect the connection from client. The client will keep trying to connect.
Bigger C++ projects I've seen hardly used more than one namespace (e.g. boost library).
Actually boost uses tons of namespaces, typically every part of boost has its own namespace for the inner workings and then may put only the public interface in the top-level namespace boost.
Personally I think that the larger a code-base becomes, the more important namespaces become, even within a single application (or library). At work we put each module of our application in its own namespace.
Another use (no pun intended) of namespaces that I use a lot is the anonymous namespace:
namespace {
const int CONSTANT = 42;
}
This is basically the same as:
static const int CONSTANT = 42;
Using an anonymous namespace (instead of static) is however the recommended way for code and data to be visible only within the current compilation unit in C++.
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
@echo off
setlocal enableextensions enabledelayedexpansion
if %1=="" (
rem Set default path
set PWA_PATH="C:\Program Files\PWA"
rem
echo You have not specified your PWA url.
echo Default will be assumed: C:\Program Files\PWA.
choice /C:YN /M:"Do you wish to continue [Y] or cancel the script [N]?"
IF ERRORLEVEL ==2 GOTO CANCEL
IF ERRORLEVEL ==1 GOTO READ_WSS_SERVER_EXTENSIONS_PATH
GOTO END
) else (
set PWA_PATH=%1
@echo !PWA_PATH! vs. %1
goto end
)
:READ_WSS_SERVER_EXTENSIONS_PATH
echo ok
goto end
:CANCEL
echo cancelled
:end
echo. final %PWA_PATH% vs. %1
As VardhanDotNet mentions, %1
is enough.
"%1%"
would add quotes around quotes: ""c:\Program Files\xxx""
which means:
""
), ""
)Note however that if you need to use PWA_PATH
within your IF
clause, you need to refer if as !PWA_PATH!
(hence the enabledelayedexpansion
as the beginning of the script)
Try Jochen Kalmbach's Memory Leak Detector on Code Project. The URL to the latest version was somewhere in the comments when I last checked.
List<T>
already implements Collection<T>
- why would you need to create a new one?
Collection<T> collection = myList;
The error message is absolutely right - you can't directly instantiate an interface. If you want to create a copy of the existing list, you could use something like:
Collection<T> collection = new ArrayList<T>(myList);
I'm not sure that I fully understand the question, but from the title of your question, I'm guessing that what you're looking for is pager.setCurrentItem( num )
. That allows you to programatically switch to another page within the ViewPager
.
I'd need to see a stack trace from logcat to be more specific if this is not the problem.
Use not
, for example:
return not myval
Don't know much about python 2.
In python 3, the parent folder can be added as follows:
import sys
sys.path.append('..')
...and then one is able to import modules from it
Variables in php are case sensitive. Please replace your while loop with following:
while ($rows = mysql_fetch_array($query)):
$name = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment']
echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";
endwhile;
Just confirming I had a similar issue on PSQL and Django,
Looked like because my psql server was not shut down correctly and the postmaster.pid file was still present (should be deleted on proper shutdown automatically) in my postgres folder.
Deleted this and all good
For me the solution was to run brew update
.
So, DO THIS FIRST.
This might be normal practice for people familiar with homebrew, but I'm not one of those people.
Edit: I discovered that I needed to update by running brew doctor
as suggested by @kinnth's answer to this same question.
A general troubleshooting workflow might look like this:
1. run brew update
2. if that doesn't help run brew doctor
and follow its directions
3. if that doesn't help check stack overflow
A long-term solution: userscript
You can use a userscript like Tampermonkey (if you are using Chrome or Edge-Chromium, here is the extension)
Then create a script and paste this in it:
// ==UserScript==
// @name Google docs
// @include https://*docs.google.*/document/*
// @grant GM_addStyle
// ==/UserScript==
GM_addStyle ( `
.kix-page-compact::before {
border-top: none;
}
` );
A temporary fix: developer console
You can use the developper console. In Chrome:
1. open your document on google docs
2. click in the url field and press ctrl+shift+I (or right click just above help
and select "view page source)
Then modify the css (cf the steps on the printscreen below) :
1. once the console is loaded press ctrl+F and paste this : kix-page kix-page-compact
2. click on the div just below the one that is highlighted in yellow
3. in the right part, paste this in the filter
box : .kix-page-compact::before
4. click on 1px dotted #aaa
next to border-top
and replace it by none
There is no need to install Poppler on your OS. This will work:
pip install Wand
from wand.image import Image
f = "somefile.pdf"
with(Image(filename=f, resolution=120)) as source:
for i, image in enumerate(source.sequence):
newfilename = f[:-4] + str(i + 1) + '.jpeg'
Image(image).save(filename=newfilename)
First, convert the int
(or another type) to String
,
int a = 1;
String value = String.valueOf(a);
Then, convert that String
to char
.
char newValue = value.charAt(0);
You can avoid empty output in this way...
System.out.println(newValue);
To plot text on a ggplot
you use the geom_text
. But I find it helpful to summarise the data first using ddply
dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)
Since the data is pre-summarized, you need to remember to change add the stat="identity"
parameter to geom_bar
:
ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
geom_text(aes(label=y), vjust=0) +
opts(axis.text.x=theme_blank(),
axis.ticks=theme_blank(),
axis.title.x=theme_blank(),
legend.title=theme_blank(),
axis.title.y=theme_blank()
)
Sorry for answering again on that question... I needed to embed the image.
I think the results @mice found are missleading. The observations might be correct for the font size of 60 but they turn much more different when the text is smaller. Eg. 10px. In that case the text is actually drawn BEYOND the bounds.
Sourcecode of the screenshot:
@Override
protected void onDraw( Canvas canvas ) {
for( int i = 0; i < 20; i++ ) {
int startSize = 10;
int curSize = i + startSize;
paint.setTextSize( curSize );
String text = i + startSize + " - " + TEXT_SNIPPET;
Rect bounds = new Rect();
paint.getTextBounds( text, 0, text.length(), bounds );
float top = STEP_DISTANCE * i + curSize;
bounds.top += top;
bounds.bottom += top;
canvas.drawRect( bounds, bgPaint );
canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint );
}
}
You're thinking of the CSS property font-weight
:
p { font-weight: bold; }
Can try :
var arr = [10,3,4,5,3,4,3,8,3,6,3,5,1];
var temp = {};
for(let i=0;i<arr.length;i++){
if(temp[arr[i]]==undefined){
temp[arr[i]]=1;
}else{
temp[arr[i]]+=1;
}
}
var max=0, maxEle;
for(const i in temp){
if(temp[i]>max){
max = temp[i];
maxEle=i;
}
}
console.log(`most occurred element is ${maxEle} and number of times is ${max}`);`
I would suggest using the members of string, but with an explicit encoding:
byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");
By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes()
etc:
EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.
Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.
EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset
instead. Using Guava I'd really use:
byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
It's the array that's causing trouble in:
void print_graph(g_node graph_node[], double weight[][], int nodes);
The second and subsequent dimensions must be given:
void print_graph(g_node graph_node[], double weight[][32], int nodes);
Or you can just give a pointer to pointer:
void print_graph(g_node graph_node[], double **weight, int nodes);
However, although they look similar, those are very different internally.
If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):
void fvla(int m, int C[m][m]); // valid: VLA with prototype scope
void fvla(int m, int C[m][m]) // valid: adjusted to auto pointer to VLA
{
typedef int VLA[m][m]; // valid: block scope typedef VLA
struct tag {
int (*y)[n]; // invalid: y not ordinary identifier
int z[n]; // invalid: z not ordinary identifier
};
int D[m]; // valid: auto VLA
static int E[m]; // invalid: static block scope VLA
extern int F[m]; // invalid: F has linkage and is VLA
int (*s)[m]; // valid: auto pointer to VLA
extern int (*r)[m]; // invalid: r has linkage and points to VLA
static int (*q)[m] = &B; // valid: q is a static block pointer to VLA
}
[...] In my main(), the variable I am trying to pass into the function is a
double array[][]
, so how would I pass that into the function? Passingarray[0][0]
into it gives me incompatible argument type, as does&array
and&array[0][0]
.
In your main()
, the variable should be:
double array[10][20];
or something faintly similar; maybe
double array[][20] = { { 1.0, 0.0, ... }, ... };
You should be able to pass that with code like this:
typedef struct graph_node
{
int X;
int Y;
int active;
} g_node;
void print_graph(g_node graph_node[], double weight[][20], int nodes);
int main(void)
{
g_node g[10];
double array[10][20];
int n = 10;
print_graph(g, array, n);
return 0;
}
That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:
/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c
It depends on the recursion level for triggers currently set on the DB.
If you do this:
SP_CONFIGURE 'nested_triggers',0
GO
RECONFIGURE
GO
Or this:
ALTER DATABASE db_name
SET RECURSIVE_TRIGGERS OFF
That trigger above won't be called again, and you would be safe (unless you get into some kind of deadlock; that could be possible but maybe I'm wrong).
Still, I do not think this is a good idea. A better option would be using an INSTEAD OF trigger. That way you would avoid executing the first (manual) update over the DB. Only the one defined inside the trigger would be executed.
An INSTEAD OF INSERT trigger would be like this:
CREATE TRIGGER setDescToUpper ON part_numbers
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO part_numbers (
colA,
colB,
part_description
) SELECT
colA,
colB,
UPPER(part_description)
) FROM
INSERTED
END
GO
This would automagically "replace" the original INSERT statement by this one, with an explicit UPPER call applied to the part_description
field.
An INSTEAD OF UPDATE trigger would be similar (and I don't advise you to create a single trigger, keep them separated).
Also, this addresses @Martin comment: it works for multirow inserts/updates (your example does not).
If you really want them to have ALL rights:
use YourDatabase
go
exec sp_addrolemember 'db_owner', 'UserName'
go
git reset --hard
This command will completely remove all the local changes from your local repository. This is the best way to avoid conflicts during pull command, only if you don't want to keep your local changes at all.
If you want to pull the new changes from remote and want to ignore the local changes during this pull then,
git stash
It will stash all the local changes, now you can pull the remote changes,
git pull
Now, you can bring back your local changes by,
git stash pop
In my case I had a ucfirst
on the asian letters string. This was not possible and produced a non utf8 string.
Another approach I like to use for application specific filters, is to use a custom read-only property on your component which allows you to encapsulate the filtering logic more cleanly than using a custom pipe (IMHO).
For example, if I want to bind to albumList
and filter on searchText
:
searchText: "";
albumList: Album[] = [];
get filteredAlbumList() {
if (this.config.searchText && this.config.searchText.length > 1) {
var lsearchText = this.config.searchText.toLowerCase();
return this.albumList.filter((a) =>
a.Title.toLowerCase().includes(lsearchText) ||
a.Artist.ArtistName.toLowerCase().includes(lsearchText)
);
}
return this.albumList;
}
To bind in the HTML you can then bind to the read-only property:
<a class="list-group-item"
*ngFor="let album of filteredAlbumList">
</a>
I find for specialized filters that are application specific this works better than a pipe as it keeps the logic related to the filter with the component.
Pipes work better for globally reusable filters.
You can't, but you can use BETWEEN
SELECT job FROM mytable WHERE id BETWEEN 10 AND 15
Note that BETWEEN
is inclusive, and will include items with both id 10 and 15.
If you do not want inclusion, you'll have to fall back to using the >
and <
operators.
SELECT job FROM mytable WHERE id > 10 AND id < 15
You can filter using index
of array.
var months = ['Jan', 'March', 'April', 'June'];_x000D_
months = months.filter((month,idx) => idx < 2)_x000D_
console.log(months);
_x000D_
Stub, Fakes and Mocks have different meanings across different sources. I suggest you to introduce your team internal terms and agree upon their meaning.
I think it is important to distinguish between two approaches: - behaviour validation (implies behaviour substitution) - end-state validation (implies behaviour emulation)
Consider email sending in case of error. When doing behaviour validation - you check that method Send
of IEmailSender
was executed once. And you need to emulate return result of this method, return Id of the sent message. So you say: "I expect that Send
will be called. And I will just return dummy (or random) Id for any call". This is behaviour validation:
emailSender.Expect(es=>es.Send(anyThing)).Return((subject,body) => "dummyId")
When doing state validation you will need to create TestEmailSender
that implements IEmailSender
. And implement Send
method - by saving input to some data structure that will be used for future state verification like array of some objects SentEmails
and then it tests you will check that SentEmails
contains expected email. This is state validation:
Assert.AreEqual(1, emailSender.SentEmails.Count)
From my readings I understood that Behaviour validation usually called Mocks. And State validation usually called Stubs or Fakes.
public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
.Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}
Jeez guys
static string ReadPasswordLine()
{
string pass = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Enter)
{
if (!(key.KeyChar < ' '))
{
pass += key.KeyChar;
Console.Write("*");
}
else if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
{
Console.Write(Convert.ToChar(ConsoleKey.Backspace));
pass = pass.Remove(pass.Length - 1);
Console.Write(" ");
Console.Write(Convert.ToChar(ConsoleKey.Backspace));
}
}
} while (key.Key != ConsoleKey.Enter);
return pass;
}
I was looking to do this also. I have a large tile (literally an image of a tile) image which I'd like to rotate by just roughly 15 degrees and have repeated. You can imagine the size of an image which would repeat seamlessly, rendering the 'image editing program' answer useless.
My solution was give the un-rotated (just one copy :) tile image to psuedo :before element - oversize it - repeat it - set the container overflow to hidden - and rotate the generated :before element using css3 transforms. Bosh!
your_string = 'Hello world';
words_array = your_tring.split(' ');
string_without_space = '';
for(i=0; i<words_array.length; i++){
new_text += words_array[i];
}
console.log("The new word:" new_text);
The output:
HelloWorld
one thing need to mention on @LachlanB 's answer.
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
If you omit the line if (IsWebApiRequest())
The whole site will have page loading slowness issue if your site is mixed with web form pages.
This is likely due to your system's overcommit handling mode.
In the default mode, 0
,
Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to allocate slightly more memory in this mode. This is the default.
The exact heuristic used is not well explained here, but this is discussed more on Linux over commit heuristic and on this page.
You can check your current overcommit mode by running
$ cat /proc/sys/vm/overcommit_memory
0
In this case you're allocating
>>> 156816 * 36 * 53806 / 1024.0**3
282.8939827680588
~282 GB, and the kernel is saying well obviously there's no way I'm going to be able to commit that many physical pages to this, and it refuses the allocation.
If (as root) you run:
$ echo 1 > /proc/sys/vm/overcommit_memory
This will enable "always overcommit" mode, and you'll find that indeed the system will allow you to make the allocation no matter how large it is (within 64-bit memory addressing at least).
I tested this myself on a machine with 32 GB of RAM. With overcommit mode 0
I also got a MemoryError
, but after changing it back to 1
it works:
>>> import numpy as np
>>> a = np.zeros((156816, 36, 53806), dtype='uint8')
>>> a.nbytes
303755101056
You can then go ahead and write to any location within the array, and the system will only allocate physical pages when you explicitly write to that page. So you can use this, with care, for sparse arrays.
This is an easier way to do it. Hope this helps...
<script type="text/javascript">
$(document).ready(function () {
$("#preview").toggle(function() {
$("#div1").hide();
$("#div2").show();
}, function() {
$("#div1").show();
$("#div2").hide();
});
});
<div id="div1">
This is preview Div1. This is preview Div1.
</div>
<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>
<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
Links:
http://www.w3schools.com/jquery/default.asp (W3Schools)
http://thenewboston.org/list.php?cat=32 (Video Tutorials)
http://andreehansson.se/the-basics-of-jquery/ (Basic Tutorial)
I think you may have over-complicated your code: If you are just checking to see if a service is running and, if not, run it and then stop re-evaluating, the following should suffice:
$ServiceName = 'Serenade'
$arrService = Get-Service -Name $ServiceName
while ($arrService.Status -ne 'Running')
{
Start-Service $ServiceName
write-host $arrService.status
write-host 'Service starting'
Start-Sleep -seconds 60
$arrService.Refresh()
if ($arrService.Status -eq 'Running')
{
Write-Host 'Service is now Running'
}
}
Just in case you would need to delete a variable, you could use SETENV from Vincent Fatica available at http://barnyard.syr.edu/~vefatica. Not exactly recent ('98) but still working on Windows 7 x64.
You should place Scanner input = new Scanner (System.in);
into the main method rather than creating the input object outside.
Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:
-vm
path/javaw.exe
for example:
-vm
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe
You can use the slurp module to fetch a file from the remote host: (Thanks to @mlissner for suggesting it)
vars:
amazon_linux_ami: "ami-fb8e9292"
user_data_file: "base-ami-userdata.sh"
tasks:
- name: Load data
slurp:
src: "{{ user_data_file }}"
register: slurped_user_data
- name: Decode data and store as fact # You can skip this if you want to use the right hand side directly...
set_fact:
user_data: "{{ slurped_user_data.content | b64decode }}"
Of course that works; when @item1 = N''
, it IS NOT NULL
.
You can define @item1
as NULL
by default at the top of your stored procedure, and then not pass in a parameter.
Your other options include:
If your list is contained in the Adapter itself, calling the function that updates the list should also call notifyDataSetChanged()
.
Running this function from the UI Thread did the trick for me:
The refresh()
function inside the Adapter
public void refresh(){
//manipulate list
notifyDataSetChanged();
}
Then in turn run this function from the UI Thread
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.refresh()
}
});
To switch between color schemes: Choose View -> Quick Switch Scheme on the main menu or press Ctrl+Back Quote To bring back the old theme: Settings -> Appearance -> Theme
This worked for me (if it applies that you also see the lock file):
first>youridhere@ubuntu:/var/lib/mongodb$ sudo service mongodb start
then >youridhere@ubuntu:/var/lib/mongodb$ sudo rm mongod.lock*
I think the easiest way to match the characters like
\^$.?*|+()[
are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:
> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")
This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\
to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp
to see more info about this.
https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf