If you're using #
as an operator, consider defining a new operator for it:
\newcommand{\pound}{\operatornamewithlimits{\#}}
You can then write things like \pound_{n = 1}^N
and get:
<!---- script ---->
<script>
function myFunction(x) {
document.getElementById("demo").style.backgroundColor = x;
}
</script>
<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>
<!---- buttons & function call ---->
<a onClick="myFunction('red')" />RED</a>
<a onClick="myFunction('blue')" />BLUE</a>
<a onClick="myFunction('black')" />BLACK</a>
When selecting columns in R for a reduced data-set you can often end up with duplicates.
These two lines give the same result. Each outputs a unique data-set with two selected columns only:
distinct(mtcars, cyl, hp);
summarise(group_by(mtcars, cyl, hp));
The postgres:9.4
image you've inherited from declares a volume at /var/lib/postgresql/data
. This essentially means you can't copy any files to that path in your image; the changes will be discarded.
You have a few choices:
You could just add your own configuration files as a volume at run-time with docker run -v postgresql.conf:/var/lib/postgresql/data/postgresql.conf ...
. However, I'm not sure exactly how that will interact with the existing volume.
You could copy the file over when the container is started. To do that, copy your file into the build at a location which isn't underneath the volume then call a script from the entrypoint or cmd which will copy the file to correct location and start postgres.
Clone the project behind the Postgres official image and edit the Dockerfile to add your own config file in before the VOLUME is declared (anything added before the VOLUME instruction is automatically copied in at run-time).
Pass all config changes in command option in docker-compose file
like:
services:
postgres:
...
command:
- "postgres"
- "-c"
- "max_connections=1000"
- "-c"
- "shared_buffers=3GB"
- "-c"
...
This is a mintty version problem alternatively use cmd. To kill server process just run this command:
taskkill -F -IM node.exe
There's a 'cheap and dirty' trick that I have used... shhhh don't tell anyone. If you output tab delimited text and make the file name *.xls then Excel opens it without objection, question or warning. So just crank the data out into a text file with tab delimitation and you can open it with Excel or Open Office.
torch.reshape() is made to dupe the numpy reshape method.
It came after the view() and torch.resize_() and it is inside the dir(torch)
package.
import torch
x=torch.arange(24)
print(x, x.shape)
x_view = x.view(1,2,3,4) # works on is_contiguous() tensor
print(x_view.shape)
x_reshaped = x.reshape(1,2,3,4) # works on any tensor
print(x_reshaped.shape)
x_reshaped2 = torch.reshape(x_reshaped, (-1,)) # part of torch package, while view() and resize_() are not
print(x_reshaped2.shape)
Out:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23]) torch.Size([24])
torch.Size([1, 2, 3, 4])
torch.Size([1, 2, 3, 4])
torch.Size([24])
But did you know it can also work as a replacement for squeeze() and unsqueeze()
x = torch.tensor([1, 2, 3, 4])
print(x.shape)
x1 = torch.unsqueeze(x, 0)
print(x1.shape)
x2 = torch.unsqueeze(x1, 1)
print(x2.shape)
x3=x.reshape(1,1,4)
print(x3.shape)
x4=x.reshape(4)
print(x4.shape)
x5=x3.squeeze()
print(x5.shape)
Out:
torch.Size([4])
torch.Size([1, 4])
torch.Size([1, 1, 4])
torch.Size([1, 1, 4])
torch.Size([4])
torch.Size([4])
From previous answer
glob('*.jpg') + glob('*.png')
Here is a shorter one,
from glob import glob
extensions = ['jpg', 'png'] # to find these filename extensions
# Method 1: loop one by one and extend to the output list
output = []
[output.extend(glob(f'*.{name}')) for name in extensions]
print(output)
# Method 2: even shorter
# loop filename extension to glob() it and flatten it to a list
output = [p for p2 in [glob(f'*.{name}') for name in extensions] for p in p2]
print(output)
After installing maven using brew or manually, using macOS Catalina and using the terminal or iTerm to operate maven you will need to grant access to the apps to access user files.
System Preferences -> Privacy (button) -> Full Disk Access
And then add terminal or iTerm to that list.
You will also need to restart your application e.g. terminal or iTerm after giving them full disk access.
The example below shows the basic usage of the FileReader
to read the contents of an uploaded file. Here is a working Plunker of this example.
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
script.js
function init(){
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event){
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event){
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
Instead of setting absolute widths and heights, you can use percentages:
#mydiv img {
height: 100%;
width: 100%;
}
I have found the SMB2 protocol introduced in Vista to lock the access databases. It can be disabled by the following regedit:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanServer\Parameters] "Smb2"=dword:00000000
The Color
structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.
Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb
method:
Color myColor = Color.FromArgb(100, 150, 75);
The reason is that eclipse cannot find your gcc or g++ environment variable path.
You might have tried to run c
or c++
or fortran
but eclipse
cannot find out the compiler.
So, add the path in your environment variable.
Windows -> Search -environment variables -> click on environmental variables at bottom.
Click on path ->edit -> new -> your variable path
Path should be entire, for example:
C:\Users\mahidhai\cygwin64\usr\sbin
Make sure that the variable is permanently stored. It is not erased after you close the environment variables GUI.
Sometimes you might find it difficult to add a path variable. Make sure windows is updated.
Even if Windows is updated and you have problems, directly go to the registry and navigate to the below.
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
Add your path here. Remove any unnecessary repetitions of path variables.
Note: You need to add your path variables in system environment variables -path
Use std::to_chars
once your standard library provides it:
std::array<char, 32> buf;
auto result = std::to_chars(buf.data(), buf.data() + buf.size(), val);
if (result.ec == std::errc()) {
auto str = std::string(buf.data(), result.ptr - buf.data());
// use the string
} else {
// handle the error
}
The advantages of this method are:
Unfortunately std::to_string
is of limited utility with floating point because it uses the fixed representation, rounding small values to zero and producing long strings for large values, e.g.
auto s1 = std::to_string(1e+40);
// s1 == 10000000000000000303786028427003666890752.000000
auto s2 = std::to_string(1e-40);
// s2 == 0.000000
C++20 might get a more convenient std::format
API with the same benefits as std::to_chars
if the P0645 standards proposal gets approved.
There is a really simple way to do this in a CSS only way.
Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors. In the hover selector, make it visible by changing the opacity value.
#mouse_over {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
I had to explicitly call out the dependency for my json library in my POM.
Once I added the below dependency, it all worked.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
When a script is loaded, any parameters that are passed are automatically loaded into a special variables $args
. You can reference that in your script without first declaring it.
As an example, create a file called test.ps1
and simply have the variable $args
on a line by itself. Invoking the script like this, generates the following output:
PowerShell.exe -File test.ps1 a b c "Easy as one, two, three"
a
b
c
Easy as one, two, three
As a general recommendation, when invoking a script by calling PowerShell directly I would suggest using the -File
option rather than implicitly invoking it with the &
- it can make the command line a bit cleaner, particularly if you need to deal with nested quotes.
Looks like you've got some answers to this, however I think there is something worth mentioning here that will greatly simplify your code. jQuery introduced the $.when
in v1.5. It looks like:
$.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
//this callback will be fired once all ajax calls have finished.
});
Didn't see it mentioned here, hope it helps.
The easiest of all:
keytool -list -printcert -jarfile file.apk
This uses the Java built-in keytool app and does not require extraction or any build-tools installation.
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause</button></p>
_x000D_
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
I got the same error for a simple bash script that wouldn't have 32/64-bit issues. This is possibly because the script you are trying to run has an error in it. This ubuntu forum post indicates that with normal script files you can add 'sh' in front and you might get some debug output from it. e.g.
$ sudo sh arm-mingw32ce-g++
and see if you get any output.
In my case the actual problem was that the file that I was trying to execute was in Windows format rather than linux.
I found this post and I have just posted something on my blog that might help.
See Setting up a Msysgit Server with copSSH on Windows. It's long, but I have successfully got this working on Windows 7 Ultimate x64.
The best (IMHO) article about .NET Application configuration is on CodeProject, Unraveling the Mysteries of .NET 2.0 Configuration. And my next favorite (shorter) article about sections in the .NET configuration files is Understanding Section Handlers - App.config File.
use this code : (my problem was solved with this code)
function dateDiff(date1, date2){
var diff = {} // Initialisation du retour
var tmp = date2 - date1;
tmp = Math.floor(tmp/1000); // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60; // Extraction du nombre de secondes
tmp = Math.floor((tmp-diff.sec)/60); // Nombre de minutes (partie entière)
diff.min = tmp % 60; // Extraction du nombre de minutes
tmp = Math.floor((tmp-diff.min)/60); // Nombre d'heures (entières)
diff.hour = tmp % 24; // Extraction du nombre d'heures
tmp = Math.floor((tmp-diff.hour)/24); // Nombre de jours restants
diff.day = tmp;
return diff;
}
I got the same error because the remote SID specified was wrong:
> sqlplus $DATASOURCE_USERNAME/$DATASOURCE_PASSWORD@$DB_SERVER_URL/$REMOTE_SID
I queried the system database:
select * from global_name;
and found my remote SID ("XE").
Then I could connect without any problem.
adding a class touchscreen to the body using JS or jQuery
//allowing mobile only css
var isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/));
if(isMobile){
jQuery("body").attr("class",'touchscreen');
}
I end up having similar issue. So I discovered that the Software PostMan can generate code when clicking the "Code" button at upper/left corner. From that we can see what going on "under the hood" and the HTTP call is generated in many code language; curl command, C# RestShart, java, nodeJs, ...
That helped me a lot and instead of using .Net base HttpClient I ended up using RestSharp nuget package.
Hope that can help someone else!
It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).
One way around this is to bind your event handler in javascript (where it should be):
document.getElementById('optionID').onchange = function () {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:
window.changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
?
Select all, then:
Ctrl+Shift+p
then type "indent"
Shift+Command+p
then type "indent"
Initial answer (EL 2.1, May 2009)
As mentioned in this java forum thread:
Basically autoboxing puts an Integer object into the Map. ie:
map.put(new Integer(0), "myValue")
EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:
map.get(new Long(0))
As a Long
is never equal to an Integer
object, it does not find the entry in the map.
That's it in a nutshell.
Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:
you can call the method
intValue
on theLong
object self inside EL 2.2:
<c:out value="${map[(1).intValue()]}"/>
That could be a good workaround here (also mentioned below in Tobias Liefke's answer)
Original answer:
EL uses the following wrappers:
Terms Description Type
null null value. -
123 int value. java.lang.Long
123.00 real value. java.lang.Double
"string" ou 'string' string. java.lang.String
true or false boolean. java.lang.Boolean
JSP page demonstrating this:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="java.util.*" %>
<h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%= application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
<%
Map map = new LinkedHashMap();
map.put("2", "String(2)");
map.put(new Integer(2), "Integer(2)");
map.put(new Long(2), "Long(2)");
map.put(42, "AutoBoxedNumber");
pageContext.setAttribute("myMap", map);
Integer lifeInteger = new Integer(42);
Long lifeLong = new Long(42);
%>
<h3>Looking up map in JSTL - integer vs long </h3>
This page demonstrates how JSTL maps interact with different types used for keys in a map.
Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.
<table border="1">
<tr><th>Key</th><th>value</th><th>Key Class</th></tr>
<c:forEach var="entry" items="${myMap}" varStatus="status">
<tr>
<td>${entry.key}</td>
<td>${entry.value}</td>
<td>${entry.key.class}</td>
</tr>
</c:forEach>
</table>
<h4> Accessing the map</h4>
Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
Evaluating: ${"${myMap[2]}"} = <c:out value="${myMap[2]}"/><br>
Evaluating: ${"${myMap[42]}"} = <c:out value="${myMap[42]}"/><br>
<p>
As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer
<p>
lifeInteger = <%= lifeInteger %><br/>
lifeLong = <%= lifeLong %><br/>
lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>
Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:
PHP Code sample:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}
In particular, don't add an exit;
as no preflight is needed.
Specific font
Setting a specific font in Swift is done like this:
let myFont = UIFont(name: "Helvetica", size: 17)
If you don't know the name, you can get a list of the available font names like this:
print(UIFont.familyNames())
Or an even more detailed list like this:
for familyName in UIFont.familyNames() {
print(UIFont.fontNamesForFamilyName(familyName))
}
But the system font changes from version to version of iOS. So it would be better to get the system font dynamically.
System font
let myFont = UIFont.systemFontOfSize(17)
But we have the size hard-coded in. What if the user's eyes are bad and they want to make the font larger? Of course, you could make a setting in your app for the user to change the font size, but this would be annoying if the user had to do this separately for every single app on their phone. It would be easier to just make one change in the general settings...
Dynamic font
let myFont = UIFont.preferredFont(forTextStyle: .body)
Ah, now we have the system font at the user's chosen size for the Text Style we are working with. This is the recommended way of setting the font. See Supporting Dynamic Type for more info on this.
When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:
def add(a,b):
return a + b
you would call the function like this:
add(3,5)
which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:
answer = add(4,7)
Which would set the variable answer equal to 11 in this case.
Here is how I achieved this without using configurations{ }
.
apply plugin: 'java'
sourceCompatibility = JavaVersion.VERSION_1_6
sourceSets {
integrationTest {
java {
srcDir 'src/integrationtest/java'
}
resources {
srcDir 'src/integrationtest/resources'
}
compileClasspath += sourceSets.main.runtimeClasspath
}
}
task integrationTest(type: Test) {
description = "Runs Integration Tests"
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath += sourceSets.integrationTest.runtimeClasspath
}
Tested using: Gradle 1.4 and Gradle 1.6
This question can also be extended if necessary jar file can be found in global library, how can you configure it into your current project.
Process like these: "project structure"-->"modules"-->"click your current project pane at right"-->"dependencies"-->"click little add(+) button"-->"library"-->"select the library you want".
if you are using maven and you can also configure dependency in your pom.xml, but it your chosen version is not like the global library, you will waste memory on storing another version of the same jar file. so i suggest use the first step.
Probably the shortest version:
[System.Collections.ArrayList]$someArray
It is also faster because it does not call relatively expensive New-Object
.
Use a library to handle phone number. Libphonenumber by Google is your best bet.
// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;
// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');
// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414
I recommend to use this package by seegno.
None of the answers found here is correct. @stinkycheeseman asked to round up, you all rounded the number.
To round up, use this:
Math.ceil(num * 100)/100;
If you are interested in html formatted email, make sure to pass Content-type: text/html;
in the header. Example:
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
<head>
<title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
<tr>
<th>Person</th><th>Day</th><th>Month</th><th>Year</th>
</tr>
<tr>
<td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
</tr>
<tr>
<td>Sally</td><td>17th</td><td>August</td><td>1973</td>
</tr>
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
For more details, check php mail function.
As mentioned, the difference is primarily the size of the underlying variables, which in each case get larger to allow more characters to be represented.
However, fonts, encoding and things are wickedly complicated (unnecessarily?), so a big link is needed to fill in more detail:
http://www.cs.tut.fi/~jkorpela/chars.html#ascii
Don't expect to understand it all, but if you don't want to have problems later it's worth learning as much as you can, as early as you can (or just getting someone else to sort it out for you).
Paul.
My answer does not require Javascript and only relies on CSS3 (available in most modern browsers). I personally like it very much if design is not relying on Javascript too much.
My answer is a "pure CSS3 , no Javascript required"-solution:
The solution as can be seen here (http://jsfiddle.net/uNF3Z/16/) uses the following additions to the CSS styles (which make use of the @media
query of CSS3 which)
@media all and (min-width: 50px) { body { font-size:0.1em; } }
@media all and (min-width: 100px) { body { font-size:0.2em; } }
@media all and (min-width: 200px) { body { font-size:0.4em; } }
@media all and (min-width: 300px) { body { font-size:0.6em; } }
@media all and (min-width: 400px) { body { font-size:0.8em; } }
@media all and (min-width: 500px) { body { font-size:1.0em; } }
@media all and (min-width: 600px) { body { font-size:1.2em; } }
@media all and (min-width: 700px) { body { font-size:1.4em; } }
@media all and (min-width: 800px) { body { font-size:1.6em; } }
@media all and (min-width: 900px) { body { font-size:1.8em; } }
@media all and (min-width: 1000px) { body { font-size:2.0em; } }
@media all and (min-width: 1100px) { body { font-size:2.2em; } }
@media all and (min-width: 1200px) { body { font-size:2.4em; } }
@media all and (min-width: 1300px) { body { font-size:2.6em; } }
@media all and (min-width: 1400px) { body { font-size:2.8em; } }
@media all and (min-width: 1500px) { body { font-size:3.0em; } }
@media all and (min-width: 1500px) { body { font-size:3.2em; } }
@media all and (min-width: 1600px) { body { font-size:3.4em; } }
@media all and (min-width: 1700px) { body { font-size:3.6em; } }
What this in effect causes is that the font-size is adjusted to the available screen width. This adjustment is done in steps of 100px (which is finegrained enough for most purposes) and covers a maximum screen width of 1700px which I reckon to be amply (2013) and can by adding further lines be further improved.
A side benefit is that the adjustment of the font-size is occuring at each resize. This dynamic adjustment (because for instance the browser windows is resized) might not yet be covered by the Javascript based solution.
You can use DataFrame.xs()
:
In [36]: df = DataFrame(np.random.randn(10, 4))
In [37]: df.columns = [np.random.choice(['a', 'b'], size=4).tolist(), np.random.choice(['c', 'd'], size=4)]
In [38]: df.columns.names = ['A', 'B']
In [39]: df
Out[39]:
A b a
B d d d d
0 -1.406 0.548 -0.635 0.576
1 -0.212 -0.583 1.012 -1.377
2 0.951 -0.349 -0.477 -1.230
3 0.451 -0.168 0.949 0.545
4 -0.362 -0.855 1.676 -2.881
5 1.283 1.027 0.085 -1.282
6 0.583 -1.406 0.327 -0.146
7 -0.518 -0.480 0.139 0.851
8 -0.030 -0.630 -1.534 0.534
9 0.246 -1.558 -1.885 -1.543
In [40]: df.xs('a', level='A', axis=1)
Out[40]:
B d d
0 -0.635 0.576
1 1.012 -1.377
2 -0.477 -1.230
3 0.949 0.545
4 1.676 -2.881
5 0.085 -1.282
6 0.327 -0.146
7 0.139 0.851
8 -1.534 0.534
9 -1.885 -1.543
If you want to keep the A
level (the drop_level
keyword argument is only available starting from v0.13.0):
In [42]: df.xs('a', level='A', axis=1, drop_level=False)
Out[42]:
A a
B d d
0 -0.635 0.576
1 1.012 -1.377
2 -0.477 -1.230
3 0.949 0.545
4 1.676 -2.881
5 0.085 -1.282
6 0.327 -0.146
7 0.139 0.851
8 -1.534 0.534
9 -1.885 -1.543
SOLUTION: @Before building your component (using mvn clean install). Build the entire project once and build your component again
WHY SO :
I get this error many times.
Most of the times I will try to build my component alone (As I have not made changes elsewhere).
Right, But that extra jar which has been downloaded recently might have affected by changes done by a third party(inside their component). Making a full mvn clean install on entire project saved me many times
The typeof operator...
typeof(T)
... won't work with the c# switch statement. But how about this? The following post contains a static class...
Is there a better alternative than this to 'switch on type'?
...that will let you write code like this:
TypeSwitch.Do(
sender,
TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
df['newcol'] = pd.Series(your_2d_numpy_array)
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace()
is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g
(global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
I think this can also works for you select count(*) as anc,(select count(*) from Patient where sex='F')as patientF,(select count(*) from Patient where sex='M') as patientM from anc
and also you can select and count related tables like this select count(*) as anc,(select count(*) from Patient where Patient.Id=anc.PatientId)as patientF,(select count(*) from Patient where sex='M') as patientM from anc
The most upvoted answer can be improved.
Let me refer to GNU Make manual "Setting variables" and "Flavors", and add some comments.
The value you specify is installed verbatim; if it contains references to other variables, these references are expanded whenever this variable is substituted (in the course of expanding some other string). When this happens, it is called recursive expansion.
foo = $(bar)
The catch: foo
will be expanded to the value of $(bar)
each time foo
is evaluated, possibly resulting in different values. Surely you cannot call it "lazy"! This can surprise you if executed on midnight:
# This variable is haunted!
WHEN = $(shell date -I)
something:
touch $(WHEN).flag
# If this is executed on 00:00:00:000, $(WHEN) will have a different value!
something-else-later: something
test -f $(WHEN).flag || echo "Boo!"
VARIABLE := value
VARIABLE ::= value
Variables defined with ‘:=’ or ‘::=’ are simply expanded variables.
Simply expanded variables are defined by lines using ‘:=’ or ‘::=’ [...]. Both forms are equivalent in GNU make; however only the ‘::=’ form is described by the POSIX standard [...] 2012.
The value of a simply expanded variable is scanned once and for all, expanding any references to other variables and functions, when the variable is defined.
Not much to add. It's evaluated immediately, including recursive expansion of, well, recursively expanded variables.
The catch: If VARIABLE
refers to ANOTHER_VARIABLE
:
VARIABLE := $(ANOTHER_VARIABLE)-yohoho
and ANOTHER_VARIABLE
is not defined before this assignment, ANOTHER_VARIABLE
will expand to an empty value.
FOO ?= bar
is equivalent to
ifeq ($(origin FOO), undefined)
FOO = bar
endif
where $(origin FOO)
equals to undefined
only if the variable was not set at all.
The catch: if FOO
was set to an empty string, either in makefiles, shell environment, or command line overrides, it will not be assigned bar
.
VAR += bar
When the variable in question has not been defined before, ‘+=’ acts just like normal ‘=’: it defines a recursively-expanded variable. However, when there is a previous definition, exactly what ‘+=’ does depends on what flavor of variable you defined originally.
So, this will print foo bar
:
VAR = foo
# ... a mile of code
VAR += $(BAR)
BAR = bar
$(info $(VAR))
but this will print foo
:
VAR := foo
# ... a mile of code
VAR += $(BAR)
BAR = bar
$(info $(VAR))
The catch is that +=
behaves differently depending on what type of variable VAR
was assigned before.
The syntax to assign multiline value to a variable is:
define VAR_NAME :=
line
line
endef
or
define VAR_NAME =
line
line
endef
Assignment operator can be omitted, then it creates a recursively-expanded variable.
define VAR_NAME
line
line
endef
The last newline before endef
is removed.
HASH != printf '\043'
is the same as
HASH := $(shell printf '\043')
Don't use it. $(shell)
call is more readable, and the usage of both in a makefiles is highly discouraged. At least, $(shell)
follows Joel's advice and makes wrong code look obviously wrong.
I tried all the answers, but failed. Directly get the source from the official site and then build install success.
tar xf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
sudo python setup.py install
Here I first filter arr1
based on element present in arr2
or not. If it's present then don't add it to resulting array otherwise do add. And then I append arr2
to the result.
arr1.filter(item => {
if (!arr2.some(item1=>item.name==item1.name)) {
return item
}
}).concat(arr2)
I just ran into this problem myself, and I found that the issue was something different than what the others have run into.
I had two DLLs that my main project was referencing: CompanyClasses.dll and CompanyControls.dll. I was getting a run-time error saying:
Could not load file or assembly 'CompanyClasses, Version=1.4.1.0, Culture=neutral, PublicKeyToken=045746ba8544160c' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference
Trouble was, I didn't have any CompanyClasses.dll files on my system with a version number of 1.4.1. None in the GAC, none in the app folders...none anywhere. I searched my entire hard drive. All the CompanyClasses.dll files I had were 1.4.2.
The real problem, I found, was that CompanyControls.dll referenced version 1.4.1 of CompanyClasses.dll. I just recompiled CompanyControls.dll (after having it reference CompanyClasses.dll 1.4.2) and this error went away for me.
I'm using the awesome_print gem
So you just have to type :
ap @var
Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:
Options -Indexes
Or try:
Options All -Indexes
Personally i prefer the format function, allows you to simply change the date part very easily.
declare @format varchar(100) = 'yyyy/MM/dd'
select
format(the_date,@format),
sum(myfield)
from mytable
group by format(the_date,@format)
order by format(the_date,@format) desc;
The simplest way is to do:
git push --all origin
This will push tags and branches.
you just need to use word boundary (\b
) instead of ^
and $
:
\bgarp\b
One of the simplest ways to convert the categorical variable into dummy/indicator variables is to use get_dummies provided by pandas.
Say for example we have data in which sex
is a categorical value (male & female)
and you need to convert it into a dummy/indicator here is how to do it.
tranning_data = pd.read_csv("../titanic/train.csv")
features = ["Age", "Sex", ] //here sex is catagorical value
X_train = pd.get_dummies(tranning_data[features])
print(X_train)
Age Sex_female Sex_male
20 0 1
33 1 0
40 1 0
22 1 0
54 0 1
_x000D_
Use /config.php
.
You might want to check HTML frames, which can do pretty much exactly what you are looking for. They are considered outdated however.
I'm using Walter's approach from above (see: https://stackoverflow.com/a/14246240/3076102)
I mix in a solution I found here https://stackoverflow.com/a/7967670 to properly show Objects.
This means the trap function becomes:
function trap(){
if(debugging){
// create an Array from the arguments Object
var args = Array.prototype.slice.call(arguments);
// console.raw captures the raw args, without converting toString
console.raw.push(args);
var index;
for (index = 0; index < args.length; ++index) {
//fix for objects
if(typeof args[index] === 'object'){
args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,' ');
}
}
var message = args.join(' ');
console.messages.push(message);
// instead of a fallback function we use the next few lines to output logs
// at the bottom of the page with jQuery
if($){
if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
$('#_console_log').append(message).append($('<br />'));
}
}
}
I hope this is helpful:-)
Problem with xampp in my case is when specifying a different folder other than htdocs are used, especially with multiple domains and dedicated folders. This is because httpd-ssl.conf
is also referencing <VirtualHost>
.
To do this rem out the entire <VirtualHost>
entry under httpd-ssl.conf
From there, any setting you do in your httpd-vhosts.conf
will update as expected both http
and https
references.
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
The Test-Connection command seems to be a useful alternative, and it can either provide either a Win32_PingStatus object, or a boolean value.
Documentation: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/test-connection
Here's what I'm using:
$('input.date').datepicker({
beforeShow: function(input, inst) {
inst.dpDiv.css({
marginTop: -input.offsetHeight + 'px',
marginLeft: input.offsetWidth + 'px'
});
}
});
You may also want to add a bit more to the left margin so it's not right up against the input field.
I found answer myself; and if someone will face same issue, i hope my solution will work for them as well.
Use break;
and this will exit the foreach loop
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
Left alinged triangle- * **
from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)each row contains star and no of stars i each row is incremented by 1.
So for Left alinged triangle we need to use 2 for loop.
1st "for loop" for printing n row.
2nd "for loop for printing stars in each rows.
Code for Left alinged triangle-
public static void leftTriangle()
{
/// here no of rows is 4
for (int a=1;a<=4;a++)// for loop for row
{
for (int b=1;b<=a;b++)for loop for column
{
System.out.print("*");
}
System.out.println();}
}
Right alinged triangle-
*
**
from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)In each row we need to print spaces followed by a star & no of spaces in each row is decremented by 1.
So for Right alinged triangle we need to use 3 for loop.
1st "for loop" for printing n row.
2nd "for loop for printing spaces.
3rd "for loop" for printing stars.
Code for Right alinged triangle -
public void rightTriangle()
{
// here 1st print space and then print star
for (int a=1;a<=4;a++)// for loop for row
{
for (int c =3;c>=a;c--)// for loop fr space
{
System.out.print(" ");
}
for (int d=1;d<=a;d++)// for loop for column
{
System.out.print("*");
}
System.out.println();
}
}
Center Triangle-
*
* *
from above pattern we come to know that- 1)we need to print pattern containing n rows (for above pattern n is 4). 2)Intially in each row we need to print spaces followed by a star & then again a space . NO of spaces in each row at start is decremented by 1. So for Right alinged triangle we need to use 3 for loop. 1st "for loop" for printing n row. 2nd "for loop for printing spaces. 3rd "for loop" for printing stars.
Code for center Triangle-
public void centerTriangle()
{
for (int a=1;a<=4;a++)// for lop for row
{
for (int c =4;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}
CODE FOR PRINTING ALL 3 PATTERNS -
public class space4
{
public static void leftTriangle()
{
/// here no of rows is 4
for (int a=1;a<=4;a++)// for loop for row
{
for (int b=1;b<=a;b++)for loop for column
{
System.out.print("*");
}
System.out.println();}
}
public static void rightTriangle()
{
// here 1st print space and then print star
for (int a=1;a<=4;a++)// for loop for row
{
for (int c =3;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int d=1;d<=a;d++)// for loop for column
{
System.out.print("*");
}
System.out.println();
}
}
public static void centerTriangle()
{
for (int a=1;a<=4;a++)// for lop for row
{
for (int c =4;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}
public static void main (String args [])
{
space4 s=new space4();
s.leftTriangle();
s.rightTriangle();
s.centerTriangle();
}
}
This is not possible in the requested way because there are numbers with two decimal places which can not be expressed exactly using IEEE floating point numbers (for example 1/10 = 0.1 can not be expressed as a Double
or Float
). The formatting should always happen as the last step before presenting the result to the user.
I guess you are asking because you want to deal with monetary values. There is no way to do this reliably with floating-point numbers, you shoud consider switching to fixed-point arithmetics. This probably means doing all calculations in "cents" instead of "dollars".
Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.
You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:
$('#add_comment').click(function() {
if(typeof TinyMCE == "undefined") {
$.getScript('tinymce.js', function() {
TinyMCE.init();
});
}
});
Assuming you only have to call init
on it once, that is. If not, you can figure it out from here :)
For me Pawan's css class combined with display: inline-block (so the selects don't stack) works best. And I wrap it in a media-query, so it stays Mobile Friendly:
@media (min-width: $screen-xs) {
.selectwidthauto {
width:auto !important;
display: inline-block;
}
}
You are trying to load a XIB named DetailViewController
, but no such XIB exists or it's not member of your current target.
You can use some code like this, you can adjust a height and width as per your need
protected void button_Click(object sender, EventArgs e)
{
// open a pop up window at the center of the page.
ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
}
I'm on Windows, and I got it by giving command go help gopath
to cmd, and read the bold text in the instruction,
that is if code you wnat to install is at ..BaseDir...\SomeProject\src\basic\set
, the GOPATH should not be the same location as code, it should be just Base Project DIR: ..BaseDir...\SomeProject
.
The GOPATH environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string. On Plan 9, the value is a list.
If the environment variable is unset, GOPATH defaults to a subdirectory named "go" in the user's home directory ($HOME/go on Unix, %USERPROFILE%\go on Windows), unless that directory holds a Go distribution. Run "go env GOPATH" to see the current GOPATH.
See https://golang.org/wiki/SettingGOPATH to set a custom GOPATH.
Each directory listed in GOPATH must have a prescribed structure:
The src directory holds source code. The path below src determines the import path or executable name.
The pkg directory holds installed package objects. As in the Go tree, each target operating system and architecture pair has its own subdirectory of pkg (pkg/GOOS_GOARCH).
If DIR is a directory listed in the GOPATH, a package with source in DIR/src/foo/bar can be imported as "foo/bar" and has its compiled form installed to "DIR/pkg/GOOS_GOARCH/foo/bar.a".
The bin directory holds compiled commands. Each command is named for its source directory, but only the final element, not the entire path. That is, the command with source in DIR/src/foo/quux is installed into DIR/bin/quux, not DIR/bin/foo/quux. The "foo/" prefix is stripped so that you can add DIR/bin to your PATH to get at the installed commands. If the GOBIN environment variable is set, commands are installed to the directory it names instead of DIR/bin. GOBIN must be an absolute path.
Here's an example directory layout:
GOPATH=/home/user/go /home/user/go/ src/ foo/ bar/ (go code in package bar) x.go quux/ (go code in package main) y.go bin/ quux (installed command) pkg/ linux_amd64/ foo/ bar.a (installed package object)
..........
if GOPATH has been set to Base Project DIR and still has this problem, in windows you can try to set GOBIN as Base Project DIR\bin
or %GOPATH%\bin
.
You can do it with following code(track by),
<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>
Once I had to make the same decision and I'm really happy with that decision today. Use resque scheduler because not only a seperate redis will take out the load from your db, you will also have access to many plugins like resque-web which provides a great user interface. As your system develops you will have more and more tasks to schedule so you will be able to control them from a single place.
I met with the same error. After struggling, I found that it was due to "Space" in the folder name.
For example :
Earlier My folder name was : "Qt Projects"
Later I changed it to : "QtProjects"
and my issue was resolved.
Its very simple but sometimes a major issue.
An improvement upon previous answers (working on multi-line or tabbed strings):
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
String.prototype.firstWord = function(){let sp=this.search(/\s/);return sp<0?this:this.substr(0,sp)}
Or without regex:
String.prototype.firstWord = function(){
let sps=[this.indexOf(' '),this.indexOf('\u000A'),this.indexOf('\u0009')].
filter((e)=>e!==-1);
return sps.length? this.substr(0,Math.min(...sps)) : this;
}
Examples:
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}_x000D_
console.log(`linebreak_x000D_
example 1`.firstWord()); // -> linebreak_x000D_
console.log('space example 2'.firstWord()); // -> singleline_x000D_
console.log('tab example 3'.firstWord()); // -> tab
_x000D_
I like to use this. There is nothing wrong with using the for loop, I just like using the build-in functions. You could even pass in a boolean argument for typecast or non typecast matching, which in that case you would use a for loop (the filter()
method/function does typecast matching (===))
Array.prototype.unique =
function()
{
return this.filter(
function(val, i, arr)
{
return (i <= arr.indexOf(val));
}
);
}
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
To reset the styles defined for legend
in bootstrap, you can do following in your css file:
legend {
all: unset;
}
Ref: https://css-tricks.com/almanac/properties/a/all/
The all property in CSS resets all of the selected element's properties, except the direction and unicode-bidi properties that control text direction.
Possible values are: initial
, inherit
& unset
.
Side note: clear
property is used in relation with float
(https://css-tricks.com/almanac/properties/c/clear/)
Not quite answering the question, but rather than having
if (error condition that would break you out of this) {
break; // leaves looping structure
}
You should probably have
while(condition && !error_condition)
Also, I'd go with a Timer
.
On MinGW, the _WIN32
define check isn't working. Here's a solution:
#if defined(_WIN32) || defined(__CYGWIN__)
// Windows (x86 or x64)
// ...
#elif defined(__linux__)
// Linux
// ...
#elif defined(__APPLE__) && defined(__MACH__)
// Mac OS
// ...
#elif defined(unix) || defined(__unix__) || defined(__unix)
// Unix like OS
// ...
#else
#error Unknown environment!
#endif
For more information please look: https://sourceforge.net/p/predef/wiki/OperatingSystems/
Many of the answers posted to this question discuss IEEE and the standards surrounding floating-point arithmetic.
Coming from a non-computer science background (physics and engineering), I tend to look at problems from a different perspective. For me, the reason why I wouldn't use a double or float in a mathematical calculation is that I would lose too much information.
What are the alternatives? There are many (and many more of which I am not aware!).
BigDecimal in Java is native to the Java language. Apfloat is another arbitrary-precision library for Java.
The decimal data type in C# is Microsoft's .NET alternative for 28 significant figures.
SciPy (Scientific Python) can probably also handle financial calculations (I haven't tried, but I suspect so).
The GNU Multiple Precision Library (GMP) and the GNU MFPR Library are two free and open-source resources for C and C++.
There are also numerical precision libraries for JavaScript(!) and I think PHP which can handle financial calculations.
There are also proprietary (particularly, I think, for Fortran) and open-source solutions as well for many computer languages.
I'm not a computer scientist by training. However, I tend to lean towards either BigDecimal in Java or decimal in C#. I haven't tried the other solutions I've listed, but they are probably very good as well.
For me, I like BigDecimal because of the methods it supports. C#'s decimal is very nice, but I haven't had the chance to work with it as much as I'd like. I do scientific calculations of interest to me in my spare time, and BigDecimal seems to work very well because I can set the precision of my floating point numbers. The disadvantage to BigDecimal? It can be slow at times, especially if you're using the divide method.
You might, for speed, look into the free and proprietary libraries in C, C++, and Fortran.
This works for me: View view is your editText, spinner...etc. And int drawable is your drawable route example (R.drawable.yourDrawable)
public void verifyDrawable (View view, int drawable){
int sdk = Build.VERSION.SDK_INT;
if(sdk < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(
ContextCompat.getDrawable(getContext(),drawable));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(getResources().getDrawable(drawable));
}
}
Python long
can be arbitrarily large. If you need a value that's greater than any other value, you can use float('inf')
, since Python has no trouble comparing numeric values of different types. Similarly, for a value lesser than any other value, you can use float('-inf')
.
Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):
When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.
Note: the answer was edited on Jan 2016 to reflect most recent changes
Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out: Bjax
Usage:
<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />
Finally, include this in the HEAD of your html:
$('a').bjax();
For more settings, checkout demo here: Bjax Demo
you can use implicit casting AddWithValue
cmd.Parameters.AddWithValue("@param1", klantId);
cmd.Parameters.AddWithValue("@param2", klantNaam);
cmd.Parameters.AddWithValue("@param3", klantVoornaam);
sample code,
using (SqlConnection conn = new SqlConnection("connectionString"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"INSERT INTO klant(klant_id,naam,voornaam)
VALUES(@param1,@param2,@param3)";
cmd.Parameters.AddWithValue("@param1", klantId);
cmd.Parameters.AddWithValue("@param2", klantNaam);
cmd.Parameters.AddWithValue("@param3", klantVoornaam);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException e)
{
MessgeBox.Show(e.Message.ToString(), "Error Message");
}
}
}
Try downloading and installing 32-bit version of Java, and then setting the path :)
Couple of things to try...
Comment out the second "Set NewBook" line of code...
You already have an object reference to the workbook.
Do your SaveAs after copying the sheets.
You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.
If you trust the data source, you can use eval
to convert your string into a dictionary:
eval(your_json_format_string)
Example:
>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)
>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}
>>> print type(x), type(y)
<type 'str'> <type 'dict'>
>>> print y['a'], type(y['a'])
1 <type 'int'>
>>> print y['a'], type(y['b'])
1 <type 'bool'>
>>> print y['a'], type(y['c'])
1 <type 'str'>
Spy can be useful when you want to create unit tests for legacy code.
I have created a runable example here https://www.surasint.com/mockito-with-spy/ , I copy some of it here.
If you have something like this code:
public void transfer( DepositMoneyService depositMoneyService, WithdrawMoneyService withdrawMoneyService,
double amount, String fromAccount, String toAccount){
withdrawMoneyService.withdraw(fromAccount,amount);
depositMoneyService.deposit(toAccount,amount);
}
You may don't need spy because you can just mock DepositMoneyService and WithdrawMoneyService.
But with some, legacy code, dependency is in the code like this:
public void transfer(String fromAccount, String toAccount, double amount){
this.depositeMoneyService = new DepositMoneyService();
this.withdrawMoneyService = new WithdrawMoneyService();
withdrawMoneyService.withdraw(fromAccount,amount);
depositeMoneyService.deposit(toAccount,amount);
}
Yes, you can change to the first code but then API is changed. If this method is being used by many places, you have to change all of them.
Alternative is that you can extract the dependency out like this:
public void transfer(String fromAccount, String toAccount, double amount){
this.depositeMoneyService = proxyDepositMoneyServiceCreator();
this.withdrawMoneyService = proxyWithdrawMoneyServiceCreator();
withdrawMoneyService.withdraw(fromAccount,amount);
depositeMoneyService.deposit(toAccount,amount);
}
DepositMoneyService proxyDepositMoneyServiceCreator() {
return new DepositMoneyService();
}
WithdrawMoneyService proxyWithdrawMoneyServiceCreator() {
return new WithdrawMoneyService();
}
Then you can use the spy the inject the dependency like this:
DepositMoneyService mockDepositMoneyService = mock(DepositMoneyService.class);
WithdrawMoneyService mockWithdrawMoneyService = mock(WithdrawMoneyService.class);
TransferMoneyService target = spy(new TransferMoneyService());
doReturn(mockDepositMoneyService)
.when(target).proxyDepositMoneyServiceCreator();
doReturn(mockWithdrawMoneyService)
.when(target).proxyWithdrawMoneyServiceCreator();
More detail in the link above.
You can use set in a class like below and set to input text class
CSS:
.place-holder-center::placeholder {
text-align: center;
}
HTML:
<input type="text" class="place-holder-center">
You seem to be unnecessarily setting properties on your ComboBox
. You can remove the DisplayMemberPath
and SelectedValuePath
properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:
<ComboBox Name="cbxSalesPeriods"
ItemsSource="{Binding SalesPeriods}"
SelectedItem="{Binding SelectedSalesPeriod}"
IsSynchronizedWithCurrentItem="True"/>
Furthermore, it is pointless using your displayPeriod
property, as the WPF Framework would call the ToString
method automatically for objects that it needs to display that don't have a DataTemplate
set up for them explicitly.
UPDATE >>>
As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod
property and also your SalesPeriodVO
property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:
public class SalesPeriodV
{
private int month, year;
public int Year
{
get { return year; }
set
{
if (year != value)
{
year = value;
NotifyPropertyChanged("Year");
}
}
}
public int Month
{
get { return month; }
set
{
if (month != value)
{
month = value;
NotifyPropertyChanged("Month");
}
}
}
public override string ToString()
{
return String.Format("{0:D2}.{1}", Month, Year);
}
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(params string[] propertyNames)
{
if (PropertyChanged != null)
{
foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
}
}
}
Then I added two properties into the view model:
private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
get { return salesPeriods; }
set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}
Then initialised the collection with your values:
SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );
And then data bound only these two properties to a ComboBox
:
<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />
That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString
method without your displayPeriod
property. Hopefully, you can work out your mistakes from this code example.
Since display
is not one of the animatable CSS properties.
One display:none
fadeOut animation replacement with pure CSS3 animations, just set width:0
and height:0
at last frame, and use animation-fill-mode: forwards
to keep width:0
and height:0
properties.
@-webkit-keyframes fadeOut {
0% { opacity: 1;}
99% { opacity: 0.01;width: 100%; height: 100%;}
100% { opacity: 0;width: 0; height: 0;}
}
@keyframes fadeOut {
0% { opacity: 1;}
99% { opacity: 0.01;width: 100%; height: 100%;}
100% { opacity: 0;width: 0; height: 0;}
}
.display-none.on{
display: block;
-webkit-animation: fadeOut 1s;
animation: fadeOut 1s;
animation-fill-mode: forwards;
}
I got the error in the following case:
I simply avoided the obfuscation and the error is gone. not a real solution, but at least I know what caused it...
People like me who don't like migrations can use steps below.
python manage.py makemigrations app_label
for the initial migration.python manage.py migrate
for creating tables before you make changes.If you confused any of these steps, read the migration files. Change them to correct your schema or remove unwanted files but don't forget to change next migration file's dependencies part ;)
I hope this will help someone in future.
As a variant on baptiste's answer, with data
defined as you have and the columns that you want to put together defined in cols
cols <- c("b", "c", "d")
You can add the new column to data
and delete the old ones with
data$x <- do.call(paste, c(data[cols], sep="-"))
for (co in cols) data[co] <- NULL
which gives
> data
a x
1 1 a-d-g
2 2 b-e-h
3 3 c-f-i
You would probably want this. Simplest solution would be
Create file first.
open file via
f = open('<filename>', 'w')
or
f = open('<filename>', 'a')
in case you want to append to file
Now, write to the same file via
f.write(<text to be written>)
Close the file after you are done using it
#good pracitice
f.close()
DOMDocument::loadHTML
will treat your string as being in ISO-8859-1 unless you tell it otherwise. This results in UTF-8 strings being interpreted incorrectly.
If your string doesn't contain an XML encoding declaration, you can prepend one to cause the string to be treated as UTF-8:
$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();
If you cannot know if the string will contain such a declaration already, there's a workaround in SmartDOMDocument which should help you:
$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8'));
echo $dom->saveHTML();
This is not a great workaround, but since not all characters can be represented in ISO-8859-1 (like these katana), it's the safest alternative.
function showUploads(){
if (!class_exists('S3')) require_once 'S3.php';
// AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', '234567665464tg');
if (!defined('awsSecretKey')) define('awsSecretKey', 'dfshgfhfghdgfhrt463457');
$bucketName = 'my_bucket1234';
$s3 = new S3(awsAccessKey, awsSecretKey);
$contents = $s3->getBucket($bucketName);
echo "<hr/>List of Files in bucket : {$bucketName} <hr/>";
$n = 1;
foreach ($contents as $p => $v):
echo $p."<br/>";
$n++;
endforeach;
}
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
Yup, just GitHub flavored Markdown. Including a README file in your repository will help others quickly determine what it's about and how to install it. Very helpful to include in your repos.
The best solution is the tuple applied to a list comprehension, but to extract one item this could work:
def pop_tuple(tuple, n):
return tuple[:n]+tuple[n+1:], tuple[n]
It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.
And if I miss-read the question then I humbly accept the votes down. (Still good to know though)
Please consider the following code:
#some_div_or_body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
There are some alternatives that can be used with a little bit peace of mind by using jQuery:
HTML
<img src="images/bg.jpg" id="bg" alt="">
CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
jQuery:
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
I hope this helps!
I would use count()
if they are the same, as in my experience it is more common, and therefore will cause less developers reading your code to say "sizeof()
, what is that?" and having to consult the documentation.
I think it means sizeof()
does not work like it does in C (calculating the size of a datatype). It probably made this mention explicitly because PHP is written in C, and provides a lot of identically named wrappers for C functions (strlen()
, printf()
, etc)
Add a $ to the end of the regex to signify the end of the pattern:
var regExp = /^(\([0-9]{3}\)\s?|[0-9]{3}-)[0-9]{3}-[0-9]{4}$/;
If you have a file named filelist.txt that is a list paths such as the following: c:/dir1/dir2/file1.h c:/dir1/dir2/dir3/file2.h
then you can do this: rev filelist.txt | cut -d"/" -f1 | rev
In chrome, your best option might be the Snippets tab under Sources in the Developer Tools.
It will allow you to write and run code, for example, in a about:blank page.
More information here: https://developers.google.com/web/tools/chrome-devtools/debug/snippets/?hl=en
Ascii string to integer conversion is done by the atoi()
function.
The name of the public class within a file has to be the same as the name of that file.
So if your file declares class WeatherArray, it needs to be named WeatherArray.java
A typical way would be to use stringstream
:
#include <iomanip>
#include <sstream>
double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();
See fixed
Use fixed floating-point notation
Sets the
floatfield
format flag for the str stream tofixed
.When
floatfield
is set tofixed
, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision
) and with no exponent part.
and setprecision.
For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.
Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:
#include <array>
#include <charconv>
double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
std::chars_format::fixed, 2);
if (ec == std::errc{}) {
std::string s(buffer.data(), ptr);
// ....
}
else {
// error handling
}
You are using older MySql version. Update your myqsl to 5.6.5+ it will work.
Well, it's not a single statement, but it's about as close as you can get with oracle:
BEGIN
FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
END LOOP;
END;
Here is my own PHP function when I do POST to a specific URL of any page.... Sample: *** usage of my Function...
<?php
parse_str("[email protected]&subject=this is just a test");
$_POST['email']=$email;
$_POST['subject']=$subject;
echo HTTP_POST("http://example.com/mail.php",$_POST);***
exit;
?>
<?php
/*********HTTP POST using FSOCKOPEN **************/
// by ArbZ
function HTTP_Post($URL,$data, $referrer="") {
// parsing the given URL
$URL_Info=parse_url($URL);
// Building referrer
if($referrer=="") // if not given use this script as referrer
$referrer=$_SERVER["SCRIPT_URI"];
// making string from $data
foreach($data as $key=>$value)
$values[]="$key=".urlencode($value);
$data_string=implode("&",$values);
// Find out which port is needed - if not given use standard (=80)
if(!isset($URL_Info["port"]))
$URL_Info["port"]=80;
// building POST-request: HTTP_HEADERs
$request.="POST ".$URL_Info["path"]." HTTP/1.1\n";
$request.="Host: ".$URL_Info["host"]."\n";
$request.="Referer: $referer\n";
$request.="Content-type: application/x-www-form-urlencoded\n";
$request.="Content-length: ".strlen($data_string)."\n";
$request.="Connection: close\n";
$request.="\n";
$request.=$data_string."\n";
$fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
fputs($fp, $request);
while(!feof($fp)) {
$result .= fgets($fp, 128);
}
fclose($fp); //$eco = nl2br();
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[1];
}
//STORE THE FETCHED CONTENTS to a VARIABLE, because its way better and fast...
$str = $result;
$txt = getTextBetweenTags($str, "span"); $eco = $txt; $result = explode("&",$result);
return $result[1];
<span style=background-color:LightYellow;color:blue>".trim($_GET['em'])."</span>
</pre> ";
}
</pre>
See MSDN documentation for InitialCatalog Property:
Gets or sets the name of the database associated with the connection...
This property corresponds to the "Initial Catalog" and "database" keys within the connection string...
Your best bet is to use
table.YourClass tr:hover td {
background-color: #FEFEFE;
}
Rows aren't fully support for background color but cells are, using the combination of :hover and the child element will yield the results you need.
You can add comments to the end of a batch file with this syntax:
@echo off
:: Start of code
...
:: End of code
(I am a comment
So I am!
This can be only at the end of batch files
Just make sure you never use a closing parentheses.
Attributions: Leo Guttirez Ramirez on https://www.robvanderwoude.com/comments.php
Essentially you want to add code to the Calculate
event of the relevant Worksheet.
In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.
Alternatively, copy the code below into the editor of the sheet you want to use:
Private Sub Worksheet_Calculate()
If Sheets("MySheet").Range("A1").Value > 0.5 Then
MsgBox "Over 50%!", vbOKOnly
End If
End Sub
This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
Below code worked for me to generate and download a text file.
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDownloadData() throws Exception {
String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
byte[] output = regData.getBytes();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("charset", "utf-8");
responseHeaders.setContentType(MediaType.valueOf("text/html"));
responseHeaders.setContentLength(output.length);
responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");
return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);
}
VBA can use the dictionary structure of Scripting.Runtime
.
And its implementation is actually a fancy one - just by doing myDict(x) = y
, it checks whether there is a key x
in the dictionary and if there is not such, it even creates it. If it is there, it uses it.
And it does not "yell" or "complain" about this extra step, performed "under the hood". Of course, you may check explicitly, whether a key exists with Dictionary.Exists(key)
. Thus, these 5 lines:
If myDict.exists("B") Then
myDict("B") = myDict("B") + i * 3
Else
myDict.Add "B", i * 3
End If
are the same as this 1 liner - myDict("B") = myDict("B") + i * 3
. Check it out:
Sub TestMe()
Dim myDict As Object, i As Long, myKey As Variant
Set myDict = CreateObject("Scripting.Dictionary")
For i = 1 To 3
Debug.Print myDict.Exists("A")
myDict("A") = myDict("A") + i
myDict("B") = myDict("B") + 5
Next i
For Each myKey In myDict.keys
Debug.Print myKey; myDict(myKey)
Next myKey
End Sub
Try adding this rule to the top of your htaccess:
RewriteEngine On
RewriteRule ^404/?$ /pages/errors/404.php [L]
Then under that (or any other rules that you have):
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://domain.com/404/ [L,R]
Avoid using companion objects. Behind the hood, getter and setter instance methods are created for the fields to be accessible. Calling instance methods is technically more expensive than calling static methods.
public class DbConstants {
companion object {
val TABLE_USER_ATTRIBUTE_EMPID = "_id"
val TABLE_USER_ATTRIBUTE_DATA = "data"
}
Instead define the constants in object
.
Recommended practice :
object DbConstants {
const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
const val TABLE_USER_ATTRIBUTE_DATA = "data"
}
and access them globally like this:
DbConstants.TABLE_USER_ATTRIBUTE_EMPID
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
I found this detailed post about how to open (attach) the MDF file in SQL Server Management Studio: http://learningsqlserver.wordpress.com/2011/02/13/how-can-i-open-mdf-and-ldf-files-in-sql-server-attach-tutorial-troublshooting/
I also have the issue of not being able to navigate to the file. The reason is most likely this:
The reason it won't "open" the folder is because the service account running the SQL Server Engine service does not have read permission on the folder in question. Assign the windows user group for that SQL Server instance the rights to read and list contents at the WINDOWS level. Then you should see the files that you want to attach inside of the folder.
One solution to this problem is described here: http://technet.microsoft.com/en-us/library/jj219062.aspx I haven't tried this myself yet. Once I do, I'll update the answer.
Hope this helps.
You can upgrade your Java 7 version to 1.7.0_131-b31
For JRE 1.7.0_131-b31 in Oracle site :
TLSv1.2 and TLSv1.1 are now enabled by default on the TLS client end-points. This is similar behavior to what already happens in JDK 8 releases.
Now has a new nuget package, try use it: https://www.nuget.org/packages/Oracle.ManagedDataAccess.EntityFramework/
Also notice a common pitfall: The non lazy operators have precedence over the lazy ones, so:
boolean a, b, c;
a || b && c; //resolves to a || (b && c)
a | b && c; //resolves to (a | b) && c
Be careful when mixing them.
I would use BeginInvoke
instead of Invoke
as often as possible, unless you are really required to wait until your control has been updated (which in your example is not the case). BeginInvoke
posts the delegate on the WinForms message queue and lets the calling code proceed immediately (in your case the for-loop in the SampleFunction
). Invoke
not only posts the delegate, but also waits until it has been completed.
So in the method AppendTextBox
from your example you would replace Invoke
with BeginInvoke
like that:
public void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.BeginInvoke(new Action<string>(AppendTextBox), new object[] {value});
return;
}
textBox1.Text += value;
}
Well and if you want to get even more fancy, there is also the SynchronizationContext
class, which lets you basically do the same as Control.Invoke/Control.BeginInvoke
, but with the advantage of not needing a WinForms control reference to be known. Here is a small tutorial on SynchronizationContext
.
I had a store procedure that call another store Procedure in "linked server".when I execute it in ssms it was ok,but when I call it in application(By Entity Framework),I got this error. This article helped me and I used this script:
EXEC sp_serveroption @server = 'LinkedServer IP or Name',@optname = 'remote proc transaction promotion', @optvalue = 'false' ;
for more detail look at this: Linked server : The partner transaction manager has disabled its support for remote/network transactions
in the video source change the type to "video/quicktime"
<video width="400" controls Autoplay=autoplay>
<source src="D:/mov1.mov" type="video/quicktime">
</video>
This may help someone I am on IE11 windows 7 and what I did In addition to install the certificate is Going to internet options ==> advance tab == > security ==> "remove the check " from warn about certificate address mismatch in addition to below - dont forget to close All IE instances and restart- after finishing :
1-Start Internet Explorer running .
2-Browse to server computer using the computer name (ignore certificate warnings)
3-Click the ”Certificate Error” text in the top of the screen and select ”View certificates”
4-In the Certificate dialog, click Install Certificate -> Next
5-Select Place all certificates in the following store -> Browse
6-Install to the trusted root Certification ..
then restart .
Hope this help someone .
If you know that you're using the same context and not detaching any entities, you can make a generic version like this:
public void InsertOrUpdate<T>(T entity, DbContext db) where T : class
{
if (db.Entry(entity).State == EntityState.Detached)
db.Set<T>().Add(entity);
// If an immediate save is needed, can be slow though
// if iterating through many entities:
db.SaveChanges();
}
db
can of course be a class field, or the method can be made static and an extension, but this is the basics.
I did manage to figure it out:
$order_meta = get_post_meta($order_id);
$email = $order_meta["_shipping_email"][0] ?: $order_meta["_billing_email"][0];
I do know know for sure if the shipping email is part of the metadata, but if so I would rather have it than the billing email - at least for my purposes.
You can use regexp to do this:
function isInt(data){
if(typeof(data)=='number'){
var patt=/^[0-9e+]+$/;
data=data+"";
data=data.match(patt);
if(data==null){return false;}
else {return true;}}
else{return false;}
}
It will return false
if data isn't an integer, true
otherwise.
Add this line to the dependencies in build.gradle:
compile 'com.mcxiaoke.volley:library:1.0.+'
Since you return to the client just String
and its content type == 'text/plain'
, there is no any chance for default converters to determine how to convert String
response to the FFSampleResponseHttp
object.
The simple way to fix it:
expected-response-type
from <int-http:outbound-gateway>
replyChannel1
<json-to-object-transformer>
Otherwise you should write your own HttpMessageConverter
to convert the String to the appropriate object.
To make it work with MappingJackson2HttpMessageConverter
(one of default converters) and your expected-response-type
, you should send your reply with content type = 'application/json'
.
If there is a need, just add <header-enricher>
after your <service-activator>
and before sending a reply to the <int-http:inbound-gateway>
.
So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.
UPDATE
OK. Since you changed your server to return FfSampleResponseHttp
object as HTTP response, not String, just add contentType = 'application/json'
header before sending the response for the HTTP and MappingJackson2HttpMessageConverter
will do the stuff for you - your object will be converted to JSON and with correct contentType
header.
From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp"
and MappingJackson2HttpMessageConverter
should do the stuff for you again.
Of course you should remove <json-to-object-transformer>
from you message flow after <int-http:outbound-gateway>
.
I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Jackson are much more convenient to use. So:
So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps. (and at least Jackson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)
EDIT 19-MAR-2014:
Another new contender is Jackson jr library: it uses same fast Streaming parser/generator as Jackson (jackson-core
), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well.
So it just might be good choice, especially for smaller apps.
An interesting point that has been hinted, but not explained, is that extend is faster than append. For any loop that has append inside should be considered to be replaced by list.extend(processed_elements).
Bear in mind that apprending new elements might result in the realloaction of the whole list to a better location in memory. If this is done several times because we are appending 1 element at a time, overall performance suffers. In this sense, list.extend is analogous to "".join(stringlist).
Update: Handling this in CSS is wonderfully simple and low overhead, but you have no control over where breaks occur when they do. That's fine if you don't care, or your data has long alphanumeric runs without any natural breaks. We had lots of long file paths, URLs, and phone numbers, all of which have places it's significantly better to break at than others.
Our solution was to first use a regex replacement to put a zero-width space (​) after every 15 (say) characters that aren't whitespace or one of the special characters where we'd prefer breaks. We then do another replacement to put a zero-width space after those special characters.
Zero-width spaces are nice, because they aren't ever visible on screen; shy hyphens were confusing when they showed, because the data has significant hyphens. Zero-width spaces also aren't included when you copy text out of the browser.
The special break characters we're currently using are period, forward slash, backslash, comma, underscore, @, |, and hyphen. You wouldn't think you'd need do anything to encourage breaking after hyphens, but Firefox (3.6 and 4 at least) doesn't break by itself at hyphens surrounded by numbers (like phone numbers).
We also wanted to control the number of characters between artificial breaks, based on the layout space available. That meant that the regex to match long non-breaking runs needed to be dynamic. This gets called a lot, and we didn't want to be creating the same identical regexes over and over for performance reasons, so we used a simple regex cache, keyed by the regex expression and its flags.
Here's the code; you'd probably namespace the functions in a utility package:
makeWrappable = function(str, position)
{
if (!str)
return '';
position = position || 15; // default to breaking after 15 chars
// matches every requested number of chars that's not whitespace or one of the special chars defined below
var longRunsRegex = cachedRegex('([^\\s\\.\/\\,_@\\|-]{' + position + '})(?=[^\\s\\.\/\\,_@\\|-])', 'g');
return str
.replace(longRunsRegex, '$1​') // put a zero-width space every requested number of chars that's not whitespace or a special char
.replace(makeWrappable.SPECIAL_CHARS_REGEX, '$1​'); // and one after special chars we want to allow breaking after
};
makeWrappable.SPECIAL_CHARS_REGEX = /([\.\/\\,_@\|-])/g; // period, forward slash, backslash, comma, underscore, @, |, hyphen
cachedRegex = function(reString, reFlags)
{
var key = reString + (reFlags ? ':::' + reFlags : '');
if (!cachedRegex.cache[key])
cachedRegex.cache[key] = new RegExp(reString, reFlags);
return cachedRegex.cache[key];
};
cachedRegex.cache = {};
Test like this:
makeWrappable('12345678901234567890 12345678901234567890 1234567890/1234567890')
Update 2: It appears that zero-width spaces in fact are included in copied text in at least some circumstances, you just can't see them. Obviously, encouraging people to copy text with hidden characters in it is an invitation to have data like that entered into other programs or systems, even your own, where it may cause problems. For instance, if it ends up in a database, searches against it may fail, and search strings like this are likely to fail too. Using arrow keys to move through data like this requires (rightly) an extra keypress to move across the character you can't see, somewhat bizarre for users if they notice.
In a closed system, you can filter that character out on input to protect yourself, but that doesn't help other programs and systems.
All told, this technique works well, but I'm not certain what the best choice of break-causing character would be.
Update 3: Having this character end up in data is no longer a theoretical possibility, it's an observed problem. Users submit data copied off the screen, it gets saved in the db, searches break, things sort weirdly etc..
We did two things:
This works well, as does the technique itself, but it's a cautionary tale.
Update 4: We're using this in a context where the data fed to this may be HTML escaped. Under the right circumstances, it can insert zero-width spaces in the middle of HTML entities, with funky results.
Fix was to add ampersand to the list of characters we don't break on, like this:
var longRunsRegex = cachedRegex('([^&\\s\\.\/\\,_@\\|-]{' + position + '})(?=[^&\\s\\.\/\\,_@\\|-])', 'g');
This seems to be the safest version.
tr '[\n]' '[\0]' < a.txt | xargs -r0 /bin/bash -c 'command1 "$@"; command2 "$@";' ''
(-0
can be removed and the tr
replaced with a redirect (or the file can be replaced with a null separated file instead). It is mainly in there since I mainly use xargs
with find
with -print0
output) (This might also be relevant on xargs
versions without the -0
extension)
It is safe, since args will pass the parameters to the shell as an array when executing it. The shell (at least bash
) would then pass them as an unaltered array to the other processes when all are obtained using ["$@"][1]
If you use ...| xargs -r0 -I{} bash -c 'f="{}"; command "$f";' ''
, the assignment will fail if the string contains double quotes. This is true for every variant using -i
or -I
. (Due to it being replaced into a string, you can always inject commands by inserting unexpected characters (like quotes, backticks or dollar signs) into the input data)
If the commands can only take one parameter at a time:
tr '[\n]' '[\0]' < a.txt | xargs -r0 -n1 /bin/bash -c 'command1 "$@"; command2 "$@";' ''
Or with somewhat less processes:
tr '[\n]' '[\0]' < a.txt | xargs -r0 /bin/bash -c 'for f in "$@"; do command1 "$f"; command2 "$f"; done;' ''
If you have GNU xargs
or another with the -P
extension and you want to run 32 processes in parallel, each with not more than 10 parameters for each command:
tr '[\n]' '[\0]' < a.txt | xargs -r0 -n10 -P32 /bin/bash -c 'command1 "$@"; command2 "$@";' ''
This should be robust against any special characters in the input. (If the input is null separated.) The tr
version will get some invalid input if some of the lines contain newlines, but that is unavoidable with a newline separated file.
The blank first parameter for bash -c
is due to this: (From the bash
man page) (Thanks @clacke)
-c If the -c option is present, then commands are read from the first non-option argument com-
mand_string. If there are arguments after the command_string, the first argument is assigned to $0
and any remaining arguments are assigned to the positional parameters. The assignment to $0 sets
the name of the shell, which is used in warning and error messages.
If using GitHub on Windows:
This is why, before you start making changes of your own, that you should create a branch for each set of changes you plan to put into a pull request. That way, once you make the pull request, you can then make another branch and continue work on some other task/feature/bugfix without affecting the previous pull request.
This flatten_nlevel function calls recursively the nested list1 to covert to one level. Try this out
def flatten_nlevel(list1, flat_list):
for sublist in list1:
if isinstance(sublist, type(list)):
flatten_nlevel(sublist, flat_list)
else:
flat_list.append(sublist)
list1 = [1,[1,[2,3,[4,6]],4],5]
items = []
flatten_nlevel(list1,items)
print(items)
output:
[1, 1, 2, 3, 4, 6, 4, 5]
<%@ Page Language="C#" %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
Response.Redirect("new.aspx");
}
</script>
The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *
, ?
, [...]
.
To get the output of a command in an array, with one line per element, there are essentially 3 ways:
With Bash=4 use mapfile
—it's the most efficient:
mapfile -t my_array < <( my_command )
Otherwise, a loop reading the output (slower, but safe):
my_array=()
while IFS= read -r line; do
my_array+=( "$line" )
done < <( my_command )
As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:
IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
Please make sure you use exactly this form, i.e., make sure you have the following:
IFS=$'\n'
on the same line as the read
statement: this will only set the environment variable IFS
for the read
statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read
to break the stream at the EOL character \n
.-r
: this is important. It tells read
to not interpret the backslashes as escape sequences.-d ''
: please note the space between the -d
option and its argument ''
. If you don't leave a space here, the ''
will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read
to stop reading at the nil byte. Some people write it as -d $'\0'
, but it is not really necessary. -d ''
is better.-a my_array
tells read
to populate the array my_array
while reading the stream.printf '\0'
statement after my_command
, so that read
returns 0
; it's actually not a big deal if you don't (you'll just get an return code 1
, which is okay if you don't use set -e
– which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf ''
, which doesn't output anything. printf '\0'
prints a null byte, needed by read
to happily stop reading there (remember the -d ''
option?).If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.
If you want to use read
, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line
variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]}
in the example I gave).
Note that mapfile
provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile
and the options -C
and -c
therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).
Now I'm going to tell you why the following method:
my_array=( $( my_command) )
is broken when there are spaces:
$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!
Then some people will then recommend using IFS=$'\n'
to fix it:
$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!
But now let's use another command, with globs:
$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?
That's because I have a file called t
in the current directory… and this filename is matched by the glob [three four]
… at this point some people would recommend using set -f
to disable globbing: but look at it: you have to change IFS
and use set -f
to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.
$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'
here we're working with the shell!
Not sure about flexbox but you can do using the position property.
set parent div
position: relative
and child element which might be an <p>
or <h1>
etc.. set position: absolute
and bottom: 0
.
Example:
index.html
<div class="parent">
<p>Child</p>
</div>
style.css
.parent {
background: gray;
width: 10%;
height: 100px;
position: relative;
}
p {
position: absolute;
bottom: 0;
}
Panda's sort_values
does the work.
If one doesn't intends to keep the same variable name, don't forget the inplace=True
(this performs the operation in-place)
df.sort_values(by=['2'], inplace=True)
One might as well assigning the change (sort) to a variable, that may have the same name as the df
as
df = df.sort_values(by=['2'])
Forgetting the steps mentioned above may lead one (as this user) to not be able to get the expected result.
Note that if one wants in descending order, one needs to pass ascending=False
, such as
df = df.sort_values(by=['2'], ascending=False)
This code works for me to get all links of the document
var links=document.getElementsByTagName('a'), hrefs = [];
for (var i = 0; i<links.length; i++)
{
hrefs.push(links[i].href);
}
In Go 1.13 and later, you can use Value.IsZero
method offered in reflect
package.
if reflect.ValueOf(v).IsZero() {
// v is zero, do something
}
Apart from basic types, it also works for Array, Chan, Func, Interface, Map, Ptr, Slice, UnsafePointer, and Struct. See this for reference.
Better answer will be
git config push.default current
upsteam
works but when you have no branch on origin
then you will need to set the upstream branch. Changing it to current
will automatically set the upsteam branch and will push the branch immediately.
<script>
jQuery(document).ready(function() {
jQuery("tr").click(function(){
alert("Click! "+ jQuery(this).find('td').html());
});
});
</script>
You can create a static inner class to encapsulate the indexer as I needed to do in example below:
static class Indexer {
int i = 0;
}
public static String getRegex() {
EnumSet<MeasureUnit> range = EnumSet.allOf(MeasureUnit.class);
StringBuilder sb = new StringBuilder();
Indexer indexer = new Indexer();
range.stream().forEach(
measureUnit -> {
sb.append(measureUnit.acronym);
if (indexer.i < range.size() - 1)
sb.append("|");
indexer.i++;
}
);
return sb.toString();
}
Quick advice:
With using JPA in standalone application (outside of JavaEE), a persistence provider needs to be specified somewhere. This can be done in two ways that I know of:
<provider>org.hibernate.ejb.HibernatePersistence</provider>
(as described in correct answere by Chris: https://stackoverflow.com/a/1285436/784594)In my case, I found out that due to maven misconfiguration, hibernate-entitymanager jar was not included as a dependency, even if it was a transient dependency of other module.
I hit the same issue,and discovered the error message gives misleading variable names. Try setting the following (singular instead of plural):
PYTHON_INCLUDE_DIR=/usr/include/python2.7
PYTHON_LIBRARY=/usr/lib/python2.7/config/libpython2.7.so
The (plural) variables you see error messages about are values that the PythonLibs sets up when it is initialised correctly.
I think with np.array()
you can only create C like though you mention the order, when you check using np.isfortran()
it says false. but with np.ndarrray()
when you specify the order it creates based on the order provided.
Like this.
.divContainer input[type="text"] {
width:150px;
}
.divContainer input[type="radio"] {
width:20px;
}
If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:
Didn't pass linting
const x = new Obj(a as b);
The linter was complaining that a
was missing properties that existed on b
. In other words, a
had some properties and methods of b
, but not all. To work around this, I followed VS Code's suggestion:
Passed linting and testing
const x = new Obj(a as unknown as b);
Note that if your code attempts to call one of the properties that exists on type b
that is not implemented on type a
, you should realize a runtime fault.
A nice option is to use tar -tvvf <filePath>
which adds a line that reports the kind of file.
Example in a valid .tar file:
> tar -tvvf filename.tar
drwxr-xr-x 0 diegoreymendez staff 0 Jul 31 12:46 ./testfolder2/
-rw-r--r-- 0 diegoreymendez staff 82 Jul 31 12:46 ./testfolder2/._.DS_Store
-rw-r--r-- 0 diegoreymendez staff 6148 Jul 31 12:46 ./testfolder2/.DS_Store
drwxr-xr-x 0 diegoreymendez staff 0 Jul 31 12:42 ./testfolder2/testfolder/
-rw-r--r-- 0 diegoreymendez staff 82 Jul 31 12:42 ./testfolder2/testfolder/._.DS_Store
-rw-r--r-- 0 diegoreymendez staff 6148 Jul 31 12:42 ./testfolder2/testfolder/.DS_Store
-rw-r--r-- 0 diegoreymendez staff 325377 Jul 5 09:50 ./testfolder2/testfolder/Scala.pages
Archive Format: POSIX ustar format, Compression: none
Corrupted .tar file:
> tar -tvvf corrupted.tar
tar: Unrecognized archive format
Archive Format: (null), Compression: none
tar: Error exit delayed from previous errors.
You can also use scipy.signal.welch to estimate the power spectral density using Welch’s method. Here is an comparison between np.fft.fft and scipy.signal.welch:
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
fs = 10e3
N = 1e5
amp = 2*np.sqrt(2)
freq = 1234.0
noise_power = 0.001 * fs / 2
time = np.arange(N) / fs
x = amp*np.sin(2*np.pi*freq*time)
x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)
# np.fft.fft
freqs = np.fft.fftfreq(time.size, 1/fs)
idx = np.argsort(freqs)
ps = np.abs(np.fft.fft(x))**2
plt.figure()
plt.plot(freqs[idx], ps[idx])
plt.title('Power spectrum (np.fft.fft)')
# signal.welch
f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum')
plt.figure()
plt.semilogy(f, np.sqrt(Pxx_spec))
plt.xlabel('frequency [Hz]')
plt.ylabel('Linear spectrum [V RMS]')
plt.title('Power spectrum (scipy.signal.welch)')
plt.show()
You shouldn't need a $watch. Just bind to resize event on window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E',
template: '<div>window size: {{width}}px</div>'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
angular.element($window).bind('resize', function(){
scope.width = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
scope.$digest();
});
}
}]);
When you initialize unsigned int a to -1;
it means that you are storing the 2's
complement of -1
into the memory of a
.
Which is nothing but 0xffffffff
or 4294967295
.
Hence when you print it using %x or %u
format specifier you get that output.
By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.
Like with unsigned int
: the range is from 0 to 4,294,967,295
and int
: the range is from -2,147,483,648 to 2,147,483,647
For more info on signedness refer this
Any decent text editor has a search&replace facility that supports regular expressions.
If however, you have reason to reinvent the wheel in Java, you can do:
Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));
This only works for Java 7 or newer. If you are stuck on an older Java, you can do:
String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);
In this case, you'll need to add error handling and close the streams after you are done with them.
IOUtils
is documented at http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html
If I'm not mistaken, the following does what was asked without the memory problems of the transpose solution and with fewer lines than @kalu 's function, keeping the first of any similarly named columns.
Cols = list(df.columns)
for i,item in enumerate(df.columns):
if item in df.columns[:i]: Cols[i] = "toDROP"
df.columns = Cols
df = df.drop("toDROP",1)
If you are trying to install a module that is listed on the central repository for PS content called PowerShell Gallery, you need to install PowerShellGet. Then the command will be available. I'm currently using PS 4.0. Installing PowerShellGet did the trick for me.
With the latest PowerShellGet module, you can:
I search a way to map a many-to-many association table with extra column(s) with hibernate in xml files configuration.
Assuming with have two table 'a' & 'c' with a many to many association with a column named 'extra'. Cause I didn't find any complete example, here is my code. Hope it will help :).
First here is the Java objects.
public class A implements Serializable{
protected int id;
// put some others fields if needed ...
private Set<AC> ac = new HashSet<AC>();
public A(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<AC> getAC() {
return ac;
}
public void setAC(Set<AC> ac) {
this.ac = ac;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 97;
int result = 1;
result = prime * result + id;
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof A))
return false;
final A other = (A) obj;
if (id != other.getId())
return false;
return true;
}
}
public class C implements Serializable{
protected int id;
// put some others fields if needed ...
public C(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 98;
int result = 1;
result = prime * result + id;
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof C))
return false;
final C other = (C) obj;
if (id != other.getId())
return false;
return true;
}
}
Now, we have to create the association table. The first step is to create an object representing a complex primary key (a.id, c.id).
public class ACId implements Serializable{
private A a;
private C c;
public ACId() {
super();
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result
+ ((c == null) ? 0 : c.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ACId other = (ACId) obj;
if (a == null) {
if (other.a != null)
return false;
} else if (!a.equals(other.a))
return false;
if (c == null) {
if (other.c != null)
return false;
} else if (!c.equals(other.c))
return false;
return true;
}
}
Now let's create the association object itself.
public class AC implements java.io.Serializable{
private ACId id = new ACId();
private String extra;
public AC(){
}
public ACId getId() {
return id;
}
public void setId(ACId id) {
this.id = id;
}
public A getA(){
return getId().getA();
}
public C getC(){
return getId().getC();
}
public void setC(C C){
getId().setC(C);
}
public void setA(A A){
getId().setA(A);
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AC that = (AC) o;
if (getId() != null ? !getId().equals(that.getId())
: that.getId() != null)
return false;
return true;
}
public int hashCode() {
return (getId() != null ? getId().hashCode() : 0);
}
}
At this point, it's time to map all our classes with hibernate xml configuration.
A.hbm.xml and C.hxml.xml (quiete the same).
<class name="A" table="a">
<id name="id" column="id_a" unsaved-value="0">
<generator class="identity">
<param name="sequence">a_id_seq</param>
</generator>
</id>
<!-- here you should map all others table columns -->
<!-- <property name="otherprop" column="otherprop" type="string" access="field" /> -->
<set name="ac" table="a_c" lazy="true" access="field" fetch="select" cascade="all">
<key>
<column name="id_a" not-null="true" />
</key>
<one-to-many class="AC" />
</set>
</class>
<class name="C" table="c">
<id name="id" column="id_c" unsaved-value="0">
<generator class="identity">
<param name="sequence">c_id_seq</param>
</generator>
</id>
</class>
And then association mapping file, a_c.hbm.xml.
<class name="AC" table="a_c">
<composite-id name="id" class="ACId">
<key-many-to-one name="a" class="A" column="id_a" />
<key-many-to-one name="c" class="C" column="id_c" />
</composite-id>
<property name="extra" type="string" column="extra" />
</class>
Here is the code sample to test.
A = ADao.get(1);
C = CDao.get(1);
if(A != null && C != null){
boolean exists = false;
// just check if it's updated or not
for(AC a : a.getAC()){
if(a.getC().equals(c)){
// update field
a.setExtra("extra updated");
exists = true;
break;
}
}
// add
if(!exists){
ACId idAC = new ACId();
idAC.setA(a);
idAC.setC(c);
AC AC = new AC();
AC.setId(idAC);
AC.setExtra("extra added");
a.getAC().add(AC);
}
ADao.save(A);
}
The definitive answer to this is from Facebook themselves. In post today at https://developers.facebook.com/bugs/335452696581712 a Facebook dev says
The ability to pass in an e-mail address into the "user" search type was
removed on July 10, 2013. This search type only returns results that match
a user's name (including alternate name).
So, alas, the simple answer is you can no longer search for users by their email address. This sucks, but that's Facebook's new rules.
public dynamic ViewBag
{
get
{
if (_viewBag == null)
{
_viewBag = new DynamicViewData(() => ViewData);
}
return _viewBag;
}
}
You're also not going to get the output you're hoping for as long as you append to listoflists only inside the if-clause.
Try something like this instead:
import copy
listoflists = []
list = []
for i in range(0,10):
list.append(i)
if len(list)>3:
list.remove(list[0])
listoflists.append((copy.copy(list), copy.copy(list[0])))
print(listoflists)
What about this?
Destructor is not called if an exception is thrown from the constructor, so I have to call it manually to destroy handles that have been created in the constructor before the exception.
class MyClass {
HANDLE h1,h2;
public:
MyClass() {
// handles have to be created first
h1=SomeAPIToCreateA();
h2=SomeAPIToCreateB();
try {
...
if(error) {
throw MyException();
}
}
catch(...) {
this->~MyClass();
throw;
}
}
~MyClass() {
SomeAPIToDestroyA(h1);
SomeAPIToDestroyB(h2);
}
};
How about this?
fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);
In this case spaces in fscanf
match multiple occurrences of any whitespace until the next token in found.
Here is my version. I may change it after I look at these examples.
$.fn.pixels = function(property){
return parseInt(this.css(property));
};
$.fn.center = function(){
var w = $($w);
return this.each(function(){
$(this).css("position","absolute");
$(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
$(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
});
};
Not only double quotes, you will be in need for single quote ('
), double quote ("
), backslash (\
) and NUL (the NULL byte).
Use fputcsv()
to write, and fgetcsv()
to read, which will take care of all.
I have seen all the answers. But everyone forgot to mention one very important point:
super() should be called or used in the first line of the constructor.
You have to put div with single quotation around it. ' '
the Div
must be in the middle of single quotation . i'm gonna clear it with one example :
<?php
echo '<div id="output">'."Identify".'<br>'.'<br>';
echo 'Welcome '."$name";
echo "<br>";
echo 'Web Mail: '."$email";
echo "<br>";
echo 'Department of '."$dep";
echo "<br>";
echo "$maj";
'</div>'
?>
hope be useful.
<Button x:Name="mybtnSave" FlowDirection="LeftToRight" HorizontalAlignment="Left" Margin="813,614,0,0" VerticalAlignment="Top" Width="223" Height="53" BorderBrush="#FF2B3830" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" TabIndex="107" Click="mybtnSave_Click" >
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF080505" Offset="1"/>
<GradientStop Color="White" Offset="0.536"/>
</LinearGradientBrush>
</Button.Background>
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
<StackPanel HorizontalAlignment="Stretch" Cursor="Hand" >
<StackPanel.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF3ED82E" Offset="0"/>
<GradientStop Color="#FF3BF728" Offset="1"/>
<GradientStop Color="#FF212720" Offset="0.52"/>
</LinearGradientBrush>
</StackPanel.Background>
<Image HorizontalAlignment="Left" Source="image/Append Or Save 3.png" Height="36" Width="203" />
<TextBlock HorizontalAlignment="Center" Width="145" Height="22" VerticalAlignment="Top" Margin="0,-31,-35,0" Text="Save Com F12" FontFamily="Tahoma" FontSize="14" Padding="0,4,0,0" Foreground="White" />
</StackPanel>
</Button>ente[![enter image description here][1]][1]r image description here
As a complement to the answer of @martin-r one should note that it is possible to use the sum/difference formula for arcus tangens.
angle = atan2(vec2.y, vec2.x) - atan2(vec1.y, vec1.x);
angle = -atan2(vec1.x * vec2.y - vec1.y * vec2.x, dot(vec1, vec2))
where dot = vec1.x * vec2.x + vec1.y * vec2.y
Java does not support output parameters. You can use a return value, or pass in an object as a parameter and modify the object.
This line:
layout = (LinearLayout) findViewById(R.id.statsviewlayout);
Looks for the "statsviewlayout" id in your current 'contentview'. Now you've set that here:
setContentView(new GraphTemperature(getApplicationContext()));
And i'm guessing that new "graphTemperature" does not set anything with that id.
It's a common mistake to think you can just find any view with findViewById. You can only find a view that is in the XML (or appointed by code and given an id).
The nullpointer will be thrown because the layout you're looking for isn't found, so
layout.addView(buyButton);
Throws that exception.
addition: Now if you want to get that view from an XML, you should use an inflater:
layout = (LinearLayout) View.inflate(this, R.layout.yourXMLYouWantToLoad, null);
assuming that you have your linearlayout in a file called "yourXMLYouWantToLoad.xml"
This is quite simple.
Assuming the data is stored in a column called A in a table called T, you can use
select A, count(A) from T group by A
My tested version
Sub PrintArray(RowPrint, ColPrint, ArrayName, WorkSheetName)
Sheets(WorkSheetName).Range(Cells(RowPrint, ColPrint), _
Cells(RowPrint + UBound(ArrayName, 2) - 1, _
ColPrint + UBound(ArrayName, 1) - 1)) = _
WorksheetFunction.Transpose(ArrayName)
End Sub
Remove the data attribute as you are not POSTING
anything to the server (Your controller does not expect any parameters).
And in your AJAX Method you can use Razor
and use @Url.Action
rather than a static string:
$.ajax({
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
From your update:
$.ajax({
type: "POST",
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.
This means that the following code is completely safe:
if(p != null && p.getAge() > 10)
Also, a || b
never evaluates b
if a
evaluates to true
.
Taking help from above answer link mentioned in the above answer sets the max value with option
yAxis: { max: 100 },
On similar line min value can be set.So if you want to set min-max value then
yAxis: {
min: 0,
max: 100
},
If you are using HighRoller php library for integration if Highchart graphs then you just need to set the option
$series->yAxis->min=0;
$series->yAxis->max=100;
Try like this way -
$(document).on( 'click', '.click-activity', function () { ... });
using System;
using System.Collections.Generic; (???????? ?????????? ?? ?? ?????
using System.Linq; ?????? PlayerScript.health =
using System.Text; 999999; ??? ?? ???? ??????)
using System.Threading.Tasks;
using UnityEngine;
namespace OneHack
{
public class One
{
public Rect RT_MainMenu = new Rect(0f, 100f, 120f, 100f); //Rect ??? ????????????????? ???? ?? x,y ? ??????, ??????.
public int ID_RTMainMenu = 1;
private bool MainMenu = true;
private void Menu_MainMenu(int id) //??????? ????
{
if (GUILayout.Button("???????? ????? ??????", new GUILayoutOption[0]))
{
if (GUILayout.Button("??????????", new GUILayoutOption[0]))
{
PlayerScript.health = 999999;//??? ??????? ?? ?????? ? ?????? ??????????????? ???????? 999999 //????? ???, ??????? ????? ??????????? ??? ??????? ?? ??? ??????
}
}
}
private void OnGUI()
{
if (this.MainMenu)
{
this.RT_MainMenu = GUILayout.Window(this.ID_RTMainMenu, this.RT_MainMenu, new GUI.WindowFunction(this.Menu_MainMenu), "MainMenu", new GUILayoutOption[0]);
}
}
private void Update() //????????? ??????????? ?????, ??? ??? ????? ????? ????????? ????? ??????????? ??????????
{
if (Input.GetKeyDown(KeyCode.Insert)) //?????? ?? ??????? ????? ??????????? ? ??????????? ????, ????? ????????? ??????
{
this.MainMenu = !this.MainMenu;
}
}
}
}
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding
attributes are evaluated (along with id
attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding
attribute returns a precreated component (i.e. non-null
) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding
attribute with the autocreated component instance as argument.
In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding
attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
3.1.5 Component Bindings
...
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException
or ConcurrentModificationException
coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState()
or restoreState()
methods and like).
binding
on a bean property is bad practiceRegardless, using binding
this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value
, and perhaps others like styleClass
, disabled
, rendered
, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.
In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent()
, new SomeComponent()
, getChildren().add()
and what not. See also How to refactor snippet of old JSP to some JSF equivalent?
Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>
, <h:dataTable>
, etc). See also How to dynamically add JSF components.
Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation>
to the backing component (i.e. the component identified by <cc:interface componentType>
. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?
binding
in local scopeHowever, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding
attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding
attribute like so binding="#{foo}"
and the component is during render response elsewhere in the same view directly as UIComponent
reference available by #{foo}
. Here are several related questions where such a solution is been used in the answer:
Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
Based on your comment, moddify this:
$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV
to:
$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV
More about selectors: https://api.jquery.com/category/selectors/
If someone is using react, following will be useful:
https://stackoverflow.com/a/62111884/1015678
const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));
Percent encoding. Replace the hash with %23
.
I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/
It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.
The Makefile looking like:
EXECUTABLE = src/Main.cpp
CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32
src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)
all: myprog
myprog: $(obj)
$(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)
.PHONY: clean
clean:
del $(obj) $(EXECUTABLE)
Thank you for all the input made so far. I just wanna add on that while one may have successfully normalized DB, updated any schema changes to their application (e.g. to dataset) or so, there is also another cause: sql CARTESIAN product (when joining tables in queries).
The existence of a cartesian query result will cause duplicate records in the primary (or key first) table of two or more tables being joined. Even if you specify a "Where" clause in the SQL, a Cartesian may still occur if JOIN with secondary table for example contains the unequal join (useful when to get data from 2 or more UNrelated tables):
FROM tbFirst INNER JOIN tbSystem ON tbFirst.reference_str <> tbSystem.systemKey_str
Solution for this: tables should be related.
Thanks. chagbert
Use global namespace or global object like Constants.
var Constants = {};
And using defineObject write function which will add all properties to that object and assign value to it.
function createConstant (prop, value) {
Object.defineProperty(Constants , prop, {
value: value,
writable: false
});
};
Remember to run "android update avd -n avd_name" after change in Android SDK path.
For everyone here seeking a crazy solution, just simply try
title="your-tooltip-here"
in any tag. I've tested into td
's and a
's and it pretty works.
A simple searchable goto for the use of commenting out code blocks when debugging.
GOTO=false
if ${GOTO}; then
echo "GOTO failed"
...
fi # End of GOTO
echo "GOTO done"
Result is-> GOTO done