I found I needed to do something similar today. The algorithm knew when it was creating a new list that needed to added to the set, but not when it would have finished operating on the list.
Anyway, the behaviour I wanted was for set to use id
rather than hash
. As such I found mydict[id(mylist)] = mylist
instead of myset.add(mylist)
to offer the behaviour I wanted.
A few differences:
print
vs println
:
The print
function prints messages in the Xcode console when debugging apps.
The println
is a variation of this that was removed in Swift 2 and is not used any more. If you see old code that is using println
, you can now safely replace it with print
.
Back in Swift 1.x, print
did not add newline characters at the end of the printed string, whereas println
did. But nowadays, print
always adds the newline character at the end of the string, and if you don't want it to do that, supply a terminator
parameter of ""
.
NSLog
:
NSLog
adds a timestamp and identifier to the output, whereas print
will not;
NSLog
statements appear in both the device’s console and debugger’s console whereas print
only appears in the debugger console.
NSLog
in iOS 10-13/macOS 10.12-10.x uses printf
-style format strings, e.g.
NSLog("%0.4f", CGFloat.pi)
that will produce:
2017-06-09 11:57:55.642328-0700 MyApp[28937:1751492] 3.1416
NSLog
from iOS 14/macOS 11 can use string interpolation. (Then, again, in iOS 14 and macOS 11, we would generally favor Logger
over NSLog
. See next point.)
Nowadays, while NSLog
still works, we would generally use “unified logging” (see below) rather than NSLog
.
Effective iOS 14/macOS 11, we have Logger
interface to the “unified logging” system. For an introduction to Logger
, see WWDC 2020 Explore logging in Swift.
To use Logger
, you must import os
:
import os
Like NSLog
, unified logging will output messages to both the Xcode debugging console and the device console, too
Create a Logger
and log
a message to it:
let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "network")
logger.log("url = \(url)")
When you observe the app via the external Console app, you can filter on the basis of the subsystem
and category
. It is very useful to differentiate your debugging messages from (a) those generated by other subsystems on behalf of your app, or (b) messages from other categories or types.
You can specify different types of logging messages, either .info
, .debug
, .error
, .fault
, .critical
, .notice
, .trace
, etc.:
logger.error("web service did not respond \(error.localizedDescription)")
So, if using the external Console app, you can choose to only see messages of certain categories (e.g. only show debugging messages if you choose “Include Debug Messages” on the Console “Action” menu). These settings also dictate many subtle issues details about whether things are logged to disk or not. See WWDC video for more details.
By default, non-numeric data is redacted in the logs. In the example where you logged the URL, if the app were invoked from the device itself and you were watching from your macOS Console app, you would see the following in the macOS Console:
url = <private>
If you are confident that this message will not include user confidential data and you wanted to see the strings in your macOS console, you would have to do:
os_log("url = \(url, privacy: .public)")
Prior to iOS 14/macOS 11, iOS 10/macOS 10.12 introduced os_log
for “unified logging”. For an introduction to unified logging in general, see WWDC 2016 video Unified Logging and Activity Tracing.
Import os.log
:
import os.log
You should define the subsystem
and category
:
let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "network")
When using os_log
, you would use a printf-style pattern rather than string interpolation:
os_log("url = %@", log: log, url.absoluteString)
You can specify different types of logging messages, either .info
, .debug
, .error
, .fault
(or .default
):
os_log("web service did not respond", type: .error)
You cannot use string interpolation when using os_log
. For example with print
and Logger
you do:
logger.log("url = \(url)")
But with os_log
, you would have to do:
os_log("url = %@", url.absoluteString)
The os_log
enforces the same data privacy, but you specify the public visibility in the printf formatter (e.g. %{public}@
rather than %@
). E.g., if you wanted to see it from an external device, you'd have to do:
os_log("url = %{public}@", url.absoluteString)
You can also use the “Points of Interest” log if you want to watch ranges of activities from Instruments:
let pointsOfInterest = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: .pointsOfInterest)
And start a range with:
os_signpost(.begin, log: pointsOfInterest, name: "Network request")
And end it with:
os_signpost(.end, log: pointsOfInterest, name: "Network request")
For more information, see https://stackoverflow.com/a/39416673/1271826.
Bottom line, print
is sufficient for simple logging with Xcode, but unified logging (whether Logger
or os_log
) achieves the same thing but offers far greater capabilities.
The power of unified logging comes into stark relief when debugging iOS apps that have to be tested outside of Xcode. For example, when testing background iOS app processes like background fetch, being connected to the Xcode debugger changes the app lifecycle. So, you frequently will want to test on a physical device, running the app from the device itself, not starting the app from Xcode’s debugger. Unified logging lets you still watch your iOS device log statements from the macOS Console app.
This may be a very late response, but just changing the POJO to this should solve the json string provided in the problem (since, the input string is not in your control as you said):
public class Wrapper {
private List<Student> wrapper;
//getters & setters here
}
if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"
The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target <script>
tags with a [src]
attribute.
/**
* Current Script Path
*
* Get the dir path to the currently executing script file
* which is always the last one in the scripts array with
* an [src] attr
*/
var currentScriptPath = function () {
var scripts = document.querySelectorAll( 'script[src]' );
var currentScript = scripts[ scripts.length - 1 ].src;
var currentScriptChunks = currentScript.split( '/' );
var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];
return currentScript.replace( currentScriptFile, '' );
}
This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.
you can convert any SVG to a component and make it reusable.
here is my answer for the easiest way you can do it
I had the same problem, so I ended up making my own.
It has a template system built in, so you can make the results look like anything you want. Works on all major browsers and accepts arrays & json objects. http://code.google.com/p/custom-combobox/
The ...For
extension methods on the HtmlHelper (e.g., DisplayFor
, TextBoxFor
, ElementFor
, etc...) take a property and nothing else. If you don't have a property, use the non-For
method (e.g., Display
, TextBox
, Element
, etc...).
The ...For
extension methods provides a way of simplifying postback by naming the control after the property. This is why it takes an expression and not simply a value. If you are not interested in this postback facilitation then do not use the ...For
methods at all.
Note: You should not be doing things like calling ToString
inside the view. This should be done inside the view model. I realize that a lot of demo projects put domain objects straight into the view. In my experience, this rarely works because it assumes that you do not want any formatting on the data in the domain entity. Best practice is to create a view model that wraps the entity into something that can be directly consumed by the view. Most of the properties in this view model should be strings that are already formatted or data for which you have element or display templates created.
I managed to fix it in Android Studio 1.3.1 by doing the following:
File -> New -> New Module
.iml
file from an existing library module and change the name of the file and rename references in the .iml
fileInstead of window
use global
it('correct url is called', () => {
global.open = jest.fn();
statementService.openStatementsReport(111);
expect(global.open).toBeCalled();
});
you could also try
const open = jest.fn()
Object.defineProperty(window, 'open', open);
I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.
I will explain it verbally first and then with an example:
A pointer object can be declared as a const pointer or a pointer to a const object (or both):
A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee").
Reference variables are thus an alternate syntax for constpointers.
A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object.
A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object.
Example:
void Foo( int * ptr,
int const * ptrToConst,
int * const constPtr,
int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the "pointee" data
ptr = 0; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the "pointee" data
ptrToConst = 0; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the "pointee" data
constPtr = 0; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the "pointee" data
constPtrToConst = 0; // Error! Cannot modify the pointer
}
Happy to help! Good Luck!
In my case: res/someLayout.xml file goes some error then i resolve it. Then Clear the project. Error is gone.
You can also try react-native-extended-stylesheet that supports percentage for single-orientation apps:
import EStyleSheet from 'react-native-extended-stylesheet';
const styles = EStyleSheet.create({
column: {
width: '80%',
height: '50%',
marginLeft: '10%'
}
});
On Ubuntu; using mkvirtualenv -p python3 env_name
loads the virtualenv with python3.
Inside the env, use python --version
to verify.
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
myfun(*some_tuple)
does exactly what you request. The *
operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.
The strcomp
function may be appropriate here (returns 0 when strings are identical):
SELECT * from table WHERE Strcmp(user, testername) <> 0;
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.
FOR /d %%K in ("n:\test*") DO (
FOR /d %%J in ("%%K*") DO (
FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"
)
)
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged
Most of the answers on this page are outdated.
Here's an updated python version to search google and get all results href's:
import urllib.parse
import re
from selenium import webdriver
driver.get("https://google.com/")
q = driver.find_element_by_name('q')
q.send_keys("always look on the bright side of life monty python")
q.submit();
sleep(1)
links= driver.find_elements_by_xpath("//h3[@class='r']//a")
for link in links:
url = urllib.parse.unquote(webElement.get_attribute("href")) # decode the url
url = re.sub("^.*?(?:url\?q=)(.*?)&sa.*", r"\1", url, 0, re.IGNORECASE) # get the clean url
Please note that the element id
/name
/class
(@class='r'
) ** will change depending on the user agent**.
The above code used PhantomJS default user agent.
This might be too little too late but what helped me is the cool sounding 'nuclear' option. Basically using the command filter-branch
you can remove files or change something over a large number of files throughout your entire git history.
It is best explained here.
If you are using 5.6 php,
sudo apt-get install php5.6-curl
JUnit 4.7 added this feature it seems using TestName-Rule. Looks like this will get you the method name:
import org.junit.Rule;
public class NameRuleTest {
@Rule public TestName name = new TestName();
@Test public void testA() {
assertEquals("testA", name.getMethodName());
}
@Test public void testB() {
assertEquals("testB", name.getMethodName());
}
}
There should only be one element with a given id. If you're stuck with that situation, see the 2nd half of my answer for options.
How a browser behaves when you have multiple elements with the same id (illegal HTML) is not defined by specification. You could test all the browsers and find out how they behave, but it's unwise to use this configuration or rely on any particular behavior.
Use classes if you want multiple objects to have the same identifier.
<div>
<span class="a">1</span>
<span class="a">2</span>
<span>3</span>
</div>
$(function() {
var w = $("div");
console.log($(".a").length); // 2
console.log($("body .a").length); // 2
console.log($(".a", w).length); // 2
});
If you want to reliably look at elements with IDs that are the same because you can't fix the document, then you will have to do your own iteration as you cannot rely on any of the built in DOM functions.
You could do so like this:
function findMultiID(id) {
var results = [];
var children = $("div").get(0).children;
for (var i = 0; i < children.length; i++) {
if (children[i].id == id) {
results.push(children[i]);
}
}
return(results);
}
Or, using jQuery:
$("div *").filter(function() {return(this.id == "a");});
jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.
As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like #a
and if so, just used document.getElementById("a")
. If the selector is more complex than that and querySelectorAll()
exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll()
does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their own querySelectorAll()
implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.
In case if you are looking for one liner
For primitives
this.items.indexOf(item) === -1) && this.items.push(item);
For objects
this.items.findIndex((item: ItemType) => item.var === checkValue) === -1 && this.items.push(item);
Here's another approach, in case you want split a string with a delimiter.
import pyspark.sql.functions as f
df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
| value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+
df_split = df.select(f.split(df.value,":")).rdd.flatMap(
lambda x: x).toDF(schema=["col1","col2","col3"])
df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
| 1| a|2001|
| 2| b|2002|
| 3| c|2003|
+----+----+----+
I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.
SELECT CREATED FROM USER_OBJECTS WHERE OBJECT_NAME='<<YOUR TABLE NAME>>'
If you do android native code development using NDK, give Visual Studio a try. (Not a typo!!!) Check out: http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html
You could use RAISE_APPLICATION_ERROR like this:
DECLARE
ex_custom EXCEPTION;
BEGIN
RAISE ex_custom;
EXCEPTION
WHEN ex_custom THEN
RAISE_APPLICATION_ERROR(-20001,'My exception was raised');
END;
/
That will raise an exception that looks like:
ORA-20001: My exception was raised
The error number can be anything between -20001 and -20999.
None of the above solutions worked for me, however instead I wrapped my content in a div (#outer-wrap) and then used the following CSS:
body {
overflow: hidden;
}
#outer-wrap {
-webkit-overflow-scrolling: touch;
height: 100vh;
overflow: auto;
}
Obviously only works in browsers that support viewport widths/heights of course.
You need to install it by launching the installer.
Click the "Workload" tab* in the upper-left, then check top right ".NET-Desktop Development" and hit install. Note it may modify your installation size (bottom-right), and you can install other Workloads, but you must install ".NET-Desktop Development" at least.
*as seen in comments below, users were not able to achieve the equivalent using the "Individual Components" tab.
Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
You'll need to unpack the file or use it directly.
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename");
to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
$output = file("http://www.example.com");
didn't work until I enabled: allow_url_fopen, allow_url_include,
and file_uploads
in php.ini
for PHP7
To generalize the good answer of Mike Nakis with String.CASE_INSENSITIVE_ORDER
, you can also use :
Collator.getInstance();
See Collator
You can replace nan
with None
in your numpy array:
>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>
Based on the docs at https://angular.io/api/platform-browser/DomSanitizer, the right way to do this seems to be to use sanitize. At least in Angular 7 (don't know if this changed from before). This worked for me:
import { Component, OnInit, Input, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
constructor(
private sanitizer: DomSanitizer
) { }
this.sanitizer.sanitize(SecurityContext.STYLE, 'url(' + this.image + ')');
Re SecurityContext, see https://angular.io/api/core/SecurityContext. Basically it's just this enum:
enum SecurityContext {
NONE: 0
HTML: 1
STYLE: 2
SCRIPT: 3
URL: 4
RESOURCE_URL: 5
}
Extended - to provide more details based on some comments
The error
Error TS2306: File 'test.ts' is not a module.
Comes from the fact described here http://exploringjs.com/es6/ch_modules.html
17. Modules
This chapter explains how the built-in modules work in ECMAScript 6.
17.1 OverviewIn ECMAScript 6, modules are stored in files. There is exactly one module per file and one file per module. You have two ways of exporting things from a module. These two ways can be mixed, but it is usually better to use them separately.
17.1.1 Multiple named exports
There can be multiple named exports:
//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } ...
17.1.2 Single default export
There can be a single default export. For example, a function:
//------ myFunc.js ------ export default function () { ··· } // no semicolon!
Based on the above we need the export
, as a part of the test.js file. Let's adjust the content of it like this:
// test.js - exporting es6
export module App {
export class SomeClass {
getName(): string {
return 'name';
}
}
export class OtherClass {
getName(): string {
return 'name';
}
}
}
And now we can import it with these thre ways:
import * as app1 from "./test";
import app2 = require("./test");
import {App} from "./test";
And we can consume imported stuff like this:
var a1: app1.App.SomeClass = new app1.App.SomeClass();
var a2: app1.App.OtherClass = new app1.App.OtherClass();
var b1: app2.App.SomeClass = new app2.App.SomeClass();
var b2: app2.App.OtherClass = new app2.App.OtherClass();
var c1: App.SomeClass = new App.SomeClass();
var c2: App.OtherClass = new App.OtherClass();
and call the method to see it in action:
console.log(a1.getName())
console.log(a2.getName())
console.log(b1.getName())
console.log(b2.getName())
console.log(c1.getName())
console.log(c2.getName())
Original part is trying to help to reduce the amount of complexity in usage of the namespace
I would really strongly suggest to check this Q & A:
Let me cite the first sentence:
Do not use "namespaces" in external modules.
Don't do this.
Seriously. Stop.
...
In this case, we just do not need module
inside of test.ts
. This could be the content of it adjusted test.ts
:
export class SomeClass
{
getName(): string
{
return 'name';
}
}
Read more here
In the previous example, when we consumed each validator, each module only exported one value. In cases like this, it's cumbersome to work with these symbols through their qualified name when a single identifier would do just as well.
The
export =
syntax specifies a single object that is exported from the module. This can be a class, interface, module, function, or enum. When imported, the exported symbol is consumed directly and is not qualified by any name.
we can later consume it like this:
import App = require('./test');
var sc: App.SomeClass = new App.SomeClass();
sc.getName();
Read more here:
In some cases, you may want to only load a module under some conditions. In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.
The compiler detects whether each module is used in the emitted JavaScript. For modules that are only used as part of the type system, no require calls are emitted. This culling of unused references is a good performance optimization, and also allows for optional loading of those modules.
The core idea of the pattern is that the import id = require('...') statement gives us access to the types exposed by the external module. The module loader is invoked (through require) dynamically, as shown in the if blocks below. This leverages the reference-culling optimization so that the module is only loaded when needed. For this pattern to work, it's important that the symbol defined via import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).
import re
pattern = re.compile("<(\d{4,5})>")
for i, line in enumerate(open('test.txt')):
for match in re.finditer(pattern, line):
print 'Found on line %s: %s' % (i+1, match.group())
A couple of notes about the regex:
?
at the end and the outer (...)
if you don't want to match the number with the angle brackets, but only want the number itselfUpdate: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.
More about regex in python can be found here : Regular Expression HOWTO
If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P
The whole creating and dispatching events works, but since you are using the onchange
attribute, your life can be a little simpler:
http://jsfiddle.net/xwywvd1a/3/
var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();
If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.
If you want to do it typed:
class Something {
areas: Area[][];
constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[] = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}
JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:
"SELECT r FROM FooBar r"
I used ScriptManager in Code Behind and it worked fine.
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "CallMyFunction", "confirm()", true);
If you are using UpdatePanel in ASP Frontend. Then, enter UpdatePanel name and 'function name' defined with script tags.
I've resolved editing my provisioning. In fact, i've noticed that this mobile provisioning was not associated with my signing identity.
So, from the developer apple i followed this step: Select Provisioning Profiles -> Edit -> check my identity from "Certificates".
Effectively it's a strange error...
Since I can only edit my own answer, I'm going to make a composite answer from the other answers to my question. Thanks to all of you who answered.
Using std::copy, this still iterates in the background, but you don't have to type out the code.
int foo(int* data, int size)
{
static std::vector<int> my_data; //normally a class variable
std::copy(data, data + size, std::back_inserter(my_data));
return 0;
}
Using regular memcpy. This is probably best used for basic data types (i.e. int) but not for more complex arrays of structs or classes.
vector<int> x(size);
memcpy(&x[0], source, size*sizeof(int));
This should do it:
<StackPanel>
<TextBox x:Name="TheTextBox" />
<Button Content="Click Me">
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
is it possible to export without looping through all records
For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application
object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data
Option Explicit
Sub AccImport()
Dim acc As New Access.Application
acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
acc.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:="tblExcelImport", _
Filename:=Application.ActiveWorkbook.FullName, _
HasFieldNames:=True, _
Range:="Folio_Data_original$A1:B10"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
End Sub
Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, because pseudo-elements, as the name implies, are not real elements, and therefore you can't select and manipulate them directly with jQuery (or any JavaScript APIs for that matter, not even the Selectors API). This applies to any pseudo-elements whose styles you're trying to modify with a script, and not just ::before
and ::after
.
You can only access pseudo-element styles directly at runtime via the CSSOM (think window.getComputedStyle()
), which is not exposed by jQuery beyond .css()
, a method that doesn't support pseudo-elements either.
You can always find other ways around it, though, for example:
Applying the styles to the pseudo-elements of one or more arbitrary classes, then toggling between classes (see seucolega's answer for a quick example) — this is the idiomatic way as it makes use of simple selectors (which pseudo-elements are not) to distinguish between elements and element states, the way they're intended to be used
Manipulating the styles being applied to said pseudo-elements, by altering the document stylesheet, which is much more of a hack
I face the same problem and solved by adding the JAVA_HOME variable with updated version of java in my Ubuntu Machine(16.04). if you are using "Apache Maven 3.3.9" You need to upgrade your JAVA_HOME with java7 or more
Step to Do this
1-sudo vim /etc/environment
2-JAVA_HOME=JAVA Installation Directory (MyCase-/opt/dev/jdk1.7.0_45/)
3-Run echo $JAVA_HOME will give the JAVA_HOME set value
4-Now mvn -version will give the desired output
Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 1.7.0_45, vendor: Oracle Corporation
Java home: /opt/dev/jdk1.7.0_45/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-36-generic", arch: "amd64", family: "unix"
TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])
Hibernate defines five types of identifier generation strategies:
AUTO - either identity column, sequence or table depending on the underlying DB
TABLE - table holding the id
IDENTITY - identity column
SEQUENCE - sequence
identity copy – the identity is copied from another entity
Example using Table
@Id
@GeneratedValue(strategy=GenerationType.TABLE , generator="employee_generator")
@TableGenerator(name="employee_generator",
table="pk_table",
pkColumnName="name",
valueColumnName="value",
allocationSize=100)
@Column(name="employee_id")
private Long employeeId;
for more details, check the link.
Concluding from above answers, Here is the exact difference between full/strictly, complete and perfect binary trees
Full/Strictly binary tree :- Every node except the leaf nodes have two children
Complete binary tree :- Every level except the last level is completely filled and all the nodes are left justified.
Perfect binary tree :- Every node except the leaf nodes have two children and every level (last level too) is completely filled.
-- To Create or Replace a Table we must first silently Drop a Table that may not exist
DECLARE
table_not_exist EXCEPTION;
PRAGMA EXCEPTION_INIT (table_not_exist , -00942);
BEGIN
EXECUTE IMMEDIATE('DROP TABLE <SCHEMA>.<TABLE NAME> CASCADE CONSTRAINTS');
EXCEPTION WHEN table_not_exist THEN NULL;
END;
/
When you have multiple if
conditions, numpy.select
is the way to go:
In [4102]: import numpy as np
In [4098]: conditions = [df.A.eq(df.B), df.A.gt(df.B), df.A.lt(df.B)]
In [4096]: choices = [0, 1, -1]
In [4100]: df['C'] = np.select(conditions, choices)
In [4101]: df
Out[4101]:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
I had the problem we are talking about here, my scenario is eclipse-helios + tomcat + jsf and what you were doing is making a deploy a simple application to tomcat. I was showing the same problem here, solved it as follows.
In eclipse go to servers tab double click on the registered server in my case tomcat 7.0, it opens my file server General registration information. On the section "General Information" click on the link "Open launch configuration" , this opens the execution of server options in the Arguments tab in VM arguments added in the end these two entries
-XX: MaxPermSize = 512m
-XX: PermSize = 512m
and ready.
Inspite of starting a chrone job, for the task, we can use log4j2.properties file in config folder of logstash. Have a look at the link below, this will be helpful.
If you are working with TypeScript modules and are trying to add a getter that is exported, you can do something like this:
// dataStore.ts
export const myData: string = undefined; // just for typing support
let _myData: string; // for memoizing the getter results
Object.defineProperty(this, "myData", {
get: (): string => {
if (_myData === undefined) {
_myData = "my data"; // pretend this took a long time
}
return _myData;
},
});
Then, in another file you have:
import * as dataStore from "./dataStore"
console.log(dataStore.myData); // "my data"
Given that a WHERE clause did not work, maybe this will:
CREATE TRIGGER
[dbo].[SystemParameterInsertUpdate]
ON
[dbo].[SystemParameter]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
If (SELECT Attribute FROM INSERTED) LIKE 'NoHist_%'
Begin
Return
End
INSERT INTO SystemParameterHistory
(
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
)
SELECT
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
FROM Inserted AS I
END
I built this small helper method for an android app, may come of use:
/**
* @param originalColor color, without alpha
* @param alpha from 0.0 to 1.0
* @return
*/
public static String addAlpha(String originalColor, double alpha) {
long alphaFixed = Math.round(alpha * 255);
String alphaHex = Long.toHexString(alphaFixed);
if (alphaHex.length() == 1) {
alphaHex = "0" + alphaHex;
}
originalColor = originalColor.replace("#", "#" + alphaHex);
return originalColor;
}
This is a modified version of @Aleksandr Fedorenko's answer adding a WHERE clause:
UPDATE x
SET x.CODE_DEST = x.New_CODE_DEST
FROM (
SELECT CODE_DEST, ROW_NUMBER() OVER (ORDER BY [RS_NOM]) AS New_CODE_DEST
FROM DESTINATAIRE_TEMP
) x
WHERE x.CODE_DEST <> x.New_CODE_DEST AND x.CODE_DEST IS NOT NULL
By adding a WHERE clause I found the performance improved massively for subsequent updates. Sql Server seems to update the row even if the value already exists and it takes time to do so, so adding the where clause makes it just skip over rows where the value hasn't changed. I have to say I was astonished as to how fast it could run my query.
Disclaimer: I'm no DB expert, and I'm using PARTITION BY for my clause so it may not be exactly the same results for this query. For me the column in question is a customer's paid order, so the value generally doesn't change once it is set.
Also make sure you have indexes, especially if you have a WHERE clause on the SELECT statement. A filtered index worked great for me as I was filtering based on payment statuses.
My query using PARTITION by
UPDATE UpdateTarget
SET PaidOrderIndex = New_PaidOrderIndex
FROM
(
SELECT PaidOrderIndex, SimpleMembershipUserName, ROW_NUMBER() OVER(PARTITION BY SimpleMembershipUserName ORDER BY OrderId) AS New_PaidOrderIndex
FROM [Order]
WHERE PaymentStatusTypeId in (2,3,6) and SimpleMembershipUserName is not null
) AS UpdateTarget
WHERE UpdateTarget.PaidOrderIndex <> UpdateTarget.New_PaidOrderIndex AND UpdateTarget.PaidOrderIndex IS NOT NULL
-- test to 'break' some of the rows, and then run the UPDATE again
update [order] set PaidOrderIndex = 2 where PaidOrderIndex=3
The 'IS NOT NULL' part isn't required if the column isn't nullable.
When I say the performance increase was massive I mean it was essentially instantaneous when updating a small number of rows. With the right indexes I was able to achieve an update that took the same amount of time as the 'inner' query does by itself:
SELECT PaidOrderIndex, SimpleMembershipUserName, ROW_NUMBER() OVER(PARTITION BY SimpleMembershipUserName ORDER BY OrderId) AS New_PaidOrderIndex
FROM [Order]
WHERE PaymentStatusTypeId in (2,3,6) and SimpleMembershipUserName is not null
user: USER
this.user = ({} as USER)
<br />
will take as much space as text-filled row of your <p>
, you can't change that. If you want larger, it means you want to separate into paragraph, so add other <p>
. Don't forget to be the most semantic you can ;)
If you are here because of the Liquibase error saying:
Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short
and you are using
not {
indexExists()
}
precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342
We can try to execute an above check using bare sqlCheck
(Postgres):
SELECT COUNT(i.relname)
FROM
pg_class t,
pg_class i,
pg_index ix
WHERE
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and t.relkind = 'r'
and t.relname = 'tableName'
and i.relname = 'indexName';
where tableName
- is an index table name and indexName
- is an index name
A simple but relatively insecure way would be to use the --net=host
option to docker run
.
This option makes it so that the container uses the networking stack of the host. Then you can connect to services running on the host simply by using "localhost" as the hostname.
This is easier to configure because you won't have to configure the service to accept connections from the IP address of your docker container, and you won't have to tell the docker container a specific IP address or host name to connect to, just a port.
For example, you can test it out by running the following command, which assumes your image is called my_image
, your image includes the telnet
utility, and the service you want to connect to is on port 25:
docker run --rm -i -t --net=host my_image telnet localhost 25
If you consider doing it this way, please see the caution about security on this page:
https://docs.docker.com/articles/networking/
It says:
--net=host -- Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to not containerize the container's networking! While container processes will still be confined to their own filesystem and process list and resource limits, a quick ip addr command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does not let the container reconfigure the host network stack — that would require --privileged=true — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like restart your computer. You should use this option with caution.
SQl Management Studio data import looks at the first few rows to determine source data specs..
shift your records around so that the longest text is at top.
Add the sheet name infront of the cell, e.g.:
=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")
Assumes the sheet name is "stock"
Use the following:
requestWindowFeature(Window.FEATURE_NO_TITLE);
Although I'm answering this very late but if anyone is seeking an easier solution.
We can use angular2-jwt. angular2-jwt is useful automatically attaching a JSON Web Token (JWT) as an Authorization header when making HTTP requests from an Angular 2 app.
We can set global headers with advanced configuration option
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: 'token',
tokenGetter: (() => sessionStorage.getItem('token')),
globalHeaders: [{'Content-Type':'application/json'}],
}), http, options);
}
And sending per request token like
getThing() {
let myHeader = new Headers();
myHeader.append('Content-Type', 'application/json');
this.authHttp.get('http://example.com/api/thing', { headers: myHeader })
.subscribe(
data => this.thing = data,
err => console.log(error),
() => console.log('Request Complete')
);
// Pass it after the body in a POST request
this.authHttp.post('http://example.com/api/thing', 'post body', { headers: myHeader })
.subscribe(
data => this.thing = data,
err => console.log(error),
() => console.log('Request Complete')
);
}
This can happen if you forget to return a value from a function: it then returns None. Look at all places where you are assigning to that variable, and see if one of them is a function call where the function lacks a return statement.
from PIL import Image
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')
yields
Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.
I try to give a general rule by using the OPs example
do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"
we have to avoid a branch where $a
gets more than 10, so $a < 10
as a general condition can be applied to every other, following condition.
In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.
So the OPs example with the rule applied may be restructured as:
if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
echo "1"
elif [ "$a" -lt 10 ]
then
echo "2"
fi
Just a variation of the above, enclosing everything in the $a < 10
condition:
if [ "$a" -lt 10 ]
then
if [ "$a" -le 5 ]
then
echo "1"
else
echo "2"
fi
fi
(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)
Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.
for (i>0; i--;){
c= input%i;
Thats division by zero at some point since you are decrementing i.
There is also a project on Github that aims to be a more direct port of the jQuery.extend()
:
https://github.com/dreamerslab/node.extend
An example, modified from the jQuery docs:
var extend = require('node.extend');
var object1 = {
apple: 0,
banana: {
weight: 52,
price: 100
},
cherry: 97
};
var object2 = {
banana: {
price: 200
},
durian: 100
};
var merged = extend(object1, object2);
I still prefer the method in one line
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())
boolean turnedOn;
if(turnedOn)
{
//do stuff when the condition is true - i.e, turnedOn is true
}
else
{
//do stuff when the condition is false - i.e, turnedOn is false
}
To get the rest of the string after the second instance of the space delimiter
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 1), ' ', -1) AS first_name,
SUBSTRING_INDEX(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2), ' ', -1)
AS middle_name,
SUBSTRING('Sachin ramesh tendulkar',LENGTH(SUBSTRING_INDEX('Sachin ramesh tendulkar', ' ', 2))+1) AS last_name
In my case the problem was using the language tag "en_US" in Locale.forLanguageTag(..)
instead of "en-US" - use a dash instead of underline!
Also use Locale.forLanguageTag("en-US")
instead of new Locale("en_US")
or new Locale("en_US")
to define a language ("en") with a region ("US") - but new Locale("en")
works.
Update 2
This method is no longer available in rxjs v6
I'm solved it by using the isNumeric operator from rxjs library (importing rxjs/util/isNumeric
Update
import { isNumeric } from 'rxjs/util/isNumeric';
. . .
var val = "5700";
if (isNumeric(val)){
alert("it is number !");
}
Here is an example that uses scipy.optimize to fit a non-linear functions like a Gaussian, even when the data is in a histogram that isn't well ranged, so that a simple mean estimate would fail. An offset constant also would cause simple normal statistics to fail ( just remove p[3] and c[3] for plain gaussian data).
from pylab import *
from numpy import loadtxt
from scipy.optimize import leastsq
fitfunc = lambda p, x: p[0]*exp(-0.5*((x-p[1])/p[2])**2)+p[3]
errfunc = lambda p, x, y: (y - fitfunc(p, x))
filename = "gaussdata.csv"
data = loadtxt(filename,skiprows=1,delimiter=',')
xdata = data[:,0]
ydata = data[:,1]
init = [1.0, 0.5, 0.5, 0.5]
out = leastsq( errfunc, init, args=(xdata, ydata))
c = out[0]
print "A exp[-0.5((x-mu)/sigma)^2] + k "
print "Parent Coefficients:"
print "1.000, 0.200, 0.300, 0.625"
print "Fit Coefficients:"
print c[0],c[1],abs(c[2]),c[3]
plot(xdata, fitfunc(c, xdata))
plot(xdata, ydata)
title(r'$A = %.3f\ \mu = %.3f\ \sigma = %.3f\ k = %.3f $' %(c[0],c[1],abs(c[2]),c[3]));
show()
Output:
A exp[-0.5((x-mu)/sigma)^2] + k
Parent Coefficients:
1.000, 0.200, 0.300, 0.625
Fit Coefficients:
0.961231625289 0.197254597618 0.293989275502 0.65370344131
There's no way to allocate the whole thing in one go. Instead, create an array of pointers, then, for each pointer, create the memory for it. For example:
int** array;
array = (int**)malloc(sizeof(int*) * 50);
for(int i = 0; i < 50; i++)
array[i] = (int*)malloc(sizeof(int) * 50);
Of course, you can also declare the array as int* array[50]
and skip the first malloc, but the second set is needed in order to dynamically allocate the required storage.
It is possible to hack a way to allocate it in a single step, but it would require a custom lookup function, but writing that in such a way that it will always work can be annoying. An example could be L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]
, then malloc a block of 50*50 ints or whatever and access using that L
macro, e.g.
#define L(arr,x,y,max_x) arr[(y)*(max_x) + (x)]
int dim_x = 50;
int dim_y = 50;
int* array = malloc(dim_x*dim_y*sizeof(int));
int foo = L(array, 4, 6, dim_x);
But that's much nastier unless you know the effects of what you're doing with the preprocessor macro.
You can use this to fill zeroes in a Mat object already containing data:
image1 = Scalar::all(0);
For eg, if you use it this way:
Mat image,image1;
image = imread("IMG_20160107_185956.jpg", CV_LOAD_IMAGE_COLOR); // Read the file
if(! image.data ) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
cvtColor(image,image1,CV_BGR2GRAY);
image1 = Scalar::all(0);
It will work fine. But you cannot use this for uninitialised Mat. For that you can go for other options mentioned in above answers, like
Mat drawing = Mat::zeros( image.size(), CV_8UC3 );
As somebody figures out that the OP wants to convert custom List to org.json.JSONArray
not the com.google.gson.JsonArray
,the CORRECT answer should be like this:
Gson gson = new Gson();
String listString = gson.toJson(
targetList,
new TypeToken<ArrayList<targetListItem>>() {}.getType());
JSONArray jsonArray = new JSONArray(listString);
You need to run Set-ExecutionPolicy
:
Set-ExecutionPolicy Restricted <-- Will not allow any powershell scripts to run. Only individual commands may be run.
Set-ExecutionPolicy AllSigned <-- Will allow signed powershell scripts to run.
Set-ExecutionPolicy RemoteSigned <-- Allows unsigned local script and signed remote powershell scripts to run.
Set-ExecutionPolicy Unrestricted <-- Will allow unsigned powershell scripts to run. Warns before running downloaded scripts.
Set-ExecutionPolicy Bypass <-- Nothing is blocked and there are no warnings or prompts.
Another way so easy:
function outside:
function funx(functionEvents, params) {
console.log("events of funx function: ", functionEvents);
console.log("this of component: ", this);
console.log("params: ", params);
thisFunction.persist();
}
Bind it:
constructor(props) {
super(props);
this.state = {};
this.funxBinded = funx.bind(this);
}
}
Please see complete tutorial here: How to use "this" of a React Component from outside?
For anyone running Windows 10 1607 and looking for .net 4.7. Disregard all of the above.
It's not in the Registry, C:\Windows\Microsoft.NET folder or the Installed Programs list or the WMIC display of that same list.
Look for "installed updates" KB3186568.
If the file is really an old .xls, this works for me on python3 just using base open() and pandas:
df = pandas.read_csv(open(f, encoding = 'UTF-8'), sep='\t')
Note that the file I'm using is tab delimited. less or a text editor should be able to read .xls so that you can sniff out the delimiter.
I did not have a lot of luck with xlrd because of – I think – UTF-8 issues.
Java doesn't have associative arrays like PHP does.
There are various solutions for what you are doing, such as using a Map, but it depends on how you want to look up the information. You can easily write a class that holds all your information and store instances of them in an ArrayList
.
public class Foo{
public String name, fname;
public Foo(String name, String fname){
this.name = name;
this.fname = fname;
}
}
And then...
List<Foo> foos = new ArrayList<Foo>();
foos.add(new Foo("demo","fdemo"));
foos.add(new Foo("test","fname"));
So you can access them like...
foos.get(0).name;
=> "demo"
You need to use the .toFixed()
method
It takes as a parameter the number of digits to show after the decimal point.
$(document).ready(function() {
$('.add').click(function() {
var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
$('#total').text( value.toFixed(2) );
});
})
Noting klaisbyskov's comment about your key length needing to be gigabytes in size, and assuming that you do in fact need this, then I think your only options are:
Hashing comes with the caveat that one day, you might get a collision.
Triggers will scan the entire table.
Over to you...
// to string
String text = textField.getText();
// to JTextField
textField.setText(text);
You can also create a new text field: new JTextField(text)
Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.
Reference: javadocs of JTextField
You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.
Try curl -v http://localhost:8080/
instead of 127.0.0.1
Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)
import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1
u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0
#option 1
#keep index of t
u.index = t.index
#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)
#now concat will keep number of rows
r=pd.concat([t,u], axis=1)
Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });
Forked @http://jsfiddle.net/QVJXD/
iPhone:
Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3
iPad:
Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3
You should use &
/ |
operators and be careful about operator precedence (==
has lower precedence than bitwise AND
and OR
):
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", "x3"))
df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
df.show()
## +---+---+---+---+---+---+
## | x1| x2| x3| x1| x2| x3|
## +---+---+---+---+---+---+
## | 2| b|3.0| 2| b|0.0|
## +---+---+---+---+---+---+
Make as shown.
$(document).ready(function(){_x000D_
$('#myModal').modal('show');_x000D_
_x000D_
$('#myBtn').on('click', function(){_x000D_
$('#myModal').modal('show');_x000D_
});_x000D_
_x000D_
});_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Activate Modal with JavaScript</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
I implemented UIGestureRecognizerDelegate methods to detect both singleTap and doubleTap.
Just do this .
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTapGesture:)];
[doubleTap setDelegate:self];
doubleTap.numberOfTapsRequired = 2;
[self.headerView addGestureRecognizer:doubleTap];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleSingleTapGesture:)];
singleTap.numberOfTapsRequired = 1;
[singleTap setDelegate:self];
[doubleTap setDelaysTouchesBegan:YES];
[singleTap setDelaysTouchesBegan:YES];
[singleTap requireGestureRecognizerToFail:doubleTap];
[self.headerView addGestureRecognizer:singleTap];
Then implement these delegate methods.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
return YES;
}
You can do like this:
INSERT INTO DENI/FRIEN01P
SELECT
RCRDID+112,
PROFESION,
NAME,
SURNAME,
AGE,
RCRDTYP,
RCRDLCU,
RCRDLCT,
RCRDLCD
FROM
FRIEN01P
There instead of 112 you should put a number of the maximum id in table DENI/FRIEN01P.
"Any" works well. Just make sure that the any keyword is on the right side of the equal to sign i.e. is present after the equal to sign.
Below statement will throw error: ERROR: syntax error at or near "any"
select 1 where any('{hello}'::text[]) = 'hello';
Whereas below example works fine
select 1 where 'hello' = any('{hello}'::text[]);
If you are Windows guy and using "Tortoise SVN' user.
Select the File. Right Click. Option 'Tortoise SVN' --> get Lock. Use option 'Steal The Lock'.
// Adds and removes body class depending on screen width.
function screenClass() {
if($(window).innerWidth() > 960) {
$('body').addClass('big-screen').removeClass('small-screen');
} else {
$('body').addClass('small-screen').removeClass('big-screen');
}
}
// Fire.
screenClass();
// And recheck when window gets resized.
$(window).bind('resize',function(){
screenClass();
});
You can try this one it is short :)
SystemClock.sleep(7000);
It will sleep for 7 sec look at documentation
$('#attached_docs [value="123"]').find ... .remove();
it should do your need however, you cannot duplicate id! remember it
I solved this problem with custom annotations. This is my "SkipSerialisation" Annotation class:
@Target (ElementType.FIELD)
public @interface SkipSerialisation {
}
and this is my GsonBuilder:
gsonBuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override public boolean shouldSkipField (FieldAttributes f) {
return f.getAnnotation(SkipSerialisation.class) != null;
}
@Override public boolean shouldSkipClass (Class<?> clazz) {
return false;
}
});
Example :
public class User implements Serializable {
public String firstName;
public String lastName;
@SkipSerialisation
public String email;
}
You are missing a PDO driver.
First install the driver
For ubuntu: For mysql database.
sudo apt-get install php5.6-mysql/php7.2-mysql
You also can search for other database systems.
You also can search for the driver:
sudo apt-cache search drivername
Then Run the cmd php artisan migrate
You need to use a while loop. If you make a while loop, and there's no instruction after the loop, it'll become an infinite loop,and won't stop until you manually stop it.
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}
▲
▼
I usually use the excellent Gucharmap to look up Unicode characters. It's installed on all recent Linux installations with Gnome under the name "Character Map". I don't know of any equivalent tools for Windows or Mac OS X, but its homepage lists a few.
Assuming your json object from your GET request looks like the one you posted above simply do:
let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
Or am I missing something that prevents you from doing it this way?
HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')
If you need sdk 23, add this to your gradle:
In dependencies add:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
and also add this
android {
useLibrary 'org.apache.http.legacy'
}
I found this solution useful in a NodeJS app. I use it just in desperate cases because it launches a timeout in order to wait for the full page load.
The second argument is the callback function which is going to be called once the response is ready.
phantom = require('phantom');
var fullLoad = function(anUrl, callbackDone) {
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open(anUrl, function (status) {
if (status !== 'success') {
console.error("pahtom: error opening " + anUrl, status);
ph.exit();
} else {
// timeOut
global.setTimeout(function () {
page.evaluate(function () {
return document.documentElement.innerHTML;
}, function (result) {
ph.exit(); // EXTREMLY IMPORTANT
callbackDone(result); // callback
});
}, 5000);
}
});
});
});
}
var callback = function(htmlBody) {
// do smth with the htmlBody
}
fullLoad('your/url/', callback);
https://mms.nw.ru uses a self-signed certificate that's not in the default trust manager set. To resolve the issue, do one of the following:
SSLContext
with a TrustManager
that accepts any certificate (see below).SSLContext
with an appropriate trust store that includes your certificate.Here's a program that creates a (mostly worthless) SSL Context that accepts any certificate:
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SSLTest {
public static void main(String [] args) throws Exception {
// configure the SSLContext with a TrustManager
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
URL url = new URL("https://mms.nw.ru");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
System.out.println(conn.getResponseCode());
conn.disconnect();
}
private static class DefaultTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
We can use map
function
print map(str, EmployeeList)
If you really must use only standard libraries, then you just have to expand on Omar's solution a bit. (Apache's IOUtils is basically just a set of convenience methods which saves on a lot of coding)
You are already able to get the input stream through clobObject.getAsciiStream()
You just have to "manually transfer" the characters to the StringWriter:
InputStream in = clobObject.getAsciiStream();
Reader read = new InputStreamReader(in);
StringWriter write = new StringWriter();
int c = -1;
while ((c = read.read()) != -1)
{
write.write(c);
}
write.flush();
String s = write.toString();
Bear in mind that
I believe that using a combination of interfaces and base classes could work for you. It will enforce behavioral requirements at compile time (rq_ post "below" refers to a post above, which is not this one).
The interface sets the behavioral API that isn't met by the base class. You will not be able to set base class methods to call on methods defined in the interface (because you will not be able to implement that interface in the base class without having to define those behaviors). Maybe someone can come up with a safe trick to allow calling of the interface methods in the parent.
You have to remember to extend and implement in the class you will instantiate. It satisfies concerns about defining runtime-fail code. You also won't even be able to call the methods that would puke if you haven't implemented the interface (such as if you try to instantiate the Animal class). I tried having the interface extend the BaseAnimal below, but it hid the constructor and the 'name' field of BaseAnimal from Snake. If I had been able to do that, the use of a module and exports could have prevented accidental direct instantiation of the BaseAnimal class.
Paste this in here to see if it works for you: http://www.typescriptlang.org/Playground/
// The behavioral interface also needs to extend base for substitutability
interface AbstractAnimal extends BaseAnimal {
// encapsulates animal behaviors that must be implemented
makeSound(input : string): string;
}
class BaseAnimal {
constructor(public name) { }
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
// If concrete class doesn't extend both, it cannot use super methods.
class Snake extends BaseAnimal implements AbstractAnimal {
constructor(name) { super(name); }
makeSound(input : string): string {
var utterance = "sssss"+input;
alert(utterance);
return utterance;
}
move() {
alert("Slithering...");
super.move(5);
}
}
var longMover = new Snake("windy man");
longMover.makeSound("...am I nothing?");
longMover.move();
var fulture = new BaseAnimal("bob fossil");
// compile error on makeSound() because it is not defined.
// fulture.makeSound("you know, like a...")
fulture.move(1);
I came across FristvanCampen's answer as linked below. He says abstract classes are an anti-pattern, and suggests that one instantiate base 'abstract' classes using an injected instance of an implementing class. This is fair, but there are counter arguments made. Read for yourself: https://typescript.codeplex.com/discussions/449920
Part 2: I had another case where I wanted an abstract class, but I was prevented from using my solution above, because the defined methods in the "abstract class" needed to refer to the methods defined in the matching interface. So, I tool FristvanCampen's advice, sort of. I have the incomplete "abstract" class, with method implementations. I have the interface with the unimplemented methods; this interface extends the "abstract" class. I then have a class that extends the first and implements the second (it must extend both because the super constructor is inaccessible otherwise). See the (non-runnable) sample below:
export class OntologyConceptFilter extends FilterWidget.FilterWidget<ConceptGraph.Node, ConceptGraph.Link> implements FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link> {
subMenuTitle = "Ontologies Rendered"; // overload or overshadow?
constructor(
public conceptGraph: ConceptGraph.ConceptGraph,
graphView: PathToRoot.ConceptPathsToRoot,
implementation: FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link>
){
super(graphView);
this.implementation = this;
}
}
and
export class FilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> {
public implementation: IFilterWidget<N, L>
filterContainer: JQuery;
public subMenuTitle : string; // Given value in children
constructor(
public graphView: GraphView.GraphView<N, L>
){
}
doStuff(node: N){
this.implementation.generateStuff(thing);
}
}
export interface IFilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> extends FilterWidget<N, L> {
generateStuff(node: N): string;
}
Beamer just delegates responsibility for managing layout of itemize
environments back to the base LaTeX packages, so there's nothing funky you need to do in Beamer itself to alter the apperaance / layout of your lists.
Since Beamer redefines itemize, item, etc., the fully proper way to manipulate things like indentation is to redefine the Beamer templates. I get the impression that you're not looking to go that far, but if that's not the case, let me know and I'll elaborate.
There are at least three ways of accomplishing your goal from within your document, without mussing about with Beamer templates.
itemize
In the following code snippet, you can change the value of \itemindent
from 0em
to whatever you please, including negative values. 0em
is the default item indentation.
The advantage of this method is that the list is styled normally. The disadvantage is that Beamer's redefinition of itemize
and \item
means that the number of paramters that can be manipulated to change the list layout is limited. It can be very hard to get the spacing right with multi-line items.
\begin{itemize}
\setlength{\itemindent}{0em}
\item This is a normally-indented item.
\end{itemize}
list
In the following code snippet, the second parameter to \list
is the bullet to use, and the third parameter is a list of layout parameters to change. The \leftmargin
parameter adjusts the indentation of the entire list item and all of its rows; \itemindent
alters the indentation of subsequent lines.
The advantage of this method is that you have all of the flexibility of lists in non-Beamer LaTeX. The disadvantage is that you have to setup the bullet style (and other visual elements) manually (or identify the right command for the template you're using). Note that if you leave the second argument empty, no bullet will be displayed and you'll save some horizontal space.
\begin{list}{$\square$}{\leftmargin=1em \itemindent=0em}
\item This item uses the margin and indentation provided above.
\end{list}
customlist
environmentThe shortcomings of the list
solution can be ameliorated by defining a new customlist
environment that basically redefines the itemize
environment from Beamer but also incorporates the \leftmargin
and \itemindent
(etc.) parameters. Put the following in your preamble:
\makeatletter
\newenvironment{customlist}[2]{
\ifnum\@itemdepth >2\relax\@toodeep\else
\advance\@itemdepth\@ne%
\beamer@computepref\@itemdepth%
\usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
\usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
\usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
\begin{list}
{
\usebeamertemplate{itemize \beameritemnestingprefix item}
}
{ \leftmargin=#1 \itemindent=#2
\def\makelabel##1{%
{%
\hss\llap{{%
\usebeamerfont*{itemize \beameritemnestingprefix item}%
\usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
}%
}%
}
\fi
}
{
\end{list}
\usebeamertemplate{itemize/enumerate \beameritemnestingprefix body end}%
}
\makeatother
Now, to use an itemized list with custom indentation, you can use the following environment. The first argument is for \leftmargin
and the second is for \itemindent
. The default values are 2.5em and 0em respectively.
\begin{customlist}{2.5em}{0em}
\item Any normal item can go here.
\end{customlist}
A custom bullet style can be incorporated into the customlist
solution using the standard Beamer mechanism of \setbeamertemplate
. (See the answers to this question on the TeX Stack Exchange for more information.)
Alternatively, the bullet style can just be modified directly within the environment, by replacing \usebeamertemplate{itemize \beameritemnestingprefix item}
with whatever bullet style you'd like to use (e.g. $\square$
).
You might not have the ability to install Expect on the target server. This is often the case when one writes, say, a Jenkins job.
If so, I would consider something like the answer to the following on askubuntu.com:
https://askubuntu.com/questions/338857/automatically-enter-input-in-command-line
printf 'y\nyes\nno\nmaybe\n' | ./script_that_needs_user_input
Note that in some rare cases the command does not require the user to press enter after the character. in that case leave the newlines out:
printf 'yyy' | ./script_that_needs_user_input
For sake of completeness you can also use a here document:
./script_that_needs_user_input << EOF
y
y
y
EOF
Or if your shell supports it a here string:
./script <<< "y
y
y
"
Or you can create a file with one input per line:
./script < inputfile
Again, all credit for this answer goes to the author of the answer on askubuntu.com, lesmana.
Just sharing this extension methods, I hope that it can help someone.
public static List<string> ToCSV(this DataSet ds, char separator = '|')
{
List<string> lResult = new List<string>();
foreach (DataTable dt in ds.Tables)
{
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(separator.ToString(), columnNames));
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field =>
string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(separator.ToString(), fields));
}
lResult.Add(sb.ToString());
}
return lResult;
}
public static DataSet CSVtoDataSet(this List<string> collectionCSV, char separator = '|')
{
var ds = new DataSet();
foreach (var csv in collectionCSV)
{
var dt = new DataTable();
var readHeader = false;
foreach (var line in csv.Split(new[] { Environment.NewLine }, StringSplitOptions.None))
{
if (!readHeader)
{
foreach (var c in line.Split(separator))
dt.Columns.Add(c);
}
else
{
dt.Rows.Add(line.Split(separator));
}
}
ds.Tables.Add(dt);
}
return ds;
}
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
To find all the pom.xml
files in your current directory and print them, you can use:
find . -name 'pom.xml' -print
you must have record in table or array record in database.
example:
SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
I am assuming what you are trying to achieve is to insert a line after the first few lines of of a textfile.
head -n10 file.txt >> newfile.txt
echo "your line >> newfile.txt
tail -n +10 file.txt >> newfile.txt
If you don't want to rest of the lines from the file, just skip the tail part.
There are (at least) two things you can do here–you can reclone the remote repo, or you can reset --hard
to the common ancestor and then do a pull, which will fast-forward to the latest commit on the remote master.
To be concrete, here's a simple extension of Nevik Rehnel's original answer:
git reset --hard origin/master
git pull origin master
NOTE: using git reset --hard
will discard any uncommitted changes, and it can be easy to confuse yourself with this command if you're new to git, so make sure you have a sense of what it is going to do before proceeding.
You need to alias the subquery.
SELECT name FROM (SELECT name FROM agentinformation) a
or to be more explicit
SELECT a.name FROM (SELECT name FROM agentinformation) a
You are not leveraging async / await effectively because the request thread will be blocked while executing the synchronous method ReturnAllCountries()
The thread that is assigned to handle a request will be idly waiting while ReturnAllCountries()
does it's work.
If you can implement ReturnAllCountries()
to be asynchronous, then you would see scalability benefits. This is because the thread could be released back to the .NET thread pool to handle another request, while ReturnAllCountries()
is executing. This would allow your service to have higher throughput, by utilizing threads more efficiently.
You can get that value by using the $_GET
array. So the id value would be stored in $_GET['id']
.
So in your case you could store that value in the $id
variable as follows:
$id = $_GET['id'];
You can use this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Actions to do after 10 seconds
}
}, 10000);
For Stop the Handler, You can try this:
handler.removeCallbacksAndMessages(null);
Using the following script, based on SLaks answer, I determined that the correct answer is:
echo The name of this file is: %~n0%~x0
echo The name of this file is: %~nx0
And here is my test script:
@echo off
echo %0
echo %~0
echo %n0
echo %x0
echo %~n0
echo %dp0
echo %~dp0
pause
What I find interesting is that %nx0 won't work, given that we know the '~' char usually is used to strip/trim quotes off of a variable.
Just use the following command
git show a2c25061
or (the exact equivalent):
git log -p -1 a2c25061
You will need have to download InternetExplorer driver executable on your system, download it from the source (http://code.google.com/p/selenium/downloads/list) after download unzip it and put on the place of somewhere in your computer. In my example, I will place it to D:\iexploredriver.exe
Then you have write below code in your eclipse main class
System.setProperty("webdriver.ie.driver", "D:/iexploredriver.exe");
WebDriver driver = new InternetExplorerDriver();
Some time ago I created module for loading modules relative to pre-defined paths.
You can use it instead of require.
irequire.prefix('controllers',join.path(__dirname,'app/master'));
var adminUsersCtrl = irequire("controllers:admin/users");
var net = irequire('net');
Maybe it will be usefull for someone..
It is not good to manipulate with DOM (including checking of attributes) in any place except directives. You can add into scope some value indicating if link should be disabled.
But other problem is that ngDisabled does not work on anything except form controls, so you can't use it with <a>, but you can use it with <button> and style it as link.
Another way is to use lazy evaluation of expressions like isDisabled || action()
so action wouold not be called if isDisabled
is true.
Here goes both solutions: http://plnkr.co/edit/5d5R5KfD4PCE8vS3OSSx?p=preview
To do this without Rails, a clean way is to store attributes on a constant.
class Gift
ATTRIBUTES = [:name, :price]
attr_accessor(*ATTRIBUTES)
end
And then, to convert an instance of Gift
to a Hash
, you can:
class Gift
...
def to_h
ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
memo[attribute_name] = send(attribute_name)
end
end
end
This is a good way to do this because it will only include what you define on attr_accessor
, and not every instance variable.
class Gift
ATTRIBUTES = [:name, :price]
attr_accessor(*ATTRIBUTES)
def create_random_instance_variable
@xyz = 123
end
def to_h
ATTRIBUTES.each_with_object({}) do |attribute_name, memo|
memo[attribute_name] = send(attribute_name)
end
end
end
g = Gift.new
g.name = "Foo"
g.price = 5.25
g.to_h
#=> {:name=>"Foo", :price=>5.25}
g.create_random_instance_variable
g.to_h
#=> {:name=>"Foo", :price=>5.25}
To quote the documentation:
Typical implementations create a new instance of the class by invoking the superclass's __new__() method using "super(currentclass, cls).__new__(cls[, ...])"with appropriate arguments and then modifying the newly-created instance as necessary before returning it.
...
If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.
__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation.
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
Check your apache error log. I had this error "[error] (OS 5)Access is denied. : could not open transfer log file C:/wamp/logs/access.log. Unable to open logs" Then I rename my "access.log" to other name, you can delete if you don't need/never see your access log. Then restart your apache service. This happen because the file size too big. I think if you trying to open this file using notepad, it will not open, I tried to open that before. Hope it help.
i'll leave this here since i will need to use it later. It's a source for a small binary compatible tool that will work equally well in assembly, C and C++.
GetErrorMessageLib.c (compiled to GetErrorMessageLib.dll)
#include <Windows.h>
/***
* returns 0 if there was enough space, size of buffer in bytes needed
* to fit the result, if there wasn't enough space. -1 on error.
*/
__declspec(dllexport)
int GetErrorMessageA(DWORD dwErrorCode, LPSTR lpResult, DWORD dwBytes)
{
LPSTR tmp;
DWORD result_len;
result_len = FormatMessageA (
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
dwErrorCode,
LANG_SYSTEM_DEFAULT,
(LPSTR)&tmp,
0,
NULL
);
if (result_len == 0) {
return -1;
}
// FormatMessage's return is 1 character too short.
++result_len;
strncpy(lpResult, tmp, dwBytes);
lpResult[dwBytes - 1] = 0;
LocalFree((HLOCAL)tmp);
if (result_len <= dwBytes) {
return 0;
} else {
return result_len;
}
}
/***
* returns 0 if there was enough space, size of buffer in bytes needed
* to fit the result, if there wasn't enough space. -1 on error.
*/
__declspec(dllexport)
int GetErrorMessageW(DWORD dwErrorCode, LPWSTR lpResult, DWORD dwBytes)
{
LPWSTR tmp;
DWORD nchars;
DWORD result_bytes;
nchars = dwBytes >> 1;
result_bytes = 2 * FormatMessageW (
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
dwErrorCode,
LANG_SYSTEM_DEFAULT,
(LPWSTR)&tmp,
0,
NULL
);
if (result_bytes == 0) {
return -1;
}
// FormatMessage's return is 1 character too short.
result_bytes += 2;
wcsncpy(lpResult, tmp, nchars);
lpResult[nchars - 1] = 0;
LocalFree((HLOCAL)tmp);
if (result_bytes <= dwBytes) {
return 0;
} else {
return result_bytes * 2;
}
}
inline version(GetErrorMessage.h):
#ifndef GetErrorMessage_H
#define GetErrorMessage_H
#include <Windows.h>
/***
* returns 0 if there was enough space, size of buffer in bytes needed
* to fit the result, if there wasn't enough space. -1 on error.
*/
static inline int GetErrorMessageA(DWORD dwErrorCode, LPSTR lpResult, DWORD dwBytes)
{
LPSTR tmp;
DWORD result_len;
result_len = FormatMessageA (
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
dwErrorCode,
LANG_SYSTEM_DEFAULT,
(LPSTR)&tmp,
0,
NULL
);
if (result_len == 0) {
return -1;
}
// FormatMessage's return is 1 character too short.
++result_len;
strncpy(lpResult, tmp, dwBytes);
lpResult[dwBytes - 1] = 0;
LocalFree((HLOCAL)tmp);
if (result_len <= dwBytes) {
return 0;
} else {
return result_len;
}
}
/***
* returns 0 if there was enough space, size of buffer in bytes needed
* to fit the result, if there wasn't enough space. -1 on error.
*/
static inline int GetErrorMessageW(DWORD dwErrorCode, LPWSTR lpResult, DWORD dwBytes)
{
LPWSTR tmp;
DWORD nchars;
DWORD result_bytes;
nchars = dwBytes >> 1;
result_bytes = 2 * FormatMessageW (
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
dwErrorCode,
LANG_SYSTEM_DEFAULT,
(LPWSTR)&tmp,
0,
NULL
);
if (result_bytes == 0) {
return -1;
}
// FormatMessage's return is 1 character too short.
result_bytes += 2;
wcsncpy(lpResult, tmp, nchars);
lpResult[nchars - 1] = 0;
LocalFree((HLOCAL)tmp);
if (result_bytes <= dwBytes) {
return 0;
} else {
return result_bytes * 2;
}
}
#endif /* GetErrorMessage_H */
dynamic usecase(assumed that error code is valid, otherwise a -1 check is needed):
#include <Windows.h>
#include <Winbase.h>
#include <assert.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int (*GetErrorMessageA)(DWORD, LPSTR, DWORD);
int (*GetErrorMessageW)(DWORD, LPWSTR, DWORD);
char result1[260];
wchar_t result2[260];
assert(LoadLibraryA("GetErrorMessageLib.dll"));
GetErrorMessageA = (int (*)(DWORD, LPSTR, DWORD))GetProcAddress (
GetModuleHandle("GetErrorMessageLib.dll"),
"GetErrorMessageA"
);
GetErrorMessageW = (int (*)(DWORD, LPWSTR, DWORD))GetProcAddress (
GetModuleHandle("GetErrorMessageLib.dll"),
"GetErrorMessageW"
);
GetErrorMessageA(33, result1, sizeof(result1));
GetErrorMessageW(33, result2, sizeof(result2));
puts(result1);
_putws(result2);
return 0;
}
regular use case(assumes error code is valid, otherwise -1 return check is needed):
#include <stdio.h>
#include "GetErrorMessage.h"
#include <stdio.h>
int main(int argc, char **argv)
{
char result1[260];
wchar_t result2[260];
GetErrorMessageA(33, result1, sizeof(result1));
puts(result1);
GetErrorMessageW(33, result2, sizeof(result2));
_putws(result2);
return 0;
}
example using with assembly gnu as in MinGW32(again, assumed that error code is valid, otherwise -1 check is needed).
.global _WinMain@16
.section .text
_WinMain@16:
// eax = LoadLibraryA("GetErrorMessageLib.dll")
push $sz0
call _LoadLibraryA@4 // stdcall, no cleanup needed
// eax = GetProcAddress(eax, "GetErrorMessageW")
push $sz1
push %eax
call _GetProcAddress@8 // stdcall, no cleanup needed
// (*eax)(errorCode, szErrorMessage)
push $200
push $szErrorMessage
push errorCode
call *%eax // cdecl, cleanup needed
add $12, %esp
push $szErrorMessage
call __putws // cdecl, cleanup needed
add $4, %esp
ret $16
.section .rodata
sz0: .asciz "GetErrorMessageLib.dll"
sz1: .asciz "GetErrorMessageW"
errorCode: .long 33
.section .data
szErrorMessage: .space 200
result: The process cannot access the file because another process has locked a portion of the file.
Create a new file startCmdLine.bat in your directory and put this line in it
call cmd
That is it. Now double click on the .bat file. It works for me.
You can replace call with start, it will also work.
What about using the unshift
method?
ary.unshift(obj, ...) ? ary
Prepends objects to the front of self, moving other elements upwards.
And in use:
irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"
%Started Program or Command% | taskkill /F /IM cmd.exe
Example:
notepad.exe | taskkill /F /IM cmd.exe
I may be late, but you can try the following code, which worked for me for Drag and Drop.
.dndclass{
cursor: url('../images/grab1.png'), auto;
}
.dndclass:active {
cursor: url('../images/grabbing1.png'), auto;
}
You can use the images below in the URL above. Make sure it is a PNG transparent image. If not, download one from google.
You have to edit httpd.conf
and find this line: Listen 127.0.0.1:80
Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80
I used 192.167.137.1
as my LAN IP of Windows 7. Restart Apache and enjoy sharing.
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);
}
}
});
}
In case you're using Laravel 8 for the back-end side with CORS properly configured, add this line to config/cors.php
:
'exposed_headers' => ['Authorization'],
<button type ="button" onclick="location.href='@Url.Action("viewname","Controllername")'"> Button name</button>
for e.g ,
<button type="button" onclick="location.href='@Url.Action("register","Home")'">Register</button>
I finally could figure the issue out.
To get the Key Alias: I copied the keytool.exe and my keystore file into C:\Program Files\Java\jdk1.7.0_71\bin folder. Then from command prompt I wrote: keytool -list -v -keystore <name>.keystore
It will also ask for keystore password then. Then it will show you the key alias and Certificate fingerprints and other info.
Then I again tried to Generate Signed Apk for the project, I provided keystore, keystore password, key alias and provided the same password. Then it asks for master password, I tried with the same and it failed. With the reset option I reset the master password here.
I had the same error, even after re-running aws configure
, and inputting a new AWS_ACESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
.
What fixed it for me was to delete my ~/.aws/credentials
file and re-run aws configure
.
It seems that my ~/.aws/credentials
file had an additional value: aws_session_token
which was causing the error. After deleting and re-creating the ~/.aws/configure
using the command aws configure
, there is now only values for aws_access_key_id
and aws_secret_access_key
.
You can also use the new HTML5 custom data- attributes.
<script type="text/javascript">
$(document).ready(function() {
$('.my_button').click(function() {
alert($(this).attr('data-value'));
});
});
</script>
<button class="my_button" name="buttonName" data-value="buttonValue">Button Label</button>
You can get the list of the fragments and look to the last one.
FragmentManager fm = getSupportFragmentManager();
List<Fragment> fragments = fm.getFragments();
Fragment lastFragment = fragments.get(fragments.size() - 1);
But sometimes (when you navigate back) list size remains same but some of the last elements are null. So in the list I iterated to the last not null fragment and used it.
FragmentManager fm = getSupportFragmentManager();
if (fm != null) {
List<Fragment> fragments = fm.getFragments();
if (fragments != null) {
for(int i = fragments.size() - 1; i >= 0; i--){
Fragment fragment = fragments.get(i);
if(fragment != null) {
// found the current fragment
// if you want to check for specific fragment class
if(fragment instanceof YourFragmentClass) {
// do something
}
break;
}
}
}
}
You need to construct it using req.headers.host + req.url
. Of course if you are hosting in a different port and such you get the idea ;-)
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
I think 'HEAD' is current check out commit. In other words 'HEAD' points to the commit that is currently checked out.
If you have just cloned and not checked out I don't know what it points to, probably some invalid location.
var divs = $("div[class*='alert-box']");
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
This is the complex (curly) syntax for string interpolation. From the manual:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in
{
and}
. Since{
can not be escaped, this syntax will only be recognised when the$
immediately follows the{
. Use{\$
to get a literal{$
. Some examples to make it clear:<?php // Show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; echo "This is ${great}"; // Works echo "This square is {$square->width}00 centimeters broad."; // Works, quoted keys only work using the curly brace syntax echo "This works: {$arr['key']}"; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong outside a string. // In other words, it will still work, but only because PHP first looks for a // constant named foo; an error of level E_NOTICE (undefined constant) will be // thrown. echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use braces around arrays // when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "This works too: {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; echo "This is the value of the var named by the return value of getName(): {${getName()}}"; echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}"; // Won't work, outputs: This is the return value of getName(): {getName()} echo "This is the return value of getName(): {getName()}"; ?>
Often, this syntax is unnecessary. For example, this:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
behaves exactly the same as this:
$out = "{$a} {$a}"; // same
So the curly braces are unnecessary. But this:
$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh
, so you need to do:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
Those are varargs
they are used to create a method that receive any number of arguments.
For instance PrintStream.printf method uses it, since you don't know how many would arguments you'll use.
They can only be used as final position of the arguments.
varargs
was was added on Java 1.5
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List
in an EditorTemplate.
I have a model like this:
public class Foo
{
public string FooName { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string BarName { get; set; }
}
And this is my main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.EditorFor(m => m.Bars)
And this is my Bar EditorTemplate (Bar.cshtml)
@model List<Bar>
<div class="some-style">
@foreach (var item in Model)
{
<label>@item.BarName</label>
}
</div>
And I got this error:
The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]
The reason for this error is that EditorFor
already iterates the List
for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.
This is how I fixed this problem:
Brought the styles outside of the editor template, and into the main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
<div class="some-style">
@Html.EditorFor(m => m.Bars)
</div>
And changed the EditorTemplate (Bar.cshtml) to this:
@model Bar
<label>@Model.BarName</label>
the difference is that max-device-width is all screen's width and max-width means the space used by the browser to show the pages. But another important difference is the support of android browsers, in fact if u're going to use max-device-width this will work only in Opera, instead I'm sure that max-width will work for every kind of mobile browser (I had test it in Chrome, firefox and opera for ANDROID).
Delegates are extremely useful when wanting to declare a block of code that you want to pass around. For example when using a generic retry mechanism.
Pseudo:
function Retry(Delegate func, int numberOfTimes)
try
{
func.Invoke();
}
catch { if(numberOfTimes blabla) func.Invoke(); etc. etc. }
Or when you want to do late evaluation of code blocks, like a function where you have some Transform
action, and want to have a BeforeTransform
and an AfterTransform
action that you can evaluate within your Transform function, without having to know whether the BeginTransform
is filled, or what it has to transform.
And of course when creating event handlers. You don't want to evaluate the code now, but only when needed, so you register a delegate that can be invoked when the event occurs.
To answer this question from my understanding...
An authentication system that uses REST so that you do not need to actually track or manage the users in your system. This is done by using the HTTP methods POST, GET, PUT, DELETE. We take these 4 methods and think of them in terms of database interaction as CREATE, READ, UPDATE, DELETE (but on the web we use POST and GET because that is what anchor tags support currently). So treating POST and GET as our CREATE/READ/UPDATE/DELETE (CRUD) then we can design routes in our web application that will be able to deduce what action of CRUD we are achieving.
For example, in a Ruby on Rails application we can build our web app such that if a user who is logged in visits http://store.com/account/logout then the GET of that page can viewed as the user attempting to logout. In our rails controller we would build an action in that logs the user out and sends them back to the home page.
A GET on the login page would yield a form. a POST on the login page would be viewed as a login attempt and take the POST data and use it to login.
To me, it is a practice of using HTTP methods mapped to their database meaning and then building an authentication system with that in mind you do not need to pass around any session id's or track sessions.
I'm still learning -- if you find anything I have said to be wrong please correct me, and if you learn more post it back here. Thanks.
This can be achieved via a hack, Navigate to some sample component and then navigate to the component that you want to reload.
this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);
Turing Complete means that it is at least as powerful as a Turing Machine. This means anything that can be computed by a Turing Machine can be computed by a Turing Complete system.
No one has yet found a system more powerful than a Turing Machine. So, for the time being, saying a system is Turing Complete is the same as saying the system is as powerful as any known computing system (see Church-Turing Thesis).
add label
to subview
of custom view
, no need of self.view.addSubview(view)
, because viewForHeaderInSection
return the UIView
view.addSubview(label)
In LINQ you can solve it the following way:
Item itemMax = (from i in items
let maxId = items.Max(m => m.ID)
where i.ID == maxId
select i).FirstOrDefault();
I always find the POSIX table in the other answer slow to grok, so here's my take on it:
+----------------------+------------+-----------------------+-----------------------+
| if VARIABLE is: | set | empty | unset |
+----------------------+------------+-----------------------+-----------------------+
- | ${VARIABLE-default} | $VARIABLE | "" | "default" |
= | ${VARIABLE=default} | $VARIABLE | "" | $(VARIABLE="default") |
? | ${VARIABLE?default} | $VARIABLE | "" | exit 127 |
+ | ${VARIABLE+default} | "default" | "default" | "" |
+----------------------+------------+-----------------------+-----------------------+
:- | ${VARIABLE:-default} | $VARIABLE | "default" | "default" |
:= | ${VARIABLE:=default} | $VARIABLE | $(VARIABLE="default") | $(VARIABLE="default") |
:? | ${VARIABLE:?default} | $VARIABLE | exit 127 | exit 127 |
:+ | ${VARIABLE:+default} | "default" | "" | "" |
+----------------------+------------+-----------------------+-----------------------+
Note that each group (with and without preceding colon) has the same set and unset cases, so the only thing that differs is how the empty cases are handled.
With the preceding colon, the empty and unset cases are identical, so I would use those where possible (i.e. use :=
, not just =
, because the empty case is inconsistent).
Headings:
VARIABLE
is non-empty (VARIABLE="something"
)VARIABLE
is empty/null (VARIABLE=""
)VARIABLE
does not exist (unset VARIABLE
)Values:
$VARIABLE
means the result is the original value of the variable."default"
means the result was the replacement string provided.""
means the result is null (an empty string).exit 127
means the script stops executing with exit code 127.$(VARIABLE="default")
means the result is "default"
and that VARIABLE
(previously empty or unset) will also be set equal to "default"
.Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.
As a beginner in SQL I find that when using a BEGIN
and END
SSMS usually adds a squiggly line with incorrect syntax near 'END'
to END, simply because there's no content in between yet. If you're just setting up BEGIN
and END
to get started and add the actual query later, then simply add a bogus PRINT
statement so SSMS stops bothering you.
For example:
IF (1=1)
BEGIN
PRINT 'BOGUS'
END
The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:
IF (1=1)
BEGIN
END
Here's a succinct and generic solution to use a seaborn color palette.
First find a color palette you like and optionally visualize it:
sns.palplot(sns.color_palette("Set2", 8))
Then you can use it with matplotlib
doing this:
# Unique category labels: 'D', 'F', 'G', ...
color_labels = df['color'].unique()
# List of RGB triplets
rgb_values = sns.color_palette("Set2", 8)
# Map label to RGB
color_map = dict(zip(color_labels, rgb_values))
# Finally use the mapped values
plt.scatter(df['carat'], df['price'], c=df['color'].map(color_map))
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}
FB.login(function(response) {
if (response.authResponse) {
// The person logged into your app
} else {
// The person cancelled the login dialog
}
});
Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
This for sure is an old topic but I want to add up to the voices to crop maybe new ideas. To address the WARNING issue under discussions, all you need to do is to set one of your table columns to a PRIMARY KEY constraint.
You use a for..in
loop for this. Be sure to check if the object owns the properties or all inherited properties are shown as well. An example is like this:
var obj = {a: 1, b: 2};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
Or if you need recursion to walk through all the properties:
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
One more way:
scala> val xs = Array("first", "second", "third")
xs: Array[java.lang.String] = Array(first, second, third)
scala> for (i <- xs.indices)
| println(i + ": " + xs(i))
0: first
1: second
2: third
Personally:
for _ in range(50):
print "Some thing"
if you don't need i
. If you use Python < 3 and you want to repeat the loop a lot of times, use xrange
as there is no need to generate the whole list beforehand.
From my understanding of the Apple documentation, a selector represents the name of the method that you want to call. The nice thing about selectors is you can use them in cases where the exact method to be called varies. As a simple example, you can do something like:
SEL selec;
if (a == b) {
selec = @selector(method1)
}
else
{
selec = @selector(method2)
};
[self performSelector:selec];
To answer Prasanna's question below:
How do you replace multiple spaces by single space in Javascript ?
You would use the same function replace
with a different regular expression. The expression for whitespace is \s
and the expression for "1 or more times" is +
the plus sign, so you'd just replace Adam's answer with the following:
key=key.replace(/\s+/g,"_");
Use of pseudo-element as suggested by Terry has one PRO and one CON:
Anyway is a great solution.
OTHER SOLUTIONS:
If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:
outline
property combined with border
and a single inset box-shadow
box-shadow
combined with border
.Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border
class):
.left
{
outline: 4px solid #fff;
box-shadow:inset 0 0 0 4px #fff;
}
.right
{
box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}
LESS code:
You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.
Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):
@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;
.double-border
{
background-color: @content-color;
border: @double-border-size solid @content-color;
padding: 2em;
width: 16em;
height: 16em;
float:left;
margin-right:20px;
text-align:center;
}
.left
{
outline: @double-border-size solid @inset-border-color;
box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}
.right
{
box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}
class Outer(object):
outer_var = 1
class Inner(object):
@property
def inner_var(self):
return Outer.outer_var
This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var
. (If you change what object the name Outer
is bound to, then this code will use that object the next time it is executed.)
If you instead want all Inner
objects to have a reference to an Outer
because outer_var
is really an instance attribute:
class Outer(object):
def __init__(self):
self.outer_var = 1
def get_inner(self):
return self.Inner(self)
# "self.Inner" is because Inner is a class attribute of this class
# "Outer.Inner" would also work, or move Inner to global scope
# and then just use "Inner"
class Inner(object):
def __init__(self, outer):
self.outer = outer
@property
def inner_var(self):
return self.outer.outer_var
Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer
to Inner
, if you want.)
Here's one more answer that I've found to be pretty concise and doesn't use external packages:
import datetime as dt
import calendar
# Today, in `dt.date` type
day = dt.datetime.now().date()
one_year_delta = dt.timedelta(days=366 if ((day.month >= 3 and calendar.isleap(day.year+1)) or
(day.month < 3 and calendar.isleap(day.year))) else 365)
# Add one year to the current date
print(day + one_year_delta)
If you have Android installed in windows, you will also find it here: C:\Program Files\Android\jdk\microsoft_dist_openjdk_1.8.0.25\jre\bin
Check if the project having HRESULT: 0x80131040 error is being used/referenced by any project. If yes, kindly check if these project have similar .dll being referenced and the version is the same. If they're are not of same version number, then it is causing the said error.
Use the below code. Here -f checks, it's a file or not:
print "File $base_path is exists!\n" if -f $base_path;
and enjoy
JavaScript:
function submitForm() {
var data1 = new FormData($('input[name^="file"]'));
$.each($('input[name^="file"]')[0].files, function(i, file) {
data1.append(i, file);
});
$.ajax({
url: "<?php echo base_url() ?>employee/dashboard2/test2",
type: "POST",
data: data1,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log("PHP Output:");
console.log(data);
});
return false;
}
PHP:
public function upload_file() {
foreach($_FILES as $key) {
$name = time().$key['name'];
$path = 'upload/'.$name;
@move_uploaded_file($key['tmp_name'], $path);
}
}
You can set a control variable in vars files located in group_vars/
or directly in hosts file like this:
[vagrant:vars]
test_var=true
[location-1]
192.168.33.10 hostname=apollo
[location-2]
192.168.33.20 hostname=zeus
[vagrant:children]
location-1
location-2
And run tasks like this:
- name: "test"
command: "echo {{test_var}}"
when: test_var is defined and test_var
I had the same problem and I ended up finding out that this seems to be a known bug in DALI (Eclipse Java Persistence Tools) since at least eclipse 3.8 which could cause the save action in the java editor to be extremly slow.
Since this hasn't been fully resolved in Kepler (20130614-0229) yet and because I don't need JPT/DALI in my eclipse I ended up manually removing the org.eclipse.jpt
features and plugins.
What I did was:
1.) exit eclipse
2.) go to my eclipse install directory
cd eclipse
and execute these steps:
*nix:
mkdir disabled
mkdir disabled/features disabled/plugins
mv plugins/org.eclipse.jpt.* disabled/plugins
mv features/org.eclipse.jpt.* disabled/features
windows:
mkdir disabled
mkdir disabled\features
mkdir disabled\plugins
move plugins\org.eclipse.jpt.* disabled\plugins
for /D /R %D in (features\org.eclipse.jpt.*) do move %D disabled\features
3.) Restart eclipse.
After startup and on first use eclipse may warn you that you need to reconfigure your content-assist. Do this in your preferences dialog.
Done.
After uninstalling DALI/JPT my eclipse feels good again. No more blocked UI and waiting for seconds when saving a file.
I needed to know this to tell a user what to add to their host machine's host file. This works for me inside vagrant using just bash:
external_ip=$(cat /vagrant/config.yml | grep vagrant_ip | cut -d' ' -f2 | xargs)
echo -e "# Add this line to your host file:\n${external_ip} host.vagrant.vm"
In PHP there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:
$_SERVER['DOCUMENT_ROOT']
The only problem is that the entries in this variable are provided by the web server and there is no guarantee that all web servers offer them.
Put the date in single quotes and move the parenthesis (after the 'yes'
) to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE()
function, just use the (Y-m-d) '20120101'
or '2012-01-01'
format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
I fixed it with Datejs
This is alerting the first day:
var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);
This is for the last day:
var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3
private void button1_Click(object sender, EventArgs e)
{
int h =3;
Button[] buttonArray = new Button[8];
for (int i = 0; i <= h-1; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(20, 43);
buttonArray[i].Name= ""+i+"";
buttonArray[i].Click += button_Click;//function
buttonArray[i].Location = new Point(40, 20 + (i * 20));
panel1.Controls.Add(buttonArray[i]);
} }
If your classes are in the same package, you won't need to import. To call a method from class B in class A, you should use classB.methodName(arg)
I am just updating this with Microsoft SQL Server Management Studio 2008 R2 version. if you run the installer normally, you can just add Management Tools – Basic, and by clicking Basic it should select Management Tools – Complete.
That is what worked for me.
I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:
// Add MVC services to the services container.
services.AddMvc()
.AddJsonOptions(opts =>
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
According to some developers, "Core Java" refers to package API java.util.*
, which is mostly used in coding.
The term "Core Java" is not defined by Sun, it's just a slang definition.
J2ME / J2EE still depend on J2SDK API's for compilation and execution.
Nobody would say java.util.*
is separated from J2SDK for usage.
Since dplyr 1.0.0
, the slice_max()
/slice_min()
functions were implemented:
mtcars %>%
group_by(cyl) %>%
slice_max(mpg, n = 2, with_ties = FALSE)
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 33.9 4 71.1 65 4.22 1.84 19.9 1 1 4 1
2 32.4 4 78.7 66 4.08 2.2 19.5 1 1 4 1
3 21.4 6 258 110 3.08 3.22 19.4 1 0 3 1
4 21 6 160 110 3.9 2.62 16.5 0 1 4 4
5 19.2 8 400 175 3.08 3.84 17.0 0 0 3 2
6 18.7 8 360 175 3.15 3.44 17.0 0 0 3 2
The documentation on with_ties
parameter:
Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.
EDIT: From ECMAScript 2018 onwards, lookbehind assertions (even unbounded) are supported natively.
In previous versions, you can do this:
^(?:(?!filename\.js$).)*\.js$
This does explicitly what the lookbehind expression is doing implicitly: check each character of the string if the lookbehind expression plus the regex after it will not match, and only then allow that character to match.
^ # Start of string
(?: # Try to match the following:
(?! # First assert that we can't match the following:
filename\.js # filename.js
$ # and end-of-string
) # End of negative lookahead
. # Match any character
)* # Repeat as needed
\.js # Match .js
$ # End of string
Another edit:
It pains me to say (especially since this answer has been upvoted so much) that there is a far easier way to accomplish this goal. There is no need to check the lookahead at every character:
^(?!.*filename\.js$).*\.js$
works just as well:
^ # Start of string
(?! # Assert that we can't match the following:
.* # any string,
filename\.js # followed by filename.js
$ # and end-of-string
) # End of negative lookahead
.* # Match any string
\.js # Match .js
$ # End of string