More of a comment than an answer...
I'm using Lombok and I was developing a (very) skeleton API and my response DTO didn't have any fields (yet) and I got the HttpMediaTypeNotAcceptableException
error while running my integration tests.
Adding a field to the response DTO fixed the issue.
Websocket and WebRTC can be used together, Websocket as a signal channel of WebRTC, and webrtc is a video/audio/text channel, also WebRTC can be in UDP also in TURN relay, TURN relay support TCP HTTP also HTTPS. Many projects use Websocket and WebRTC together.
Its better to always encode spaces as %20, not as "+".
It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.
Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".
I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
Just add another join:
SELECT dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id,
images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.
Hungarian is bad because it takes precious characters away from variable names in exchange for what, some type information?
First of all, in a strongly typed language, the compiler will warn you if you do any truly stupid.
Second, if you believe in good modularized code and don't do too much work in any 1 function, you're variables are probable declared just above the code they are used in anyway (so you have the type right there).
Third, if you prefix every pointer with p and every class with C, your really screwing up your nice modern IDE's ability to do intellisense (you know that feature where it guesses as you type what class name your typing and as soon as it gets it right you can hit enter and it completes it for you? well, if you prefix every class with C, you always have at least 1 extra letter to type)...
When checking for a function, one must always use typeof
.
Here's the difference:
var f = Object.create(Function);
console.log(f instanceof Function); //=> true
console.log(typeof f === 'function'); //=> false
f(); // throws TypeError: f is not a function
This is why one must never use instanceof
to check for a function.
I had this issue when i set colspan
in table header. So my table was:
<thead>
<tr>
<th colspan="2">Expenses</th>
<th colspan="2">Income</th>
<th>Profit/Loss</th>
</tr>
</thead>
Then once i change it to:
<thead>
<tr>
<th>Expenses</th>
<th></th>
<th>Income</th>
<th></th>
<th>Profit/Loss</th>
</tr>
</thead>
Everything worked just fine.
Can a Python function be an argument of another function?
Yes.
def myfunc(anotherfunc, extraArgs):
anotherfunc(*extraArgs)
To be more specific ... with various arguments ...
>>> def x(a,b):
... print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
... z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>
If your file idea/workspace.xml
is added to .gitignore (or its parent folder) just add
it manually to git version control. Also you can add it using TortoiseGit. After the next push you will see, that your problem is solved.
You need to configuring JSSE System Properties, specifically point to client certificate store.
Via command line:
java -Djavax.net.ssl.trustStore=truststores/client.ts com.progress.Client
or via Java code:
import java.util.Properties;
...
Properties systemProps = System.getProperties();
systemProps.put("javax.net.ssl.keyStorePassword","passwordForKeystore");
systemProps.put("javax.net.ssl.keyStore","pathToKeystore.ks");
systemProps.put("javax.net.ssl.trustStore", "pathToTruststore.ts");
systemProps.put("javax.net.ssl.trustStorePassword","passwordForTrustStore");
System.setProperties(systemProps);
...
For more refer to details on RedHat site.
Add a spinner to the XML layout, and then add this code to the Java file:
Spinner spinner;
spinner = (Spinner) findViewById(R.id.spinner1) ;
java.util.ArrayList<String> strings = new java.util.ArrayList<>();
strings.add("Mobile") ;
strings.add("Home");
strings.add("Work");
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(AddMember.this, R.layout.support_simple_spinner_dropdown_item, strings);
spinner.setAdapter(spinnerAdapter);
This is what I got from the Spring 3.0.x Reference Manual :-
Tip
If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
As a specific consequence of this semantic difference, beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.
@Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.
Just to add my two cents. I've put myself into the same situation, while searching the minimum required privileges of a db login to run successfully the statement:
ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE
It seems that the ALTER statement completes successfully, when executed with a sysadmin login, but it requires the connections cleanup part, when executed under a login which has "only" limited permissions like:
ALTER ANY DATABASE
P.S. I've spent hours trying to figure out why the "ALTER DATABASE.." does not work when executed under a login that has dbcreator role + ALTER ANY DATABASE privileges. Here's my MSDN thread!
Several of these things did not work for me... however, this did. Might help someone else in the future. Here is the CSS:
.img-area {
display: block;
padding: 0px 0 0 0px;
text-indent: 0;
width: 100%;
background-size: 100% 95%;
background-repeat: no-repeat;
background-image: url("https://yourimage.png");
}
The class .show-grid is applying center aligned text in the example in the link.
You can always add style="text-align:center"
to your row div or some other class I would think.
You can use
if (array == null || array.Length == 0)
OR
if (!(array != null && array.Length != 0))
NOTE!!!!! To insure that c# will implement the short circuit correctly; you have to compare that the object with NULL before you go to the children compare of the object.
C# 7.0 and above
if(!(array?.Length != 0))
every minute:
* * * * * /path/to/php /var/www/html/a.php
every 24hours (every midnight):
0 0 * * * /path/to/php /var/www/html/reset.php
See this reference for how crontab works: http://adminschoice.com/crontab-quick-reference, and this handy tool to build cron jobx: http://www.htmlbasix.com/crontab.shtml
I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process
I had the same problem with Xcode. I followed steps you gave and it didn't work. I became crazy because in every forum I saw, all clues for this problem are the one you gave. I finally saw I put a space after the malloc_error_break, I suppressed it and now it works. A dumb problem but if the solution doesn't work, be sure you haven't put any space before and after the malloc_error_break.
Hope this message will help..
I have used the following code in the past and it had worked with basic authentication enabled in TomCat:
URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);
You can try the above code. The code above is for POST, and you can modify it for GET
Use anchors instead:
aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)
These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^
anchor because it's implicit in the .match()
method).
Then, check if the regex did in fact match before trying to access its results:
if aa:
ip = aa.group()
Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:
ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)
Here, the \b
word boundary anchors make sure that the digits don't exceed 3 for each segment.
You need to pass a function to setTimeout
$(window).load(function () {
window.setTimeout(function () {
window.location.href = "https://www.google.co.in";
}, 5000)
});
In python "else if" is spelled "elif".
Also, you need a colon after the elif
and the else
.
Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).
So your code should read:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
function(input('input:'))
Here is my solution:
[12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) ([01][0-9]|2[0-3]):[0-5]\d
In addition to what people wrote years ago:
main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]
printf("%llu\n", k);
Then your version of mingw does not default to c99. Add this compiler flag: -std=c99
.
The easiest is,
1. select the file(s) that are not being copied,
2. Press <F4> to get the properties window
3. Make the "Build Action" property "compile" or "content" depending on what it is.
4. Now this particular file will be included!
If your input is a child element of the label
and you have more than one labels, you can combine @Mike's trick with Flexbox
+ order
.
label.switchLabel {
display: flex;
justify-content: space-between;
width: 150px;
}
.switchLabel .left { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right { order: 3; }
/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }
/* style the switch */
:root {
--radio-size: 14px;
}
.switchLabel input.switch {
width: var(--radio-size);
height: var(--radio-size);
border-radius: 50%;
border: 1px solid #999999;
box-sizing: border-box;
outline: none;
-webkit-appearance: inherit;
-moz-appearance: inherit;
appearance: inherit;
box-shadow: calc(var(--radio-size) / 2) 0 0 0 gray, calc(var(--radio-size) / 4) 0 0 0 gray;
margin: 0 calc(5px + var(--radio-size) / 2) 0 5px;
}
.switchLabel input.switch:checked {
box-shadow: calc(-1 * var(--radio-size) / 2) 0 0 0 gray, calc(-1 * var(--radio-size) / 4) 0 0 0 gray;
margin: 0 5px 0 calc(5px + var(--radio-size) / 2);
}
_x000D_
<label class="switchLabel">
<input type="checkbox" class="switch" />
<span class="left">Left</span>
<span class="right">Right</span>
</label>
_x000D_
<label class="switchLabel">
<input type="checkbox" class="switch"/>
<span class="left">Left</span>
<span class="right">Right</span>
</label>
css
label.switchLabel {
display: flex;
justify-content: space-between;
width: 150px;
}
.switchLabel .left { order: 1; }
.switchLabel .switch { order: 2; }
.switchLabel .right { order: 3; }
/* sibling selector ~ */
.switchLabel .switch:not(:checked) ~ span.left { color: lightblue }
.switchLabel .switch:checked ~ span.right { color: lightblue }
See it on JSFiddle.
note: Sibling selector only works within the same parent. To work around this, you can make the input hidden at top-level using @Nathan Blair hack.
Are you trying to get the name of the current tag that was clicked?
If so, do this..
$("*").click(function(){
alert($(this)[0].nodeName);
});
You can't really get the "selector", the "selector" in your case is *
.
public static class XMLHelper
{
/// <summary>
/// Usage: var xmlString = XMLHelper.Serialize<MyObject>(value);
/// </summary>
/// <typeparam name="T">Ki?u d? li?u</typeparam>
/// <param name="value">giá tr?</param>
/// <param name="omitXmlDeclaration">b? qua declare</param>
/// <param name="removeEncodingDeclaration">xóa encode declare</param>
/// <returns>xml string</returns>
public static string Serialize<T>(T value, bool omitXmlDeclaration = false, bool omitEncodingDeclaration = true)
{
if (value == null)
{
return string.Empty;
}
try
{
var xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = omitXmlDeclaration, //true: remove <?xml version="1.0" encoding="utf-8"?>
Encoding = Encoding.UTF8,
NewLineChars = "", // remove \r\n
};
var xmlserializer = new XmlSerializer(typeof(T));
using (var memoryStream = new MemoryStream())
{
using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
{
xmlserializer.Serialize(xmlWriter, value);
//return stringWriter.ToString();
}
memoryStream.Position = 0;
using (var sr = new StreamReader(memoryStream))
{
var pureResult = sr.ReadToEnd();
var resultAfterOmitEncoding = ReplaceFirst(pureResult, " encoding=\"utf-8\"", "");
if (omitEncodingDeclaration)
return resultAfterOmitEncoding;
return pureResult;
}
}
}
catch (Exception ex)
{
throw new Exception("XMLSerialize error: ", ex);
}
}
private static string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
}
It's usually describes as for optional add-on software packages
source, or anything that isn't part of the base system. Only some distributions use it, others simply use /usr/local
.
In MongoDB 3.2 and newer, Mongo().getDBNames()
in the mongo
shell will output a list of database names in the server:
> Mongo().getDBNames()
[ "local", "test", "test2", "test3" ]
> show dbs
local 0.000GB
test 0.000GB
test2 0.000GB
test3 0.000GB
A forEach()
loop over the array could then call dropDatabase()
to drop all the listed databases. Optionally you can opt to skip some important databases that you don't want to drop. For example:
Mongo().getDBNames().forEach(function(x) {
// Loop through all database names
if (['admin', 'config', 'local'].indexOf(x) < 0) {
// Drop if database is not admin, config, or local
Mongo().getDB(x).dropDatabase();
}
})
Example run:
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
test2 0.000GB
test3 0.000GB
> Mongo().getDBNames().forEach(function(x) {
... if (['admin', 'config', 'local'].indexOf(x) < 0) {
... Mongo().getDB(x).dropDatabase();
... }
... })
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
Add this
node_modules/
to .gitignore
file to ignore all directories called node_modules
in current folder and any subfolders
Sometimes, while taking a pull from your git, the HEAD gets detached. You can check this by entering the command:
git branch
(HEAD detached from 8790704)
master
develop
It's better to move to your branch and take a fresh pull from your respective branch.
git checkout develop
git pull origin develop
git push origin develop
this is my solution, you can set on an item (or a group) and deselect it with another click:
private final ArrayList<Integer> seleccionados = new ArrayList<>();
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
viewHolder.san.setText(android_versions.get(i).getAndroid_version_name());
if (!seleccionados.contains(i)){
viewHolder.inside.setCardBackgroundColor(Color.LTGRAY);
}
else {
viewHolder.inside.setCardBackgroundColor(Color.BLUE);
}
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (seleccionados.contains(i)){
seleccionados.remove(seleccionados.indexOf(i));
viewHolder.inside.setCardBackgroundColor(Color.LTGRAY);
} else {
seleccionados.add(i);
viewHolder.inside.setCardBackgroundColor(Color.BLUE);
}
}
});
}
As an alternative, if you just want to install make, you can use the chocolatey package manager to install gnu make by using
choco install make -y
This deals with any path issues that you might have.
Some might prefer returning multiple values as object:
function test() {
$object = new stdClass();
$object->x = 'value 1';
$object->y = 'value 2';
return $object;
}
And call it like this:
echo test()->x;
Or:
$test = test();
echo $test->y;
Use the DataContractJsonSerializer
class: MSDN1, MSDN2.
My example: HERE.
It can also safely deserialize objects from a JSON string, unlike JavaScriptSerializer
. But personally I still prefer Json.NET.
The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.
grep '^[-d]rwx.*[0-9]$' "$@"
See: Regular Expressions and grep for POSIX-standard details.
called_from
must be null
. Add a test against that condition like
if (called_from != null && called_from.equalsIgnoreCase("add")) {
or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null
behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)
if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null
import csv
with open('file_name.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(('colum1', 'colum2', 'colum3'))
for key, value in dictionary.items():
writer.writerow([key, value[0], value[1]])
This would be the simplest way to write data to .csv file
Use the -i
option:
ssh -i mykey.pem [email protected]
As noted in this answer, this file needs to have correct permissions set. The ssh man page says:
ssh will simply ignore a private key file if it is accessible by others.
You can change the permissions with this command:
chmod go= mykey.pem
That is, set permissions for group and others equal to the empty list of permissions.
I think it will help you to understand the basic differences between Inline-Elements (e.g. span) and Block-Elements (e.g. div), in order to understand why "display: inline-block" is so useful.
Problem: inline elements (e.g. span, a, button, input etc.) take "margin" only horizontally (margin-left and margin-right) on, not vertically. Vertical spacing works only on block elements (or if "display:block" is set)
Solution: Only through "display: inline-block" will also take the vertical distance (top and bottom). Reason: Inline element Span, behaves now like a block element to the outside, but like an inline element inside
Here Code Examples:
/* Inlineelement */
div,
span {
margin: 30px;
}
span {
outline: firebrick dotted medium;
background-color: antiquewhite;
}
span.mitDisplayBlock {
background: #a2a2a2;
display: block;
width: 200px;
height: 200px;
}
span.beispielMargin {
margin: 20px;
}
span.beispielMarginDisplayInlineBlock {
display: inline-block;
}
span.beispielMarginDisplayInline {
display: inline;
}
span.beispielMarginDisplayBlock {
display: block;
}
/* Blockelement */
div {
outline: orange dotted medium;
background-color: deepskyblue;
}
.paddingDiv {
padding: 20px;
background-color: blanchedalmond;
}
.marginDivWrapper {
background-color: aliceblue;
}
.marginDiv {
margin: 20px;
background-color: blanchedalmond;
}
</style>
<style>
/* Nur für das w3school Bild */
#w3_DIV_1 {
bottom: 0px;
box-sizing: border-box;
height: 391px;
left: 0px;
position: relative;
right: 0px;
text-size-adjust: 100%;
top: 0px;
width: 913.984px;
perspective-origin: 456.984px 195.5px;
transform-origin: 456.984px 195.5px;
background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
border: 2px dashed rgb(187, 187, 187);
font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
padding: 45px;
transition: all 0.25s ease-in-out 0s;
}
/*#w3_DIV_1*/
#w3_DIV_1:before {
bottom: 349.047px;
box-sizing: border-box;
content: '"Margin"';
display: block;
height: 31px;
left: 0px;
position: absolute;
right: 0px;
text-align: center;
text-size-adjust: 100%;
top: 6.95312px;
width: 909.984px;
perspective-origin: 454.984px 15.5px;
transform-origin: 454.984px 15.5px;
font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
}
/*#w3_DIV_1:before*/
#w3_DIV_2 {
bottom: 0px;
box-sizing: border-box;
color: black;
height: 297px;
left: 0px;
position: relative;
right: 0px;
text-decoration: none solid rgb(255, 255, 255);
text-size-adjust: 100%;
top: 0px;
width: 819.984px;
column-rule-color: rgb(255, 255, 255);
perspective-origin: 409.984px 148.5px;
transform-origin: 409.984px 148.5px;
caret-color: rgb(255, 255, 255);
background: rgb(76, 175, 80) none repeat scroll 0% 0% / auto padding-box border-box;
border: 0px none rgb(255, 255, 255);
font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
outline: rgb(255, 255, 255) none 0px;
padding: 45px;
}
/*#w3_DIV_2*/
#w3_DIV_2:before {
bottom: 258.578px;
box-sizing: border-box;
content: '"Border"';
display: block;
height: 31px;
left: 0px;
position: absolute;
right: 0px;
text-align: center;
text-size-adjust: 100%;
top: 7.42188px;
width: 819.984px;
perspective-origin: 409.984px 15.5px;
transform-origin: 409.984px 15.5px;
font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
}
/*#w3_DIV_2:before*/
#w3_DIV_3 {
bottom: 0px;
box-sizing: border-box;
height: 207px;
left: 0px;
position: relative;
right: 0px;
text-size-adjust: 100%;
top: 0px;
width: 729.984px;
perspective-origin: 364.984px 103.5px;
transform-origin: 364.984px 103.5px;
background: rgb(241, 241, 241) none repeat scroll 0% 0% / auto padding-box border-box;
font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
padding: 45px;
}
/*#w3_DIV_3*/
#w3_DIV_3:before {
bottom: 168.344px;
box-sizing: border-box;
content: '"Padding"';
display: block;
height: 31px;
left: 3.64062px;
position: absolute;
right: -3.64062px;
text-align: center;
text-size-adjust: 100%;
top: 7.65625px;
width: 729.984px;
perspective-origin: 364.984px 15.5px;
transform-origin: 364.984px 15.5px;
font: normal normal 400 normal 21px / 31.5px Lato, sans-serif;
}
/*#w3_DIV_3:before*/
#w3_DIV_4 {
bottom: 0px;
box-sizing: border-box;
height: 117px;
left: 0px;
position: relative;
right: 0px;
text-size-adjust: 100%;
top: 0px;
width: 639.984px;
perspective-origin: 319.984px 58.5px;
transform-origin: 319.984px 58.5px;
background: rgb(191, 201, 101) none repeat scroll 0% 0% / auto padding-box border-box;
border: 2px dashed rgb(187, 187, 187);
font: normal normal 400 normal 15px / 22.5px Lato, sans-serif;
padding: 20px;
}
/*#w3_DIV_4*/
#w3_DIV_4:before {
box-sizing: border-box;
content: '"Content"';
display: block;
height: 73px;
text-align: center;
text-size-adjust: 100%;
width: 595.984px;
perspective-origin: 297.984px 36.5px;
transform-origin: 297.984px 36.5px;
font: normal normal 400 normal 21px / 73.5px Lato, sans-serif;
}
/*#w3_DIV_4:before*/
_x000D_
<h1> The Box model - content, padding, border, margin</h1>
<h2> Inline element - span</h2>
<span>Info: A span element can not have height and width (not without "display: block"), which means it takes the fixed inline size </span>
<span class="beispielMargin">
<b>Problem:</b> inline elements (eg span, a, button, input etc.) take "margin" only vertically (margin-left and margin-right)
on, not horizontal. Vertical spacing works only on block elements (or if display: block is set) </span>
<span class="beispielMarginDisplayInlineBlock">
<b>Solution</b> Only through
<b> "display: inline-block" </ b> will also take the vertical distance (top and bottom). Reason: Inline element Span,
behaves now like a block element to the outside, but like an inline element inside</span>
<span class="beispielMarginDisplayInline">Example: here "display: inline". See the margin with Inspector!</span>
<span class="beispielMarginDisplayBlock">Example: here "display: block". See the margin with Inspector!</span>
<span class="beispielMarginDisplayInlineBlock">Example: here "display: inline-block". See the margin with Inspector! </span>
<span class="mitDisplayBlock">Only with the "Display" -property and "block" -Value in addition, a width and height can be assigned. "span" is then like
a "div" block element. </span>
<h2>Inline-Element - Div</h2>
<div> A div automatically takes "display: block." </ div>
<div class = "paddingDiv"> Padding is for padding </ div>
<div class="marginDivWrapper">
Wrapper encapsulates the example "marginDiv" to clarify the "margin" (distance from inner element "marginDiv" to the text)
of the outer element "marginDivWrapper". Here 20px;)
<div class = "marginDiv"> margin is for the margins </ div>
And there, too, 20px;
</div>
<h2>w3school sample image </h2>
source:
<a href="https://www.w3schools.com/css/css_boxmodel.asp">CSS Box Model</a>
<div id="w3_DIV_1">
<div id="w3_DIV_2">
<div id="w3_DIV_3">
<div id="w3_DIV_4">
</div>
</div>
</div>
</div>
_x000D_
You can test this answer:
python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose
Anybody working with nullable types, Value
is required to use CompareTo
.
objListOrder.Sort((x, y) => x.YourNullableType.Value.CompareTo(y.YourNullableType.Value));
SELECT *
FROM sys.tables t
INNER JOIN sys.objects o on o.object_id = t.object_id
WHERE o.is_ms_shipped = 0;
I had a red X on a folder, but not on any of the files inside it. The only thing that fixed it was clicking and dragging some of the files from the problem folder into another folder, and then performing Maven -> Update Project
. I could then drag the files back without the red X returning.
I know this is late, but it does answer your original question.
/*Read the comments the same way that SQL runs the query
1) FROM
2) GROUP
3) SELECT
4) My final notes at the bottom
*/
SELECT
list.invoiceid
, cust.customernumber
, MAX(list.inv_amount) AS invoice_amount/* we select the max because it will be the same for each payment to that invoice (presumably invoice amounts do not vary based on payment) */
, MAX(list.inv_amount) - SUM(list.pay_amount) AS [amount_due]
FROM
Customers AS cust
INNER JOIN
Payments AS pay
ON
pay.customerid = cust.customerid
INNER JOIN ( /* generate a list of payment_ids, their amounts, and the totals of the invoices they billed to*/
SELECT
inpay.paymentid AS paymentid
, inv.invoiceid AS invoiceid
, inv.amount AS inv_amount
, pay.amount AS pay_amount
FROM
InvoicePayments AS inpay
INNER JOIN
Invoices AS inv
ON inv.invoiceid = inpay.invoiceid
INNER JOIN
Payments AS pay
ON pay.paymentid = inpay.paymentid
) AS list
ON
list.paymentid = pay.paymentid
/* so at this point my result set would look like:
-- All my customers (crossed by) every paymentid they are associated to (I'll call this A)
-- Every invoice payment and its association to: its own ammount, the total invoice ammount, its own paymentid (what I call list)
-- Filter out all records in A that do not have a paymentid matching in (list)
-- we filter the result because there may be payments that did not go towards invoices!
*/
GROUP BY
/* we want a record line for each customer and invoice ( or basically each invoice but i believe this makes more sense logically */
cust.customernumber
, list.invoiceid
/*
-- we can improve this query by only hitting the Payments table once by moving it inside of our list subquery,
-- but this is what made sense to me when I was planning.
-- Hopefully it makes it clearer how the thought process works to leave it in there
-- as several people have already pointed out, the data structure of the DB prevents us from looking at customers with invoices that have no payments towards them.
*/
That's because you created a Web Site instead of a Web Application. The cs/vb
files can only be seen in a Web Application, but in a website you can't have a separate cs/vb
file.
Edit: In the website you can add a cs file behavior like..
<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>
~/Global.asax.cs:
namespace ApplicationName
{
public partial class MyApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
}
}
}
If you should need to replace the handle with something else entirely, rather than just restyling it:
$('.slider').append('<div class="my-handle ui-slider-handle"><svg height="18" width="14"><path d="M13,9 5,1 A 10,10 0, 0, 0, 5,17z"/></svg></div>');_x000D_
_x000D_
$('.slider').slider({_x000D_
range: "min",_x000D_
value: 10_x000D_
});
_x000D_
.slider .ui-state-default {_x000D_
background: none;_x000D_
}_x000D_
.slider.ui-slider .ui-slider-handle {_x000D_
width: 14px;_x000D_
height: 18px;_x000D_
margin-left: -5px;_x000D_
top: -4px;_x000D_
border: none;_x000D_
background: none;_x000D_
}_x000D_
.slider {_x000D_
height: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.9.1/jquery-ui.min.js"></script>_x000D_
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />_x000D_
<div class="slider"></div>
_x000D_
Concurrent signal assignment:
library ieee;
use ieee.std_logic_1164.all;
entity foo is
end;
architecture behave of foo is
signal clk: std_logic := '0';
begin
CLOCK:
clk <= '1' after 0.5 ns when clk = '0' else
'0' after 0.5 ns when clk = '1';
end;
ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw
Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.
I was reciving some date from my arduino uno (0-1023 numbers). Using code from 1337holiday, jwygralak67 and some tips from other sources:
import serial
import time
ser = serial.Serial(
port='COM4',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
#this will store the line
seq = []
count = 1
while True:
for c in ser.read():
seq.append(chr(c)) #convert from ANSII
joined_seq = ''.join(str(v) for v in seq) #Make a string from array
if chr(c) == '\n':
print("Line " + str(count) + ': ' + joined_seq)
seq = []
count += 1
break
ser.close()
For Swift 2.0
//First get the nsObject by defining as an optional anyObject
let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
let version = nsObject as! String
I needed to create a drag and drop + rotation that works on desktop, mobile, tablet including windows phone. The last one made it more complicated (mspointer vs. touch events).
The solution came from The great Greensock library
It took some jumping through hoops to make the same object draggable and rotatable but it works perfectly
My solution for sprintf
if ($value =~ m/\d\..*5$/){
$format =~ /.*(\d)f$/;
if (defined $1){
my $coef = "0." . "0" x $1 . "05";
$value = $value + $coef;
}
}
$value = sprintf( "$format", $value );
What I do after defining all routes is to catch potential 404 and forward to error handler, like this:
const httpError = require('http-errors');
...
// API router
app.use('/api/', routes);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new httpError(404)
return next(err);
});
module.exports = app;
I couldn't get the other answers to work within the evaluate console in Intellij so...
groovy.json.JsonOutput.toJson(myObject)
This works quite well, but unfortunately
groovy.json.JsonOutput.prettyString(myObject)
didn't work for me.
To get it pretty printed I had to do this...
groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))
Execute the workbench.action.reloadWindow
command.
There are some ways to do so:
Open the command palette (Ctrl + Shift + P) and execute the command:
>Reload Window
Define a keybinding for the command (for example CTRL+F5) in keybindings.json
:
[
{
"key": "ctrl+f5",
"command": "workbench.action.reloadWindow",
"when": "editorTextFocus"
}
]
.innerText
doesnt work in Firefox.
.innerHTML
works in both the browsers.
You can try the following:
from haversine import haversine
haversine((45.7597, 4.8422),(48.8567, 2.3508), unit='mi')
243.71209416020253
display PDF file into WinForms
Displaying a pdf file from Winform.
displaying a pdf on a windows form?
How to display PDF or Word's DOC/DOCX inside WinForms window?
Hello every one thanks for the help below is the working code for my question
$("#TableView tr.item").each(function() {
var quantity1=$(this).find("input.name").val();
var quantity2=$(this).find("input.id").val();
});
Okay, how about a CSS answer! We use display: table
. Then each of the divs are rows, and finally we apply height of 100% to middle 'row' and voilà.
body { display: table; }
div { display: table-row; }
#content {
width:450px;
margin:0 auto;
text-align: center;
background-color: blue;
color: white;
height: 100%;
}
Try this
chdir /d D:\Work\Root
Enjoy rooting ;)
jspdf does not work with css but it can work along with html2canvas. You can use jspdf along with html2canvas.
include these two files in script on your page :
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jspdf.min.js"></script>
<script type="text/javascript">
function genPDF()
{
html2canvas(document.body,{
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img,'JPEG',20,20);
doc.save('test.pdf');
}
});
}
</script>
You need to download script files such as https://github.com/niklasvh/html2canvas/releases https://cdnjs.com/libraries/jspdf
make clickable button on page so that it will generate pdf and it will be seen same as that of original html page.
<a href="javascript:genPDF()">Download PDF</a>
It will work perfectly.
To clear the whole thing use the reset_session method in a controller.
reset_session
Here's the documentation on this method: http://api.rubyonrails.org/classes/ActionController/Base.html#M000668
Resets the session by clearing out all the objects stored within and initializing a new session object.
Good luck!
View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
$(document).on('change', ':file', function () {
var fileUpload = $(this).get(0);
var files = fileUpload.files;
var bid = 0;
if (files.length != 0) {
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
xhr: function () {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (e) {
console.log(Math.floor(e.loaded / e.total * 100) + '%');
};
return xhr;
},
contentType: false,
processData: false,
type: 'POST',
data: data,
url: '/ControllerX/' + bid,
success: function (response) {
location.href = 'xxx/Index/';
}
});
}
});
});
</Script>
Controller:
[HttpPost]
public ActionResult ControllerX(string id)
{
var files = Request.Form.Files;
...
You can use a time_t
struct and clock()
function from time.h.
Store the start time in a time_t
struct by using clock()
and check the elapsed time by comparing the difference between stored time and current time.
Any of above solutions didn't work for me but I finally found it!
You should remove under folders in C:\Users\[your user]\VirtualBox VMs
.
I hope it helps you.
Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray
with java8 Stream API.
import org.json.JSONArray;
import org.json.JSONObject;
@Test
public void access_org_JsonArray() {
//Given: array
JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
new HashMap() {{
put("a", 100);
put("b", 200);
}}
),
new JSONObject(
new HashMap() {{
put("a", 300);
put("b", 400);
}}
)));
//Then: convert to List<JSONObject>
List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.collect(Collectors.toList());
// you can access the array elements now
jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
// prints 100, 300
}
If the iteration is only one time, (no need to .collect
)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
There is a nice hack how to pipe host machine environment variables to a docker container:
env > env_file && docker run --env-file env_file image_name
Use this technique very carefully, because
env > env_file
will dump ALL host machine ENV variables toenv_file
and make them accessible in the running container.
Editing to add a high level example (non functional)
<div id='popup1-content' popup='showPopup1'>
....
....
</div>
<div id='popup2-content' popup='showPopup2'>
....
....
</div>
.directive('popup', function() {
var p = {
link : function(scope, iElement, iAttrs){
//code to wrap the div (iElement) with a abs pos div (parentDiv)
// code to add a mask layer div behind
// if the parent is already there, then skip adding it again.
//use jquery ui to make it dragable etc.
scope.watch(showPopup, function(newVal, oldVal){
if(newVal === true){
$(parentDiv).show();
}
else{
$(parentDiv).hide();
}
});
}
}
return p;
});
If you want to convert back the file formats which have been changed to UNIX Format from PC format.
(1)You need to reinstall tortoise GIT and in the "Line Ending Conversion" Section make sure that you have selected "Check out as is - Check in as is"option.
(2)and keep the remaining configurations as it is.
(3)once installation is done
(4)write all the file extensions which are converted to UNIX format into a text file (extensions.txt).
ex:*.dsp
*.dsw
(5) copy the file into your clone Run the following command in GITBASH
while read -r a;
do
find . -type f -name "$a" -exec dos2unix {} \;
done<extension.txt
For SumUp Users, if you are loading the latest SumUpSDK.xcFramework, then you need to make sure that it's set to "Embed & Sign" from the application's General tab of the Target.
i.e. to reverse the above statement (making it easier to understand):
Go to the "Project Navigator" (i.e. the first icon to show all project items etc)
Select your project from the top of the tree.
On the menu in the middle of the page (slightly to the right), select your application under "Targets"
From the top-tab, select "General"
Scroll down to "Frameworks, Libraries and Embedded Content"
Select your Lib from the list
Select "Embed & Sign" from the drop down list next to it.
Clean
Re-Build and run.
I hope this helps.
H
You can specify the -t
option (--target
) to specify the destination directory. See pip install --help
for detailed information. This is the command you need:
pip install -t path_to_your_home package-name
for example, for installing say mxnet, in my $HOME
directory, I type:
pip install -t /home/foivos/ mxnet
when you have an existing form, that should now work with jquery - ajax/post now you could:
do your own stuff
$(function() {
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
//do your own request an handle the results
$.ajax({
url: actionurl,
type: 'post',
dataType: 'application/json',
data: $("#myform").serialize(),
success: function(data) {
... do something with the data...
}
});
});
});
Please note that, in order for the serialize()
function to work in the example above, all form elements need to have their name
attribute defined.
Example of the form:
<form id="myform" method="post" action="http://example.com/do_recieve_request">
<input type="text" size="20" value="default value" name="my_input_field">
..
.
</form>
@PtF - the data is submitted using POST in this sample, so this means you can access your data via
$_POST['dataproperty1']
, where dataproperty1 is a "variable-name" in your json.
here sample syntax if you use CodeIgniter:
$pdata = $this->input->post();
$prop1 = $pdata['prop1'];
$prop1 = $pdata['prop2'];
Remove the file: C:/Sites/folder/Pids/Server.pids
Explanation In UNIX land at least we usually track the process id (pid) in a file like server.pid. I think this is doing the same thing here. That file was probably left over from a crash.
git reset --hard HEAD^
Use the above command to revert merge changes.
Use the wait
built-in:
process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait
For the above example, 4 processes process1
... process4
would be started in the background, and the shell would wait until those are completed before starting the next set.
From the GNU manual:
wait [jobspec or pid ...]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
Since Git 2.23 (August 2019) you can use restore
(more info):
git restore pathTo/MyFile
The above will restore MyFile
on HEAD
(the last commit) on the current branch.
If you want to get the changes from other commit you can go backwards on the commit history. The below command will get MyFile
two commits previous to the last one. You need now the -s
(--source
) option since now you use master~2
and not master
(the default) as you restore source:
git restore -s master~2 pathTo/MyFile
You can also get the file from other branch!
git restore -s my-feature-branch pathTo/MyFile
If you are using the new Navigation Component, is simple as
findNavController().popBackStack()
It will do all the FragmentTransaction in behind for you.
JSON data must be encoded as UTF-8, UTF-16 or UTF-32. The JSON decoder can determine the encoding by examining the first four octets of the byte stream:
00 00 00 xx UTF-32BE
00 xx 00 xx UTF-16BE
xx 00 00 00 UTF-32LE
xx 00 xx 00 UTF-16LE
xx xx xx xx UTF-8
It sounds like the server is encoding data in some illegal encoding (ISO-8859-1, windows-1252, etc.)
That's not how events work. Instead, you give them a function to be called when they happen.
$("input").change(function() {
alert("Something happened!");
});
Named exports:
Let's say you create a file called utils.js
, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:
export function add(x, y) {
return x + y
}
export function mutiply(x, y) {
return x * y
}
Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:
import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.
Or if you prefer, place the entire module's contents under a common namespace:
import * as utils from './utils.js';
...
utils.multiply(2,3)
Default exports:
If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js
, with only one function that logs out whatever argument it's called with:
export default function log(message) {
console.log(message);
}
This can now be used like this:
import log from './log.js';
...
log('test') // Would print 'test' in the console.
You don't have to call it log
when you import it, you could actually call it whatever you want:
import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.
Combined:
A module can have both a default export (max 1), and named exports (imported either one by one, or using *
with an alias). React actually has this, consider:
import React, { Component, PropTypes } from 'react';
Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your specific case, original code with tuning would look like this:
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
class UserService
{
private $userRepository;
// use custom repository over direct use of EntityManager
// see step 2
public function __constructor(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function getUser($userId)
{
return $this->userRepository->find($userId);
}
}
<?php
namespace Test\CommonBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
class UserRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(UserEntity::class);
}
public function find($userId)
{
return $this->repository->find($userId);
}
}
# app/config/services.yml
services:
_defaults:
autowire: true
Test\CommonBundle\:
resource: ../../Test/CommonBundle
Yes, a foreign key can be a primary key in the case of one to one relationship between those tables
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
In the newer versions of GWT (starting either 2.3 or 2.4, i believe), you can also add
<collapse-all-properties />
to your gwt.xml for development purposes. That will tell the GWT compiler to create a single permutation which covers all locales and browsers. Therefore, you can still test in all browsers and languages, but are still only compiling a single permutation
Filezilla is great and it can support command line arguments.
Another option is to use querySelector('.foo')
or querySelectorAll('.foo')
which have broader browser support than getElementsByClassName
.
(Window) If Pilow not work try download pil at http://www.pythonware.com/products/pil/
An attempt to easy_install
indicates a problem with their listing in the Python Package Index, which pip searches.
easy_install scipy
Searching for scipy
Reading http://pypi.python.org/simple/scipy/
Reading http://www.scipy.org
Reading http://sourceforge.net/project/showfiles.php?group_id=27747&package_id=19531
Reading http://new.scipy.org/Wiki/Download
All is not lost, however; pip
can install from Subversion (SVN), Git, Mercurial, and Bazaar repositories. SciPy uses SVN:
pip install svn+http://svn.scipy.org/svn/scipy/trunk/#egg=scipy
Update (12-2012):
pip install git+https://github.com/scipy/scipy.git
Since NumPy is a dependency, it should be installed as well.
I've got this error after changing computers. I'm using SourceTree with Bitbucket.
So I had to add the SSH key generated by SourceTree, on the new computer, in Bitbucket Settings > Security > SSH keys, while connected to my Bitbucket account on the web.
//How to Run App
bool ok = QProcess::startDetached("C:\\TTEC\\CozxyLogger\\CozxyLogger.exe");
qDebug() << "Run = " << ok;
//How to Kill App
system("taskkill /im CozxyLogger.exe /f");
qDebug() << "Close";
You can change the array type without converting like this:
a.dtype = numpy.float32
but first you have to change all the integers to something that will be interpreted as the corresponding float. A very slow way to do this would be to use python's struct
module like this:
def toi(i):
return struct.unpack('i',struct.pack('f',float(i)))[0]
...applied to each member of your array.
But perhaps a faster way would be to utilize numpy's ctypeslib tools (which I am unfamiliar with)
- edit -
Since ctypeslib doesnt seem to work, then I would proceed with the conversion with the typical numpy.astype
method, but proceed in block sizes that are within your memory limits:
a[0:10000] = a[0:10000].astype('float32').view('int32')
...then change the dtype when done.
Here is a function that accomplishes the task for any compatible dtypes (only works for dtypes with same-sized items) and handles arbitrarily-shaped arrays with user-control over block size:
import numpy
def astype_inplace(a, dtype, blocksize=10000):
oldtype = a.dtype
newtype = numpy.dtype(dtype)
assert oldtype.itemsize is newtype.itemsize
for idx in xrange(0, a.size, blocksize):
a.flat[idx:idx + blocksize] = \
a.flat[idx:idx + blocksize].astype(newtype).view(oldtype)
a.dtype = newtype
a = numpy.random.randint(100,size=100).reshape((10,10))
print a
astype_inplace(a, 'float32')
print a
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
A rect
can't contain a text
element. Instead transform a g
element with the location of text and rectangle, then append both the rectangle and the text to it:
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
http://bl.ocks.org/mbostock/7341714
Multi-line labels are also a little tricky, you might want to check out this wrap function.
There is no global callback for this, but for each activity it is onStop(). You don't need to mess with an atomic int. Just have a global int with the number of started activities, in every activity increment it in onStart() and decrement it in onStop().
public class BaseActivity extends ActionBarActivity {
public static int count = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
count = count + 1;
Log.d(TAG, "onStart" + count);
if (count == 1) {
Toast.makeText(getApplicationContext(), "online", Toast.LENGTH_SHORT).show();
}
}
protected void onStop() {
super.onStop();
count = count - 1;
if (count == 0) {
Toast.makeText(getApplicationContext(), "offline", Toast.LENGTH_SHORT).show();
}
}
}
My problem was that I had setup an @ManyToOne
relationship. Maybe if the answers above don't fix your problem you might want to check the relationship that was mentioned in the error message.
Java infers automatically the type of the elements in case
, so the labels must be unqualified.
int i;
switch(i) {
case 5: // <- integer is expected
}
MyEnum e;
switch (e) {
case VALUE_A: // <- an element of the enumeration is expected
}
For what it is worth, depending on the browser, jQuery-based AJAX calls will call your success callback with a HTTP status code of 0. We've found a status code of "0" usually means the user navigated to a different page before the AJAX call completed.
Not the same technology stack as you are using, but hopefully useful to somebody.
The standard procedures are:
Have you tried ALTER SYSTEM KILL SESSION? Get the SID and SERIAL# from V$SESSION for each session in the given schema, then do
ALTER SCHEMA KILL SESSION sid,serial#;
this is backend problem. if use sails api on backend change cors.js and add your filed here
module.exports.cors = {
allRoutes: true,
origin: '*',
credentials: true,
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
headers: 'Origin, X-Requested-With, Content-Type, Accept, Engaged-Auth-Token'
};
I just want to add to all great answers above,
that if you write a library it's a good practice to use ConfigureAwait(false)
and get better performance, as said here.
So this snippet seems to be better:
public static async Task DoWork()
{
int[] ids = new[] { 1, 2, 3, 4, 5 };
await Task.WhenAll(ids.Select(i => DoSomething(1, i))).ConfigureAwait(false);
}
A full fiddle link here.
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
Edit : Updated the code zstring_remove_chr()
according to the latest version of the library.
From a BSD licensed string processing library for C, called zString
https://github.com/fnoyanisi/zString
Function to remove a character
int zstring_search_chr(char *token,char s){
if (!token || s=='\0')
return 0;
for (;*token; token++)
if (*token == s)
return 1;
return 0;
}
char *zstring_remove_chr(char *str,const char *bad) {
char *src = str , *dst = str;
/* validate input */
if (!(str && bad))
return NULL;
while(*src)
if(zstring_search_chr(bad,*src))
src++;
else
*dst++ = *src++; /* assign first, then incement */
*dst='\0';
return str;
}
Exmaple Usage
char s[]="this is a trial string to test the function.";
char *d=" .";
printf("%s\n",zstring_remove_chr(s,d));
Example Output
thisisatrialstringtotestthefunction
I will group the options based on output. Assume the following vector for all the examples.
v <- c('z', 'a','b','a','e')
For checking presence:
%in%
> 'a' %in% v
[1] TRUE
any()
> any('a'==v)
[1] TRUE
is.element()
> is.element('a', v)
[1] TRUE
For finding first occurance:
match()
> match('a', v)
[1] 2
For finding all occurances as vector of indices:
which()
> which('a' == v)
[1] 2 4
For finding all occurances as logical vector:
==
> 'a' == v
[1] FALSE TRUE FALSE TRUE FALSE
Edit: Removing grep() and grepl() from the list for reason mentioned in comments
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
Source: http://www.christianschenk.org/blog/php-curl-allow-url-fopen/
The best way to remember if rows or columns come first would be writing a comment and mentioning it.
Java does not store a 2D Array as a table with specified rows and columns, it stores it as an array of arrays, like many other answers explain. So you can decide, if the first or second dimension is your row. You just have to read the array depending on that.
So, since I get confused by this all the time myself, I always write a comment that tells me, which dimension of the 2d Array is my row, and which is my column.
Because in Python 3, print statement
has been replaced with a print() function
, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as
print("Hello World")
But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:
from __future__ import print_function
Now your code works on both 2.x & 3.x.
Check out below examples also to get familiar with print() function.
Old: print "The answer is", 2*2
New: print("The answer is", 2*2)
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Old: print # Prints a newline
New: print() # You must call the function!
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
Old: print (x, y) # prints repr((x, y))
New: print((x, y)) # Not the same as print(x, y)!
Source: What’s New In Python 3.0?
Here are some easy way to get you up and running with the XlsxWriter module.The first step is to install the XlsxWriter module.The pip installer is the preferred method for installing Python modules from PyPI, the Python Package Index:
sudo pip install xlsxwriter
Note
Windows users can omit sudo at the start of the command.
I had the exact same problem with my instance. My problem was that I forgot to allow port 80 access to the server. Maybe that's your issue as well?
Check with your WHM and make sure that port is open for the IP address of your site,
Besides the most commonly known registry key for installed programs:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
wmic command and the add/remove programs also query another registry key:
HKEY_CLASSES_ROOT\Installer\Products
Software name shown in the list is read from the Value of a Data entry within this key called: ProductName
Removing the registry key for a certain product from both of the above locations will keep it from showing in the add/remove programs list. This is not a method to uninstall programs, it will just remove the entry from what's known to windows as installed software.
Since, by using this method you would lose the chance of using the Remove button from the add/remove list to cleanly remove the software from your system; it's recommended to export registry keys to a file before you delete them. In future, if you decided to bring that item back to the list, you would simply run the registry file you stored.
An alternative approach would be:
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))
df = df1.join(df2, ['x1','x2'])
df.show()
which outputs:
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
| 2| b|3.0|0.0|
+---+---+---+---+
With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.
Whenever the columns in the two tables have different names, (let's say in the example above, df2
has the columns y1
, y2
and y4
), you could use the following syntax:
df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])
Coarse-grained granularity does not always mean bigger components, if you go by literally meaning of the word coarse, it means harsh, or not appropriate. e.g. In software projects management, if you breakdown a small system into few components, which are equal in size, but varies in complexities and features, this could lead to a coarse-grained granularity. In reverse, for a fine-grained breakdown, you would divide the components based on their cohesiveness of the functionalities each component is providing.
Use jQuery $(document)
function...
$(document).ready(function(){
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
//d3.select('#chart svg')
//d3.select("body").append("svg")
//var svg = d3.select("#chart").append("svg:svg");
var svg = d3.select("#BarChart").append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var updateData = function(getData){
d3.selectAll('svg > g > *').remove();
d3.csv(getData, function(error, data) {
if (error) throw error;
var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });
data.forEach(function(d) {
d.ages = ageNames.map(function(name) { return {name: name, value: +d[name]}; });
});
x0.domain(data.map(function(d) { return d.State; }));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function(d) { return d3.max(d.ages, function(d) { return d.value; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "state")
.attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });
state.selectAll("rect")
.data(function(d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function(d) { return x1(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
});
}
updateData('data1.csv');
});
You can certainly use putty (puttygen.exe) to do that.
Or you can get Cygwin to use the utilities you just described.
The reason you are getting rejected is that your tag lost sync with the remote version. This is the same behaviour with branches.
sync with the tag from the remote via git pull --rebase <repo_url> +refs/tags/<TAG>
and after you sync, you need to manage conflicts.
If you have a diftool installed (ex. meld) git mergetool meld
use it to sync remote and keep your changes.
The reason you're pulling with --rebase flag is that you want to put your work on top of the remote one so you could avoid other conflicts.
Also, what I don't understand is why would you delete the dev
tag and re-create it??? Tags are used for specifying software versions or milestones. Example of git tags v0.1dev
, v0.0.1alpha
, v2.3-cr
(cr - candidate release) and so on..
Another way you can solve this is issue a git reflog
and go to the moment you pushed the dev
tag on remote. Copy the commit id and git reset --mixed <commmit_id_from_reflog>
this way you know your tag was in sync with the remote at the moment you pushed it and no conflicts will arise.
Javascript doesn't have access to the user's filesystem for security reasons. FileReader
is only for files manually selected by the user.
For Windows
, you can check the Java
home location. If it contains (x86)
it is 32-bit
otherwise 64-bit
:
public static boolean is32Bit()
{
val javaHome = System.getProperty("java.home");
return javaHome.contains("(x86)");
}
public static boolean is64Bit()
{
return !is32Bit();
}
Example paths:
C:\Program Files (x86)\Java\jdk1.8.0_181\bin\java.exe # 32-bit
C:\Program Files\Java\jdk-10.0.2\bin\java.exe # 64-bit
Windows
only solution?If you need to know which bit version you're running on, you're likely fiddling around with native code on Windows
so platform-independence is out of the window anyway.
Honestly it is as simple as Simon P Steven's answer however with that approach you don't have a solid control on whether you want the points on the edges of the triangle to be included or not.
My approach is a little different but very basic. Consider the following triangle;
In order to have the point in the triangle we have to satisfy 3 conditions
In this method you have full control to include or exclude the point on the edges individually. So you may check if a point is in the triangle including only the |AC| edge for instance.
So my solution in JavaScript would be as follows;
function isInTriangle(t,p){_x000D_
_x000D_
function isInBorder(a,b,c,p){_x000D_
var m = (a.y - b.y) / (a.x - b.x); // calculate the slope_x000D_
return Math.sign(p.y - m*p.x + m*a.x - a.y) === Math.sign(c.y - m*c.x + m*a.x - a.y);_x000D_
}_x000D_
_x000D_
function findAngle(a,b,c){ // calculate the C angle from 3 points._x000D_
var ca = Math.hypot(c.x-a.x, c.y-a.y), // ca edge length_x000D_
cb = Math.hypot(c.x-b.x, c.y-b.y), // cb edge length_x000D_
ab = Math.hypot(a.x-b.x, a.y-b.y); // ab edge length_x000D_
return Math.acos((ca*ca + cb*cb - ab*ab) / (2*ca*cb)); // return the C angle_x000D_
}_x000D_
_x000D_
var pas = t.slice(1)_x000D_
.map(tp => findAngle(p,tp,t[0])), // find the angle between (p,t[0]) with (t[1],t[0]) & (t[2],t[0])_x000D_
ta = findAngle(t[1],t[2],t[0]);_x000D_
return pas[0] < ta && pas[1] < ta && isInBorder(t[1],t[2],t[0],p);_x000D_
}_x000D_
_x000D_
var triangle = [{x:3, y:4},{x:10, y:8},{x:6, y:10}],_x000D_
point1 = {x:3, y:9},_x000D_
point2 = {x:7, y:9};_x000D_
_x000D_
console.log(isInTriangle(triangle,point1));_x000D_
console.log(isInTriangle(triangle,point2));
_x000D_
CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?
I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).
However the refused message is likely a server side problem, (usually port closed).
If you want the underline to be present while the mouse hovers over the link, then:
a:hover {text-decoration: underline; }
is sufficient, however you can also use a class-name of 'hover' if you wish, and the following would be equally applicable:
a.hover:hover {text-decoration: underline; }
Incidentally it may be worth pointing out that the class name of 'hover' doesn't really add anything to the element, as the psuedo-element of a:hover
does the same thing as that of a.hover:hover
. Unless it's just a demonstration of using a class-name.
If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding ID}"/>
</StackPanel>
That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.
If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.
BufferedReader br;
FileInputStream fin;
try {
fin = new FileInputStream(fileName);
br = new BufferedReader(new InputStreamReader(fin));
/*Path pathToFile = Paths.get(fileName);
br = Files.newBufferedReader(pathToFile,StandardCharsets.US_ASCII);*/
String line = br.readLine();
while (line != null) {
String[] attributes = line.split(",");
Movie movie = createMovie(attributes);
movies.add(movie);
line = br.readLine();
}
fin.close();
br.close();
} catch (FileNotFoundException e) {
System.out.println("Your Message");
} catch (IOException e) {
System.out.println("Your Message");
}
It works for me. Hope It will help you too.
For Kotlin and bindings the code is:
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
Try This
SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key
UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey
WHERE invckey = @tmp_key
FETCH NEXT FROM @get_invckey INTO @tmp_key
You would declare this variable outside of your loop as just a standard TSQL variable.
I should also note that this is how you would do it for any type of select into a variable, not just when dealing with cursors.
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
Another Update
Needing an answer to this question myself I looked up the node docs, seems you should not be using fs.exists, instead use fs.open and use outputted error to detect if a file does not exist:
from the docs:
fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.
In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.
If you have not set the type of a file, Git tries to determine it automatically and a file with really long lines and maybe some wide characters (e.g. Unicode) is treated as binary. With the .gitattributes file you can define how Git interpretes the file. Setting the diff attribute manually lets Git interprete the file content as text and will do an usual diff.
Just add a .gitattributes to your repository root folder and set the diff attribute to the paths or files. Here's an example:
src/Acme/DemoBundle/Resources/public/js/i18n/* diff
doc/Help/NothingToSay.yml diff
*.css diff
If you want to check if there are attributes set on a file, you can do that with the help of git check-attr
git check-attr --all -- src/my_file.txt
Another nice reference about Git attributes could be found here.
jquery will provide you with this and more ...
if($("#something").val()){ //do stuff}
It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.
jQuery(document).ready(function() {
/* finds closest element with class divright/left and
makes all checkboxs inside that div class the same as selectAll...
*/
$("#selectAll").click(function() {
$(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
});
});
OK... I can resond..
Disclaimer: I just had an 18+ hour day (again).. I'm old and forgetfull.. I can't spell.. I have a short attention span so I better respond fast.. :-)
Question:
Is it possible to change the thread principal to an user with no account on the local machine?
Answer:
Yes, you can change a thread principal even if the credentials you are using are not defined locally or are outside the "forest".
I just ran into this problem when trying to connect to an SQL server with NTLM authentication from a service. This call uses the credentials associated with the process meaning that you need either a local account or a domain account to authenticate before you can impersonate. Blah, blah...
But...
Calling LogonUser(..) with the attribute of ????_NEW_CREDENTIALS will return a security token without trying to authenticate the credentials. Kewl.. Don't have to define the account within the "forest". Once you have the token you might have to call DuplicateToken() with the option to enable impersonation resulting in a new token. Now call SetThreadToken( NULL, token ); (It might be &token?).. A call to ImpersonateLoggedonUser( token ); might be required, but I don't think so. Look it up..
Do what you need to do..
Call RevertToSelf() if you called ImpersonateLoggedonUser() then SetThreadToken( NULL, NULL ); (I think... look it up), and then CloseHandle() on the created handles..
No promises but this worked for me... This is off the top of my head (like my hair) and I can't spell!!!
A simple example of testing Tesseract OCR in C#:
public static string GetText(Bitmap imgsource)
{
var ocrtext = string.Empty;
using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
{
using (var img = PixConverter.ToPix(imgsource))
{
using (var page = engine.Process(img))
{
ocrtext = page.GetText();
}
}
}
return ocrtext;
}
Info: The tessdata folder must exist in the repository: bin\Debug\
The tools sed
or tr
will do this for you by swapping the whitespace for nothing
sed 's/ //g'
tr -d ' '
Example:
$ echo " 3918912k " | sed 's/ //g'
3918912k
Simple? Yup.
If you multiply two large prime numbers, you get a huge non-prime number with only two (large) prime factors.
Factoring that number is a non-trivial operation, and that fact is the source of a lot of Cryptographic algorithms. See one-way functions for more information.
Addendum: Just a bit more explanation. The product of the two prime numbers can be used as a public key, while the primes themselves as a private key. Any operation done to data that can only be undone by knowing one of the two factors will be non-trivial to unencrypt.
Text to speech is built into Android 1.6+. Here is a simple example of how to do it.
TextToSpeech tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);
More info: http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html
Here are instructions on how to download sample code from the Android SDK Manager:
Launch the Android SDK Manager.
a. On Windows, double-click the SDK Manager.exe file at the root of the Android SDK directory.
b. On Mac or Linux, open a terminal to the tools/ directory in the Android SDK, then execute android sdk.
Expand the list of packages for the latest Android platform.
/sdk/samples/android-version/
(i.e. \android-sdk-windows\samples\android-16\ApiDemos\src\com\example\android\apis\app\TextToSpeechActivity.java)
Be aware of that if you use nested transactions, a ROLLBACK operation rolls back all the nested transactions including the outer-most one.
This might, with usage in combination with TRY/CATCH, result in the error you described. See more here.
An Object file is the compiled file itself. There is no difference between the two.
An executable file is formed by linking the Object files.
Object file contains low level instructions which can be understood by the CPU. That is why it is also called machine code.
This low level machine code is the binary representation of the instructions which you can also write directly using assembly language and then process the assembly language code (represented in English) into machine language (represented in Hex) using an assembler.
Here's a typical high level flow for this process for code in High Level Language such as C
--> goes through pre-processor
--> to give optimized code, still in C
--> goes through compiler
--> to give assembly code
--> goes through an assembler
--> to give code in machine language which is stored in OBJECT FILES
--> goes through Linker
--> to get an executable file.
This flow can have some variations for example most compilers can directly generate the machine language code, without going through an assembler. Similarly, they can do the pre-processing for you. Still, it is nice to break up the constituents for a better understanding.
your_string = "lnfgbdgfi343456dsfidf[my data] ljfbgns47647jfbgfjbgskj"
your_string[your_string.find("[")+1 : your_string.find("]")]
courtesy: Regular expression to return text between parenthesis
var checkbox = $( "#checkbox" );
checkbox.val( checkbox[0].checked ? "true" : "false" );
This will set the value
of the checkbox to "true"
or "false"
(value property
is a string)
, depending whether it's unchecked
or checked
.
Works in jQuery >= 1.0
Dim result2 = From s In mySession.Query(Of CSucursal)()
Where (From c In mySession.Query(Of CCiudad)()
From cs In mySession.Query(Of CCiudadSucursal)()
Where cs.id_ciudad Is c
Where cs.id_sucursal Is s
Where c.id = IdCiudad
Where s.accion <> "E" AndAlso s.accion <> Nothing
Where cs.accion <> "E" AndAlso cs.accion <> Nothing
Select c.descripcion).Single() Is Nothing
Where s.accion <> "E" AndAlso s.accion <> Nothing
Select s.id, s.Descripcion
numpy's genfromtxt or loadtxt is what I use:
import numpy as np
...
wordset = np.genfromtxt(fname='words.txt')
This got me headed in the right direction and solved my problem.
I've tried in a sample project to use standard, @2x and @3x images, and the iPhone 6+ simulator uses the @3x image. So it would seem that there are @3x images to be done (if the simulator actually replicates the device's behavior).
But the strange thing is that all devices (simulators) seem to use this @3x image when it's on the project structure, iPhone 4S/iPhone 5 too.
The lack of communication from Apple on a potential @3x structure, while they ask developers to publish their iOS8 apps is quite confusing, especially when seeing those results on simulator.
**Edit from Apple's Website **: Also found this on the "What's new on iOS 8" section on Apple's developer space :
Support for a New Screen Scale The iPhone 6 Plus uses a new Retina HD display with a screen scale of 3.0. To provide the best possible experience on these devices, include new artwork designed for this screen scale. In Xcode 6, asset catalogs can include images at 1x, 2x, and 3x sizes; simply add the new image assets and iOS will choose the correct assets when running on an iPhone 6 Plus. The image loading behavior in iOS also recognizes an @3x suffix.
Still not understanding why all devices seem to load the @3x. Maybe it's because I'm using regular files and not xcassets ? Will try soon.
Edit after further testing : Ok it seems that iOS8 has a talk in this. When testing on an iOS 7.1 iPhone 5 simulator, it uses correctly the @2x image. But when launching the same on iOS 8 it uses the @3x on iPhone 5. Not sure if that's a wanted behavior or a mistake/bug in iOS8 GM or simulators in Xcode 6 though.
The way to do this in .NET Core is (at the time of writing) as follows:
public async Task<IActionResult> YourAction(YourModel model)
{
if (ModelState.IsValid)
{
return StatusCode(200);
}
return StatusCode(400);
}
The StatusCode method returns a type of StatusCodeResult which implements IActionResult and can thus be used as a return type of your action.
As a refactor, you could improve readability by using a cast of the HTTP status codes enum like:
return StatusCode((int)HttpStatusCode.OK);
Furthermore, you could also use some of the built in result types. For example:
return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON
Ref. StatusCodeResult - https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1
Here's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".
$.ajax({
url:/ControllerName/ActionName,
data: "id=" + Id + "¶m2=" + param2,
type: "GET",
success: function(data){
// code here
},
error: function(passParams){
// code here
}
});
Another alternative will be to use the data-ajax on a link.
<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>
Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.
<div id="_content"></div>
Not really a direct answer to ur question but its some info u should be aware of ;).
// offsetWidth includes width of scroll bar and clientWidth doesn't. As rule, it equals 14-18px. so:
var scrollBarWidth = element.offsetWidth - element.clientWidth;
You can use android-ripple-background
Start Effect
final RippleBackground rippleBackground=(RippleBackground)findViewById(R.id.content);
ImageView imageView=(ImageView)findViewById(R.id.centerImage);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rippleBackground.startRippleAnimation();
}
});
Stop animation:
rippleBackground.stopRippleAnimation();
For KOTLIN
val rippleBackground = findViewById(R.id.content) as RippleBackground
val imageView: ImageView = findViewById(R.id.centerImage) as ImageView
imageView.setOnClickListener(object : OnClickListener() {
fun onClick(view: View?) {
rippleBackground.startRippleAnimation()
}
})
ummm, I don't know why all this programming, I think the original problem is solved easily by specifying this default route ...
routes.MapRoute("Default", "{*id}",
new { controller = "Home"
, action = "Index"
, id = UrlParameter.Optional
}
);
Edit 2: See @flodel's answer. Much better.
Try:
# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))
Edit: or as @ CarlWitthoft suggested in the comments:
matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))
Consider the following code
int a[10];
a[0] = 0;
a[1] = 0;
a[2] = 0;
a[3] = 0;
int i = 0;
a[i++] = i++;
a[i++] = i++;
a[i++] = i++;
since i++ gets evaluated twice the output is (from vs2005 debugger)
[0] 0 int
[1] 0 int
[2] 2 int
[3] 0 int
[4] 4 int
Now consider the following code :
int a[10];
a[0] = 0;
a[1] = 0;
a[2] = 0;
a[3] = 0;
int i = 0;
a[++i] = ++i;
a[++i] = ++i;
a[++i] = ++i;
Notice that the output is the same. Now you might think that ++i and i++ are the same. They are not
[0] 0 int
[1] 0 int
[2] 2 int
[3] 0 int
[4] 4 int
Finally consider this code
int a[10];
a[0] = 0;
a[1] = 0;
a[2] = 0;
a[3] = 0;
int i = 0;
a[++i] = i++;
a[++i] = i++;
a[++i] = i++;
The output is now :
[0] 0 int
[1] 1 int
[2] 0 int
[3] 3 int
[4] 0 int
[5] 5 int
So they are not the same, mixing both result in not so intuitive behavior. I think that for loops are ok with ++, but watch out when you have multiple ++ symbols on the same line or same instruction
They serve different purposes. clear()
clears an instance of the class, removeAll()
removes all the given objects and returns the state of the operation.
If the strings are the same length, then I would go for '%x' % ()
of the built-in xor (^
).
Examples -
>>>a = '290b6e3a'
>>>b = 'd6f491c5'
>>>'%x' % (int(a,16)^int(b,16))
'ffffffff'
>>>c = 'abcd'
>>>d = '12ef'
>>>'%x' % (int(a,16)^int(b,16))
'b922'
If the strings are not the same length, truncate the longer string to the length of the shorter using a slice longer = longer[:len(shorter)]
I was looking for something like this and after some tries and falls i create my own makefile, I know that's not the "idiomatic way" but it's a begining to understand make and this works for me, maybe you could try in your project.
PROJ_NAME=mono
CPP_FILES=$(shell find . -name "*.cpp")
S_OBJ=$(patsubst %.cpp, %.o, $(CPP_FILES))
CXXFLAGS=-c \
-g \
-Wall
all: $(PROJ_NAME)
@echo Running application
@echo
@./$(PROJ_NAME)
$(PROJ_NAME): $(S_OBJ)
@echo Linking objects...
@g++ -o $@ $^
%.o: %.cpp %.h
@echo Compiling and generating object $@ ...
@g++ $< $(CXXFLAGS) -o $@
main.o: main.cpp
@echo Compiling and generating object $@ ...
@g++ $< $(CXXFLAGS)
clean:
@echo Removing secondary things
@rm -r -f objects $(S_OBJ) $(PROJ_NAME)
@echo Done!
I know that's simple and for some people my flags are wrong, but as i said this is my first Makefile to compile my project in multiple dirs and link all of then together to create my bin.
I'm accepting sugestions :D
You can use the toggle-event
(docs) method to assign 2 (or more) handlers that toggle with each click.
Example: http://jsfiddle.net/SQHQ2/1/
$("#topbar").toggle(function(){
$(this).animate({height:40},200);
},function(){
$(this).animate({height:10},200);
});
or you could create your own toggle behavior:
Example: http://jsfiddle.net/SQHQ2/
$("#topbar").click((function() {
var i = 0;
return function(){
$(this).animate({height:(++i % 2) ? 40 : 10},200);
}
})());
Easier is subjective, but maybe the switch statement would be easier? You don't have to repeat the variable, so more values can fit on the line, and a line with many comparisons is more legible than the counterpart using the if statement.
There is a NuGet package Microsoft Experimental Collections that contains a class MultiValueDictionary
which does exactly what you need.
Here is a blog post of the creator of the package that describes it further.
Here is another blog post if you're feeling curious.
Example Usage:
MultiDictionary<string, int> myDictionary = new MultiDictionary<string, int>();
myDictionary.Add("key", 1);
myDictionary.Add("key", 2);
myDictionary.Add("key", 3);
//myDictionary["key"] now contains the values 1, 2, and 3
I had to add "Current" using .NET 4.5:
HttpContext.Current.Server.ScriptTimeout = 300;
pandas.isnull()
(also pd.isna()
, in newer versions) checks for missing values in both numeric and string/object arrays. From the documentation, it checks for:
NaN in numeric arrays, None/NaN in object arrays
Quick example:
import pandas as pd
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
pd.isnull(s)
Out[9]:
0 False
1 True
2 False
dtype: bool
The idea of using numpy.nan
to represent missing values is something that pandas
introduced, which is why pandas
has the tools to deal with it.
Datetimes too (if you use pd.NaT
you won't need to specify the dtype)
In [24]: s = Series([Timestamp('20130101'),np.nan,Timestamp('20130102 9:30')],dtype='M8[ns]')
In [25]: s
Out[25]:
0 2013-01-01 00:00:00
1 NaT
2 2013-01-02 09:30:00
dtype: datetime64[ns]``
In [26]: pd.isnull(s)
Out[26]:
0 False
1 True
2 False
dtype: bool
Most of the answers are/were valid. The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.
You will get a deprecated message for similar calls.
new Date() // deprecated
The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.
The new way of doing this is using the Calendar Instance.
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()
Here too the naming convention is not perfect but this is much organised. For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.
This is more synonymous to real life
One more way to do this is using Joda time API
new DateTime().toString("yyyy-MM-dd")
or the much obvious
new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")
both will return the same result.
To implement this the way you have started, you'll need to add an AnimationListener so that you can detect the beginning and ending of an animation. When onAnimationEnd() for the fade out is called, you can set the visibility of your ImageView object to View.INVISIBLE, switch the images and start your fade in animation - you'll need another AnimationListener here too. When you receive onAnimationEnd() for your fade in animation, set the ImageView to be View.VISIBLE and that should give you the effect you're looking for.
I've implemented a similar effect before, but I used a ViewSwitcher with 2 ImageViews rather than a single ImageView. You can set the "in" and "out" animations for the ViewSwitcher with your fade in and fade out so it can manage the AnimationListener implementation. Then all you need to do is alternate between the 2 ImageViews.
Edit: To be a bit more useful, here is a quick example of how to use the ViewSwitcher. I have included the full source at https://github.com/aldryd/imageswitcher.
activity_main.xml
<ViewSwitcher
android:id="@+id/switcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inAnimation="@anim/fade_in"
android:outAnimation="@anim/fade_out" >
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/sunset" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/clouds" />
</ViewSwitcher>
MainActivity.java
// Let the ViewSwitcher do the animation listening for you
((ViewSwitcher) findViewById(R.id.switcher)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ViewSwitcher switcher = (ViewSwitcher) v;
if (switcher.getDisplayedChild() == 0) {
switcher.showNext();
} else {
switcher.showPrevious();
}
}
});
Is contextmenu
an event?
I would use onmousedown
or onclick
then grab the MouseEvent
's button property to determine which button was pressed (0 = left, 1 = middle, 2 = right).
Every call to the Iterator.next()
moves the iterator to the next element. If you want to use the current element in more than one statement or expression, you have to store it in a local variable. Or even better, why don't you simply use a for-each loop?
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
Moreover, loop over the entrySet is faster, because you don't query the map twice for each key. Also Map.Entry
implementations usually implement the toString()
method, so you don't have to print the key-value pair manually.
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry);
}
Even in base Python you can do the computation in generic form
result = sum(x**2 for x in some_vector) ** 0.5
x ** 2
is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).
Using instead x ** 0.5
to take the square root doesn't do the exact same computations as math.sqrt
as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.
I often use x ** 0.5
simply because I don't want to add math
just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.
I just experienced this issue and it was because I was trying to run a script from the wrong directory.. doh! It happens to the best of us.
Just in case this answer helps someone: as found here, you might save yourself a lot of trouble running Sysinternals Autoruns as administrator. Just go to the "Services" tab and delete your service.
It did the trick for me on a machine where I didn't have any permission to edit the registry.
Whenever possible, avoid applying functions to a column in the where clause:
SELECT *
FROM table_name
WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00')
AND timestamp < UNIX_TIMESTAMP('2010-11-01 00:00:00');
Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.
Exactly.
Projection means choosing which columns (or expressions) the query shall return.
Selection means which rows are to be returned.
if the query is
select a, b, c from foobar where x=3;
then "a, b, c" is the projection part, "where x=3" the selection part.
In my case, I needed to add the JMETER_HOME
environment variable to be available via my Ant build scripts across all projects on my Jenkins server (Linux), in a way that would not interfere with my local build environment (Windows and Mac) in the build.xml
script. Setting the environment variable via Manage Jenkins - Configure System - Global properties was the easiest and least intrusive way to accomplish this. No plug-ins are necessary.
The environment variable is then available in Ant via:
<property environment="env" />
<property name="jmeter.home" value="${env.JMETER_HOME}" />
This can be verified to works by adding:
<echo message="JMeter Home: ${jmeter.home}"/>
Which produces:
JMeter Home: ~/.jmeter
Have you installed Windows Identity Foundation and the companion WIF SDK?
I found out that the URL of the application conflicted with a module in the Sun GlassFish.
So, in the file sun-web.xml
I renamed the <context-root>/servlets-samples</context-root>.
It is now working.
Answer is already given above. Trying to differentiate between strong vs week and static vs dynamic concept.
Strongly Typed: Will not be automatically converted from one type to another
In Go or Python like strongly typed languages "2" + 8 will raise a type error, because they don't allow for "type coercion".
Weakly (loosely) Typed: Will be automatically converted to one type to another: Weakly typed languages like JavaScript or Perl won't throw an error and in this case JavaScript will results '28' and perl will result 10.
Perl Example:
my $a = "2" + 8;
print $a,"\n";
Save it to main.pl and run perl main.pl
and you will get output 10.
In programming, programmer define static typing and dynamic typing with respect to the point at which the variable types are checked. Static typed languages are those in which type checking is done at compile-time, whereas dynamic typed languages are those in which type checking is done at run-time.
What is this means?
In Go it checks typed before run-time (static check). This mean it not only translates and type-checks code it’s executing, but it will scan through all the code and type error would be thrown before the code is even run. For example,
package main
import "fmt"
func foo(a int) {
if (a > 0) {
fmt.Println("I am feeling lucky (maybe).")
} else {
fmt.Println("2" + 8)
}
}
func main() {
foo(2)
}
Save this file in main.go and run it, you will get compilation failed message for this.
go run main.go
# command-line-arguments
./main.go:9:25: cannot convert "2" (type untyped string) to type int
./main.go:9:25: invalid operation: "2" + 8 (mismatched types string and int)
But this case is not valid for Python. For example following block of code will execute for first foo(2) call and will fail for second foo(0) call. It's because Python is dynamically typed, it only translates and type-checks code it’s executing on. The else block never executes for foo(2), so "2" + 8 is never even looked at and for foo(0) call it will try to execute that block and failed.
def foo(a):
if a > 0:
print 'I am feeling lucky.'
else:
print "2" + 8
foo(2)
foo(0)
You will see following output
python main.py
I am feeling lucky.
Traceback (most recent call last):
File "pyth.py", line 7, in <module>
foo(0)
File "pyth.py", line 5, in foo
print "2" + 8
TypeError: cannot concatenate 'str' and 'int' objects
Why does no one mention multiple statements in one query?
In php, you use multi_query
method of mysqli instance.
From the php manual
MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.
Here is the result comparing to other 3 methods in update 30,000 raw. Code can be found here which is based on answer from @Dakusan
Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354
As you can see, multiple statements query is more efficient than the highest answer.
If you get error message like this:
PHP Warning: Error while sending SET_OPTION packet
You may need to increase the max_allowed_packet
in mysql config file which in my machine is /etc/mysql/my.cnf
and then restart mysqld.
The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.
You want HttpRuntime.AppDomainAppPath
.
If you're in an HTTP request, you can also call Server.MapPath("~/Whatever")
.
Very simple using printf
[jaypal:~/Temp] printf "%05d\n" 1
00001
[jaypal:~/Temp] printf "%05d\n" 2
00002
For me this happened within a class function.
In PHP 5.3 and above $this::$defaults
worked fine; when I swapped the code into a server that for whatever reason had a lower version number it threw this error.
The solution, in my case, was to use the keyword self
instead of $this
:
self::$defaults
works just fine.
You can keep your images as strings and use WKWebView to display them:
let webView: WKWebView = {
let mySVGImage = "<svg height=\"190\"><polygon points=\"100,10 40,180 190,60 10,60 160,180\" style=\"fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;\"></svg>"
let preferences = WKPreferences()
preferences.javaScriptEnabled = false
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
let wv = WKWebView(frame: .zero, configuration: configuration)
wv.scrollView.isScrollEnabled = false
wv.loadHTMLString(mySVGImage, baseURL: nil)
return wv
}()
Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.
OpenJDK and Oracle JDK are implementations of the same Java specification passed the TCK (Java Technology Certification Kit).
Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace licensed proprietary parts / replace with more high-performance items that only work on specific OS] components without breaking the TCK compatibility.
Many vendors implemented the Java specification and got TCK passed. For example, IBM J9, Azul Zulu, Azul Zing, and Oracle JDK.
Almost every existing JDK is derived from OpenJDK.
As suggested by many, licensing is a change between JDKs.
Starting with JDK 11 accessing the long time support Oracle JDK/Java SE will now require a commercial license. You should now pay attention to which JDK you're installing as Oracle JDK without subscription could stop working. source
abs()
:
Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float.
Also it works on complex variable also i.e. abs(a+bj)
also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)
math.fabs()
:
It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).
The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:
scp [email protected]:/somedir/table /home/me/Desktop/.
The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.
First, all collections in .NET implement IEnumerable.
Second, a lot of the collections are duplicates because generics were added in version 2.0 of the framework.
So, although the generic collections likely add features, for the most part:
Arrays are a fixed size collection that you can change the value stored at a given index.
SortedDictionary is an IDictionary that is sorted based on the keys. SortedList is an IDictionary that is sorted based on a required IComparer.
So, the IDictionary implementations (those supporting KeyValuePairs) are: * Hashtable * Dictionary * SortedList * SortedDictionary
Another collection that was added in .NET 3.5 is the Hashset. It is a collection that supports set operations.
Also, the LinkedList is a standard linked-list implementation (the List is an array-list for faster retrieval).
You could start converting this java snippet to C the author states he has converted it from C based on the book numerical recipies which you find online! here
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=Vacation2010
SET new=December
for /f "tokens=*" %%f in ('dir /b *.jpg') do (
SET newname=%%f
SET newname=!newname:%old%=%new%!
move "%%f" "!newname!"
)
What this does is it loops over all .jpg files in the folder where the batch file is located and replaces the Vacation2010 with December inside the filenames.
Combine Kim's answer with os:
p=Path(os.getcwd())
os.chdir(p.parent)
As Paul mentioned, import works in pgAdmin:
right click on table -> import
select local file, format and coding
here is a german pgAdmin GUI screenshot:
similar thing you can do with DbVisualizer (I have a license, not sure about free version)
right click on a table -> Import Table Data...
File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
counter[row[11]]+=1
TypeError: unhashable type: 'list'
row[11]
is unhashable. It's a list. That is precisely (and only) what the error message means. You might not like it, but that is the error message.
Do this
counter[tuple(row[11])]+=1
Also, simplify.
d= [ row for row in c if counter[tuple(row[11])]>=sample_cutoff ]
The real question is: whether to use interfaces or base classes. This has been covered before.
In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.
Table names and column names can be specified as part of the mapping of DbContext
. Then there is no need to do it in migrations.
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Restaurant>()
.HasMany(p => p.Cuisines)
.WithMany(r => r.Restaurants)
.Map(mc =>
{
mc.MapLeftKey("RestaurantId");
mc.MapRightKey("CuisineId");
mc.ToTable("RestaurantCuisines");
});
}
}
class App():
def __init__(self):
self.root = Tkinter.Tk()
button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = App()
One liner, attach one or many new cascading rule(s) to the document.
This example attach a cursor:pointer
to every button
, input
, select
.
document.body.appendChild(Object.assign(document.createElement("style"), {textContent: "select, button, input {cursor:pointer}"
If you need fixed size types, use types like uint32_t (unsigned integer 32 bits) defined in stdint.h. They are specified in C99.
Here raw_input
is string
, so if you wanted to check, if var>3
then you should convert next to double, ie float(next)
and do as you would do if float(next)>3
:, but in most cases
All of the previous answers have one or more problems. The accepted answer allows ip numbers like 999.999.999.999. The currently second most upvoted answer requires prefixing with 0 such as 127.000.000.001 or 008.008.008.008 instead of 127.0.0.1 or 8.8.8.8. Apama has it almost right, but that expression requires that the ipnumber is the only thing on the line, no leading or trailing space allowed, nor can it select ip's from the middle of a line.
I think the correct regex can be found on http://www.regextester.com/22
So if you want to extract all ip-adresses from a file use:
grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" file.txt
If you don't want duplicates use:
grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" file.txt | sort | uniq
Please comment if there still are problems in this regex. It easy to find many wrong regex for this problem, I hope this one has no real issues.
Not 100% certain that you have the same problem, but I found out the hard way that my job blocks each mirror site option that was offered and I was getting errors like this:
Installing package into ‘/usr/lib64/R/library’
(as ‘lib’ is unspecified)
--- Please select a CRAN mirror for use in this session ---
Error in download.file(url, destfile = f, quiet = TRUE) :
unsupported URL scheme
Warning: unable to access index for repository https://rweb.crmda.ku.edu/cran/src/contrib
Warning message:
package ‘ggplot2’ is not available (for R version 3.2.2)
Workaround (I am using CentOS)...
install.packages('package_name', dependencies=TRUE, repos='http://cran.rstudio.com/')
I hope this saves someone hours of frustration.
There is a quite interesting way to execute script minimized by making him restart itself minimised. Here is the code to put in the beginning of your script:
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit
... script logic here ...
exit
When the script is being executed IS_MINIMIZED
is not defined (if not DEFINED IS_MINIMIZED
) so:
set IS_MINIMIZED=1
.Script starts a copy of itself using start command && start "" /min "%~dpnx0" %*
where:
""
- empty title for the window./min
- switch to run minimized."%~dpnx0"
- full path to your script.%*
- passing through all your script's parameters.Then initial script finishes its work: && exit
.
For the started copy of the script variable IS_MINIMIZED
is set by the original script so it just skips the execution of the first line and goes directly to the script logic.
exit
, otherwise the cmd window wouldn't be closed after the script execution.If your script doesn't accept arguments you could use argument as a flag instead of variable:
if "%1" == "" start "" /min "%~dpnx0" MY_FLAG && exit
or shorter
if "%1" == "" start "" /min "%~f0" MY_FLAG && exit
Turns out all I needed to do was wrap the left-hand side of the expression in soft brackets:
<span class="gallery-date">{{(gallery.date | date:'mediumDate') || "Various"}}</span>