Your awnser can be found here:
Why Lists Can't Be Dictionary Keys
Newcomers to Python often wonder why, while the language includes both a tuple and a list type, tuples are usable as a dictionary keys, while lists are not. This was a deliberate design decision, and can best be explained by first understanding how Python dictionaries work.
Source & more info: http://wiki.python.org/moin/DictionaryKeys
I guess you should restart the emulator with "emulator -wipe-data -avd YourAvdName" or check "Wipe User Data" in run configuration if you are using Eclipse.
I am facing the same issue right now.
I went through the Android Device Monitor
Step 1: Inject the $locationProvider service into the app config's constructor
Step 2: Add code line $locationProvider.html5Mode(true) to the app config's constructor.
Step 3: in the container (landing, master, or layout) page, add html tag such as <base href="/">
inside the tag.
Step 4: remove all '#" for routing config from all anchor tags. For examples, href="#home" becomes href="home"; href="#about" becomes herf="about"; href="#contact" becomes href="contact"
<ul class="nav navbar-nav">
<li><a href="home">Home</a></li>
<li><a href="about">About us</a></li>
<li><a href="contact">Contact us</a></li>
</ul>
To those in the answer above. It's definitely JavaScript. It's just inline.
BTW the jQuery equivalent if you want to apply to all selects:
$('form select').on('change', function(){
$(this).closest('form').submit();
});
I'm using Visual Studio 2015, and I've found that the first thing to do is look in the build output.
I found this error reported there:
Reading build config file: \build.json... SyntaxError: Unexpected token
The solution for that was to remove the bom from the build.json file
Then I hit a second problem - with this message in the build output:
FAILURE: Build failed with an exception. * What went wrong: A problem was found with the configuration of task ':packageRelease'.
File 'C:\Users\Colin\etc' specified for property 'signingConfig.storeFile' is not a file.
Easily solved by putting the correct filename into the keystore property
You can't do this with cp
alone but you can combine cp
with xargs
:
echo dir1 dir2 dir3 | xargs -n 1 cp file1
Will copy file1
to dir1
, dir2
, and dir3
. xargs
will call cp
3 times to do this, see the man page for xargs
for details.
To centered the pagination in BS4, should add justify-content-center
in ul
:
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1">Previous</a>
</li>
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item">
<a class="page-link" href="#">Next</a>
</li>
</ul>
</nav>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
_x000D_
See Pagination Bootstrap 4 for further information.
As Sotirios Delimanolis already pointed out in the comments, there are two options:
ResponseEntity
with error messageChange your method like this:
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
@RequestHeader(value="Secret-key") String secretKey) {
try {
// see note 1
return ResponseEntity
.status(HttpStatus.CREATED)
.body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
}
catch(ChekingCredentialsFailedException e) {
e.printStackTrace(); // see note 2
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note 1: You don't have to use the ResponseEntity
builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location
header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI)
.
Note 2: Don't use printStackTrace()
, use a logger instead.
@ExceptionHandler
Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice
like this:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ChekingCredentialsFailedException.class)
public ResponseEntity handleException(ChekingCredentialsFailedException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note that methods which are annotated with @ExceptionHandler
are allowed to have very flexible signatures. See the Javadoc for details.
Languages like scala&python give to you very powerful stuff like patternMatching, unfortunately this is still a missing-feature in Java...
but there is a solution (which I don't like in most of the cases), you can do something like this:
final int s1Value = 0;
final int s2Value = 0;
final String s1 = "a";
final String s2 = "g";
switch (s1 + s2 + s1Value + s2Value){
case "ag00": return true;
default: return false;
}
Example:
import React from 'react';
import PropTypes from 'prop-types';
class MenuItem extends React.Component {
render() {
return (
<li>
<a href={this.props.href}>{this.props.children}</a>
</li>
);
}
}
MenuItem.defaultProps = {
href: "/",
children: "Main page"
};
MenuItem.propTypes = {
href: PropTypes.string.isRequired,
children: PropTypes.string.isRequired
};
export default MenuItem;
Picture: Shows you error in console if the expected type is different
Do you mean like this?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll()
to accomplish this:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
Update
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
Your requirements still aren't 100% clear though.
Finally solved it:
var zoomIntensity = 0.2;_x000D_
_x000D_
var canvas = document.getElementById("canvas");_x000D_
var context = canvas.getContext("2d");_x000D_
var width = 600;_x000D_
var height = 200;_x000D_
_x000D_
var scale = 1;_x000D_
var originx = 0;_x000D_
var originy = 0;_x000D_
var visibleWidth = width;_x000D_
var visibleHeight = height;_x000D_
_x000D_
_x000D_
function draw(){_x000D_
// Clear screen to white._x000D_
context.fillStyle = "white";_x000D_
context.fillRect(originx,originy,800/scale,600/scale);_x000D_
// Draw the black square._x000D_
context.fillStyle = "black";_x000D_
context.fillRect(50,50,100,100);_x000D_
}_x000D_
// Draw loop at 60FPS._x000D_
setInterval(draw, 1000/60);_x000D_
_x000D_
canvas.onwheel = function (event){_x000D_
event.preventDefault();_x000D_
// Get mouse offset._x000D_
var mousex = event.clientX - canvas.offsetLeft;_x000D_
var mousey = event.clientY - canvas.offsetTop;_x000D_
// Normalize wheel to +1 or -1._x000D_
var wheel = event.deltaY < 0 ? 1 : -1;_x000D_
_x000D_
// Compute zoom factor._x000D_
var zoom = Math.exp(wheel*zoomIntensity);_x000D_
_x000D_
// Translate so the visible origin is at the context's origin._x000D_
context.translate(originx, originy);_x000D_
_x000D_
// Compute the new visible origin. Originally the mouse is at a_x000D_
// distance mouse/scale from the corner, we want the point under_x000D_
// the mouse to remain in the same place after the zoom, but this_x000D_
// is at mouse/new_scale away from the corner. Therefore we need to_x000D_
// shift the origin (coordinates of the corner) to account for this._x000D_
originx -= mousex/(scale*zoom) - mousex/scale;_x000D_
originy -= mousey/(scale*zoom) - mousey/scale;_x000D_
_x000D_
// Scale it (centered around the origin due to the trasnslate above)._x000D_
context.scale(zoom, zoom);_x000D_
// Offset the visible origin to it's proper position._x000D_
context.translate(-originx, -originy);_x000D_
_x000D_
// Update scale and others._x000D_
scale *= zoom;_x000D_
visibleWidth = width / scale;_x000D_
visibleHeight = height / scale;_x000D_
}
_x000D_
<canvas id="canvas" width="600" height="200"></canvas>
_x000D_
The key, as @Tatarize pointed out, is to compute the axis position such that the zoom point (mouse pointer) remains in the same place after the zoom.
Originally the mouse is at a distance mouse/scale
from the corner, we want the point under the mouse to remain in the same place after the zoom, but this is at mouse/new_scale
away from the corner. Therefore we need to shift the origin
(coordinates of the corner) to account for this.
originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;
scale *= zoom
The remaining code then needs to apply the scaling and translate to the draw context so it's origin coincides with the canvas corner.
I had the same issue with pip 1.5.6.
I just deleted the ~/.pip folder and it worked like a charm.
rm -r ~/.pip/
temp = bankAccNos.contains(no) ? 1 : 2;
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the main()
of this class where your program starts.
By init()
, I assume you mean the JApplet method. When an applet is launched in the browser, the init()
method of the specified applet is executed as the first order of business.
By run()
, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
If Eclipse is running your run()
method even though you have no main()
, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.
There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.
PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.
There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.
You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.
Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!
At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.
In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!
Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?>
on your site and look for the Server API
entry. This could say something like CGI/FastCGI
or Apache 2.0 Handler
.
If you also look at the command-line version of PHP -- thread safety does not matter.
Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!
Swift 3 compatible
// MARK: - UIDevice Extension -
private let DeviceList = [
/* iPod 5 */ "iPod5,1": "iPod Touch 5",
/* iPhone 4 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4",
/* iPhone 4S */ "iPhone4,1": "iPhone 4S",
/* iPhone 5 */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5",
/* iPhone 5C */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C",
/* iPhone 5S */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S",
/* iPhone 6 */ "iPhone7,2": "iPhone 6",
/* iPhone 6 Plus */ "iPhone7,1": "iPhone 6 Plus",
/* iPhone 6S */ "iPhone8,1": "iPhone 6S",
/* iPhone 6S Plus */ "iPhone8,2": "iPhone 6S Plus",
/* iPhone SE */ "iPhone8,4": "iPhone SE",
/* iPhone 7 */ "iPhone9,1": "iPhone 7",
/* iPhone 7 */ "iPhone9,3": "iPhone 7",
/* iPhone 7 Plus */ "iPhone9,2": "iPhone 7 Plus",
/* iPhone 7 Plus */ "iPhone9,4": "iPhone 7 Plus",
/* iPad 2 */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2",
/* iPad 3 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3",
/* iPad 4 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4",
/* iPad Air */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air",
/* iPad Air 2 */ "iPad5,1": "iPad Air 2", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2",
/* iPad Mini */ "iPad2,5": "iPad Mini 1", "iPad2,6": "iPad Mini 1", "iPad2,7": "iPad Mini 1",
/* iPad Mini 2 */ "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2",
/* iPad Mini 3 */ "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3",
/* iPad Pro 12.9 */ "iPad6,7": "iPad Pro 12.9", "iPad6,8": "iPad Pro 12.9",
/* iPad Pro 9.7 */ "iPad6,3": "iPad Pro 9.7", "iPad6,4": "iPad Pro 9.7",
/* Simulator */ "x86_64": "Simulator", "i386": "Simulator"
]
extension UIDevice {
static var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machine = systemInfo.machine
let mirror = Mirror(reflecting: machine)
var identifier = ""
for child in mirror.children {
if let value = child.value as? Int8, value != 0 {
identifier += String(UnicodeScalar(UInt8(value)))
}
}
return DeviceList[identifier] ?? identifier
}
static var isIphone4: Bool {
return modelName == "iPhone 5" || modelName == "iPhone 5C" || modelName == "iPhone 5S" || UIDevice.isSimulatorIPhone4
}
static var isIphone5: Bool {
return modelName == "iPhone 4S" || modelName == "iPhone 4" || UIDevice.isSimulatorIPhone5
}
static var isIphone6: Bool {
return modelName == "iPhone 6" || UIDevice.isSimulatorIPhone6
}
static var isIphone6Plus: Bool {
return modelName == "iPhone 6 Plus" || UIDevice.isSimulatorIPhone6Plus
}
static var isIpad: Bool {
if UIDevice.current.model.contains("iPad") {
return true
}
return false
}
static var isIphone: Bool {
return !self.isIpad
}
/// Check if current device is iPhone4S (and earlier) relying on screen heigth
static var isSimulatorIPhone4: Bool {
return UIDevice.isSimulatorWithScreenHeigth(480)
}
/// Check if current device is iPhone5 relying on screen heigth
static var isSimulatorIPhone5: Bool {
return UIDevice.isSimulatorWithScreenHeigth(568)
}
/// Check if current device is iPhone6 relying on screen heigth
static var isSimulatorIPhone6: Bool {
return UIDevice.isSimulatorWithScreenHeigth(667)
}
/// Check if current device is iPhone6 Plus relying on screen heigth
static var isSimulatorIPhone6Plus: Bool {
return UIDevice.isSimulatorWithScreenHeigth(736)
}
private static func isSimulatorWithScreenHeigth(_ heigth: CGFloat) -> Bool {
let screenSize: CGRect = UIScreen.main.bounds
return modelName == "Simulator" && screenSize.height == heigth
}
}
It will take some work, but is certainly not impossible.
What I have done is:
Microsoft.CSharp.CSharpCodeProvider
(CompileAssemblyFromSource)Activator.CreateInstance
)This way you can deal with the C# code you already know, instead of having to emit MSIL.
But this works best if your class implements some interface (or is derived from some baseclass), else how is the calling code (read: compiler) to know about that class that will be generated at runtime?
@media screen and (max-width: 767px) {
}
@media screen and (min-width: 768px) and (max-width: 991px){
}
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape){
}
@media screen and (min-width: 992px) {
}
This should help -
var json = "{'@STARTDATE': '2016-02-17 00:00:00.000', '@ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["@STARTDATE"];
The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:
class PetStore: public Farm
{
public :
PetStore()
: Farm() // <---- Call base-class constructor in initialision list
{
idF=0;
};
private:
int idF;
string nameF;
}
Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.
You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.
If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.
Update: comment from Nick Westgate in nice formatting
The steps are not all that intuitive:
- Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
- In the Connect to Server dialog change Server type to SQL Server Compact Edition
- From the Database file dropdown select < Browse for more...>
- Open your SDF file.
user334291's answer was a life saver for me. Just want to add how you can add what the OP originally intended to do (what I ended up using):
Overriding the GetWebRequest function on the generated webservice code:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.WebRequest request = base.GetWebRequest(uri);
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(this.Credentials.GetCredential(uri, "Basic").UserName + ":" + this.Credentials.GetCredential(uri, "Basic").Password));
request.Headers.Add("Authorization", auth);
return request;
}
and setting the credentials before calling the webservice:
client.Credentials = new NetworkCredential(user, password);
componentWillMount(){
document.addEventListener('mousedown', this.handleClickOutside)
}
handleClickOutside(event) {
if(event.path[0].id !== 'your-button'){
this.setState({showWhatever: false})
}
}
Event path[0]
is the last item clicked
function getType(entity){
var x = Object.prototype.toString.call(entity)
return x.split(" ")[1].split(']')[0].toLowerCase()
}
function checkType(entity, type){
return getType(entity) === type
}
You need to assign the result back to $content
as preg_replace
does not modify the original string.
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
You urls are not in the same repository, so you can't do it with the svn diff
command.
svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'
Another way you could do it, is export each repos using svn export
, and then use the diff command to compare the 2 directories you exported.
// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2
// Compare exported directories
diff repos1 repos2 > file.diff
That helped me with my code.
When I tried feltering only a type of files and show them on screen by adding a condition that tests on each line.
Like this
elif command == 'ls':
print("directory of ", ftp.pwd())
data = []
ftp.dir(data.append)
for line in data:
x = line.split(".")
formats=["gz", "zip", "rar", "tar", "bz2", "xz"]
if x[-1] in formats:
print ("-", line)
Hi we can use ToLower Method sometimes it is not filter.
EmployeeId = Session["EmployeeID"].ToString();
var rows = dtCrewList.AsEnumerable().Where
(row => row.Field<string>("EmployeeId").ToLower()== EmployeeId.ToLower());
if (rows.Any())
{
tblFiltered = rows.CopyToDataTable<DataRow>();
}
When I instantiate a promise, I'm going to generate an asynchronous function. If the function goes well then I call the RESOLVE then the flow continues in the RESOLVE handler, in the THEN. If the function fails, then terminate the function by calling REJECT then the flow continues in the CATCH.
In NodeJs are deprecated the rejection handler. Your error is just a warning and I read it inside node.js github. I found this.
DEP0018: Unhandled promise rejections
Type: Runtime
Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
You are looking for System.Reflection.Assembly.GetExecutingAssembly()
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
Note:
The .Location
property returns the location of the currently running DLL file.
Under some conditions the DLL is shadow copied before execution, and the .Location
property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase
property instead.
.CodeBase
contains a prefix (file:\
), which you may need to remove.
the OOP way to do this in ES5 is to make that variable into a property using the this keyword.
function first(){
this.nameContent=document.getElementById('full_name').value;
}
function second() {
y=new first();
alert(y.nameContent);
}
Map is the static type of map, while HashMap is the dynamic type of map. This means that the compiler will treat your map object as being one of type Map, even though at runtime, it may point to any subtype of it.
This practice of programming against interfaces instead of implementations has the added benefit of remaining flexible: You can for instance replace the dynamic type of map at runtime, as long as it is a subtype of Map (e.g. LinkedHashMap), and change the map's behavior on the fly.
A good rule of thumb is to remain as abstract as possible on the API level: If for instance a method you are programming must work on maps, then it's sufficient to declare a parameter as Map instead of the stricter (because less abstract) HashMap type. That way, the consumer of your API can be flexible about what kind of Map implementation they want to pass to your method.
Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).
<div class="container">
<div class="row">
<div class="col-3 col-md-6">
<div class="card card-block">1</div>
</div>
<div class="col-6 col-md-12 flex-md-last">
<div class="card card-block">3</div>
</div>
<div class="col-3 col-md-6 ">
<div class="card card-block">2</div>
</div>
</div>
Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
How about:
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(rowNumber)], withRowAnimation: UITableViewRowAnimation.Top)
Yes, this is possible by using worksheet events:
In the Visual Basic Editor open the worksheet you're interested in (i.e. "BigBoard") by double clicking on the name of the worksheet in the tree at the top left. Place the following code in the module:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Me.Range("D2")) Is Nothing Then Exit Sub
Application.EnableEvents = False 'to prevent endless loop
On Error Goto Finalize 'to re-enable the events
MsgBox "You changed THE CELL!"
End If
Finalize:
Application.EnableEvents = True
End Sub
I got this error in a fresh Rails app with bundle correctly installed. Commenting out the spring gem in Gemfile resolved the problem.
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.
=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))
or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.
=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")
in earlier versions you need to repeat the VLOOKUP, e.g.
=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
In BufferedInputStream‘s source you will find: private static int DEFAULT_BUFFER_SIZE = 8192;
So it's okey for you to use that default value.
But if you can figure out some more information you will get more valueable answers.
For example, your adsl maybe preffer a buffer of 1454 bytes, thats because TCP/IP's payload. For disks, you may use a value that match your disk's block size.
I loaded the scripts asynchronously (html 5 has that feature) when all the scripts where done loading I redirected the page to index2.html where index2.html uses the same libraries. Because browsers have a cache once the page redirects to index2.html, index2.html loads in less than a second because it has all it needs to load the page. In my index.html page I also load the images that I plan on using so that the browser place those images on the cache. so my index.html looks like:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Project Management</title>
<!-- the purpose of this page is to load all the scripts on the browsers cache so that pages can load fast from now on -->
<script type="text/javascript">
function stylesheet(url) {
var s = document.createElement('link');
s.type = 'text/css';
s.async = true;
s.src = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
}
function script(url) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
}
//load scritps to the catche of browser
(function () {
stylesheet('css/custom-theme/jquery-ui-1.8.16.custom.css');
stylesheet('css/main.css');
stylesheet('css/marquee.css');
stylesheet('css/mainTable.css');
script('js/jquery-ui-1.8.16.custom.min.js');
script('js/jquery-1.6.2.min.js');
script('js/myFunctions.js');
script('js/farinspace/jquery.imgpreload.min.js');
script('js/marquee.js');
})();
</script>
<script type="text/javascript">
// once the page is loaded go to index2.html
window.onload = function () {
document.location = "index2.html";
}
</script>
</head>
<body>
<div id="cover" style="position:fixed; left:0px; top:0px; width:100%; height:100%; background-color:Black; z-index:100;">Loading</div>
<img src="images/home/background.png" />
<img src="images/home/3.png"/>
<img src="images/home/6.jpg"/>
<img src="images/home/4.png"/>
<img src="images/home/5.png"/>
<img src="images/home/8.jpg"/>
<img src="images/home/9.jpg"/>
<img src="images/logo.png"/>
<img src="images/logo.png"/>
<img src="images/theme/contentBorder.png"/>
</body>
</html>
another nice thing about this is that I may place a loader in the page and when the page is done loading the loader will go away and in a matte of milliseconds the new page will be running.
I also had to update the version of Tomcat I was using from Tomcat 7 to Tomcat 8.
You need to do some escaping I think.
find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i {} \-sameq {}.mp3 \&\& rm {}\;
My solution was to hide the badge, then display it when the user focuses on a form input - thus still adhering to Google's T&Cs.
Note: The reCAPTCHA I was tweaking had been generated by a WordPress plugin, so you may need to wrap the reCAPTCHA with a <div class="inv-recaptcha-holder"> ... </div>
yourself.
CSS
.inv-recaptcha-holder {
visibility: hidden;
opacity: 0;
transition: linear opacity 1s;
}
.inv-recaptcha-holder.show {
visibility: visible;
opacity: 1;
transition: linear opacity 1s;
}
jQuery
$(document).ready(function () {
$('form input, form textarea').on( 'focus', function() {
$('.inv-recaptcha-holder').addClass( 'show' );
});
});
Obviously you can change the jQuery selector to target specific forms if necessary.
$row = 1;
$arrResult = array();
if (($handle = fopen("ifsc_code.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
DB::table('banks')->insert(
array('bank_name' => $data[1], 'ifsc' => $data[2], 'micr' => $data[3], 'branch_name' => $data[4],'address' => $data[5], 'contact' => $data[6], 'city' => $data[7],'district' => $data[8],'state' => $data[9])
);
}
fclose($handle);
}
@Ryan Cavanaugh's answer is totally ok and still valid. Still it worth to add that as of Fall'16 when we can claim that ES6 is supported by the majority of platforms it almost always better to stick to Map whenever you need associate some data with some key.
When we write let a: { [s: string]: string; }
we need to remember that after typescript compiled there's not such thing like type data, it's only used for compiling. And { [s: string]: string; } will compile to just {}.
That said, even if you'll write something like:
class TrickyKey {}
let dict: {[key:TrickyKey]: string} = {}
This just won't compile (even for target es6
, you'll get error TS1023: An index signature parameter type must be 'string' or 'number'.
So practically you are limited with string or number as potential key so there's not that much of a sense of enforcing type check here, especially keeping in mind that when js tries to access key by number it converts it to string.
So it is quite safe to assume that best practice is to use Map even if keys are string, so I'd stick with:
let staff: Map<string, string> = new Map();
Some modifications were made on posted answer UnderWaterKremlin to make it python3 proof. A surprising result below as answer.
System specs:
import timeit
d = {x: x**2 for x in range(1000)}
#print (d)
print (len(d))
# 1000
print (len(d.keys()))
# 1000
print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000)) # 1
print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2
Result:
1) = 37.0100378
2) = 37.002148899999995
So it seems that len(d.keys())
is currently faster than just using len()
.
here's one way you can do it with awk
curl -sL 'http://twitter.com/users/username.json' | awk -F"," -v k="text" '{
gsub(/{|}/,"")
for(i=1;i<=NF;i++){
if ( $i ~ k ){
print $i
}
}
}'
As mentioned in a comment above, you can have expressions within the template strings/literals. Example:
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
alternative way:
mail -N
d *
quit
-N
Inhibits the initial display of message headers when reading mail or editing a mail folder.
d *
delete all mails
The easiest way I thought of was to just project the point onto the axis of the rectangle. Let me explain:
If you can get the vector from the center of the rectangle to the top or bottom edge and the left or right edge. And you also have a vector from the center of the rectangle to your point, you can project that point onto your width and height vectors.
P = point vector, H = height vector, W = width vector
Get Unit vector W', H' by dividing the vectors by their magnitude
proj_P,H = P - (P.H')H' proj_P,W = P - (P.W')W'
Unless im mistaken, which I don't think I am... (Correct me if I'm wrong) but if the magnitude of the projection of your point on the height vector is less then the magnitude of the height vector (which is half of the height of the rectangle) and the magnitude of the projection of your point on the width vector is, then you have a point inside of your rectangle.
If you have a universal coordinate system, you might have to figure out the height/width/point vectors using vector subtraction. Vector projections are amazing! remember that.
Often you want to pass a viewmodel also, and not the only one file. In the code below you'll find some other useful features:
It could be done via the following code:
[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
// if file's content length is zero or no files submitted
if (Request.Files.Count != 1 || Request.Files[0].ContentLength == 0)
{
ModelState.AddModelError("uploadError", "File's length is zero, or no files found");
return View(viewModel);
}
// check the file size (max 4 Mb)
if (Request.Files[0].ContentLength > 1024 * 1024 * 4)
{
ModelState.AddModelError("uploadError", "File size can't exceed 4 MB");
return View(viewModel);
}
// check the file size (min 100 bytes)
if (Request.Files[0].ContentLength < 100)
{
ModelState.AddModelError("uploadError", "File size is too small");
return View(viewModel);
}
// check file extension
string extension = Path.GetExtension(Request.Files[0].FileName).ToLower();
if (extension != ".pdf" && extension != ".doc" && extension != ".docx" && extension != ".rtf" && extension != ".txt")
{
ModelState.AddModelError("uploadError", "Supported file extensions: pdf, doc, docx, rtf, txt");
return View(viewModel);
}
// extract only the filename
var fileName = Path.GetFileName(Request.Files[0].FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
try
{
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
Request.Files[0].SaveAs(path);
}
catch (Exception)
{
ModelState.AddModelError("uploadError", "Can't save file to disk");
}
if(ModelState.IsValid)
{
// put your logic here
return View("Success");
}
return View(viewModel);
}
Make sure you have
@Html.ValidationMessage("uploadError")
in your view for validation errors.
Also keep in mind that default maximum request length is 4MB (maxRequestLength = 4096), to upload larger files you have to change this parameter in web.config:
<system.web>
<httpRuntime maxRequestLength="40960" executionTimeout="1100" />
(40960 = 40 MB here).
Execution timeout is the whole number of seconds. You may want to change it to allow huge files uploads.
You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.
Use package str2bool pip install str2bool
For Oracle:
select EXTRACT(month from DATE_CREATED), sum(Num_of_Pictures)
from pictures_table
group by EXTRACT(month from DATE_CREATED);
break causes the program counter to jump out of the scope of the innermost loop
for(i = 0; i < 10; i++)
{
if(i == 2)
break;
}
Works like this
for(i = 0; i < 10; i++)
{
if(i == 2)
goto BREAK;
}
BREAK:;
continue jumps to the end of the loop. In a for loop, continue jumps to the increment expression.
for(i = 0; i < 10; i++)
{
if(i == 2)
continue;
printf("%d", i);
}
Works like this
for(i = 0; i < 10; i++)
{
if(i == 2)
goto CONTINUE;
printf("%d", i);
CONTINUE:;
}
React uses event delegation with a single event listener on document
for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation
on React's synthetic event is possible because React handles propagation of synthetic events internally.
Use Event.stopImmediatePropagation
to prevent your other (jQuery in this case) listeners on the root from being called. It is supported in IE9+ and modern browsers.
stopPropagation: function(e){
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
},
Your jQuery code uses event delegation as well, which means calling stopPropagation
in the handler is not stopping anything; the event has already propagated to document
, and React's listener will be triggered.
// Listener bound to `document`, event delegation
$(document).on('click', '.stop-propagation', function(e){
e.stopPropagation();
});
To prevent propagation beyond the element, the listener must be bound to the element itself:
// Listener bound to `.stop-propagation`, no delegation
$('.stop-propagation').on('click', function(e){
e.stopPropagation();
});
Edit (2016/01/14): Clarified that delegation is necessarily only used for events that bubble. For more details on event handling, React's source has descriptive comments: ReactBrowserEventEmitter.js.
puts 'abcdefg'.start_with?('abc') #=> true
[edit] This is something I didn't know before this question: start_with
takes multiple arguments.
'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
I had this error with MySQL as my database and the only solution was reinstall all components of MySQL, because before I installed just the server.
So try to download other versions of PostgreSQL and get all the components
Don't use height property in input field.
Example:
.heighttext{
display:inline-block;
padding:15px 10px;
line-height:140%;
}
Always use padding and line-height css property. Its work perfect for all mobile device and all browser.
Angular Concepts
imports
makes the exported declarations of other modules available in the current moduledeclarations
are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.providers
are to make services and values known to DI (dependency injection). They are added to the root scope and they are injected to other services or directives that have them as dependency.A special case for providers
are lazy loaded modules that get their own child injector. providers
of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).
For more details about modules see also https://angular.io/docs/ts/latest/guide/ngmodule.html
exports
makes the components, directives, and pipes available in modules that add this module to imports
. exports
can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.
entryComponents
registers components for offline compilation so that they can be used with ViewContainerRef.createComponent()
. Components used in router configurations are added implicitly.
TypeScript (ES2015) imports
import ... from 'foo/bar'
(which may resolve to an index.ts
) are for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.
Angular's @NgModule()
imports
and TypeScript import
are entirely different concepts.
See also jDriven - TypeScript and ES6 import syntax
Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.
first convert your date string to date
then convert it to timestamp
by using following set of line
Date date=new Date();
Timestamp timestamp = new Timestamp(date.getTime());//instead of date put your converted date
Timestamp myTimeStamp= timestamp;
Need to use this way I have used this one and it's working fine.
react-native-responsive-screen npm install react-native-responsive-screen --save
Just like I have a device 1080x1920
The vertical number we calculate from height **hp**
height:200
200/1920*100 = 10.41% - height:hp("10.41%")
The Horizontal number we calculate from width **wp**
width:200
200/1080*100 = 18.51% - Width:wp("18.51%")
It's working for all device
filter(lambda v: v==v, x)
works both for lists and numpy array since v!=v only for NaN
On almost every system I've met uint8_t == unsigned char, but this is not guaranteed by the C standard. If you are trying to write portable code and it matters exactly what size the memory is, use uint8_t. Otherwise use unsigned char.
In my case the window was also missing and "View -> ToolWindows -> Logcat (Alt + 6)" did not even exist. Pressing ALT+6 also had absolutely no effect whatsoever.
I fixed it this way:
After closing the terminal the Logcat window appeared in the tab list and the menu entry appeared in the "View -> ToolWindows" category.
Another option is:
SELECT *
FROM TABLE
WHERE EXTRACT( YEAR FROM date_field) = EXTRACT(YEAR FROM sysdate)
order
is an Object
, not an Array()
.
push()
is for arrays.
Refer to this post
Try this though(but your subobjects have to be Arrays()
):
var order = new Array();
// initialize order; n = index
order[n] = new Array();
// and then you can perform push()
order[n].push(some_value);
Or you can just use order as an array of non-array objects:
var order = new Array();
order.push(a[n]);
I claimed 3.5gb space in ubuntu AWS through this.
clean docker
docker stop $(docker ps -qa) && docker system prune -af --volumes
build again
docker build .
docker-compose build
docker-compose up
If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).
threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).
Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).
Suppose we want one thread to process one pixel (i,j).
We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)
It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.
dim3 threadsPerBlock(8, 8); // 64 threads
and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.
dim3 numBlocks(imageWidth/threadsPerBlock.x, /* for instance 512/8 = 64*/
imageHeight/threadsPerBlock.y);
The kernel is launched like this:
myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );
Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.
In the kernel the pixel (i,j) to be processed by a thread is calculated this way:
uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;
Please make sure you have downloaded the sqldump fully, this problem is very common when we try to import half/incomplete downloaded sqldump. Please check size of your sqldump file.
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(7, 10, 5, 10);
}
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
https://github.com/ko1nksm/getoptions
getoptions is a new option parser (generator) written in POSIX-compliant shell script and released in august 2020. It is for those who want to support the standard option syntax in shell scripts without bashisms. The supported syntaxes are -a
, +a
, -abc
, -vvv
, -p VALUE
, -pVALUE
, --flag
, --no-flag
, --param VALUE
, --param=VALUE
, --option[=VALUE]
, --no-option
--
.
It supports subcommands, validation, abbreviated options, and automatic help generation. and works with most OS (Linux, macOS, BSD, Windows, etc) and all POSIX shells (dash, bash, ksh, zsh, etc).
#!/bin/sh
. ./lib/getoptions.sh
. ./lib/getoptions_help.sh
parser_definition() {
setup REST help:usage -- "Usage: ${2##*/} [options] [arguments]" ''
flag FLAG -f --flag -- "--flag option"
param PARAM -p --param -- "--param option"
option OPTION -o --option on:"default" -- "--option option"
disp :usage -h --help
disp VERSION --version
}
eval "$(getoptions parser_definition parse "$0")"
parse "$@"
eval "set -- $REST"
echo "FLAG: $FLAG"
echo "PARAM: $PARAM"
echo "OPTION: $OPTION"
printf ': %s\n' "$@" # Rest arguments
It is also an option parser generator, generates the following option parsing code.
FLAG=''
PARAM=''
OPTION=''
REST=''
parse() {
OPTIND=$(($#+1))
while OPTARG= && [ $# -gt 0 ]; do
case $1 in
--?*=*) OPTARG=$1; shift
eval 'set -- "${OPTARG%%\=*}" "${OPTARG#*\=}"' ${1+'"$@"'}
;;
--no-*) unset OPTARG ;;
-[po]?*) OPTARG=$1; shift
eval 'set -- "${OPTARG%"${OPTARG#??}"}" "${OPTARG#??}"' ${1+'"$@"'}
;;
-[!-]?*) OPTARG=$1; shift
eval 'set -- "${OPTARG%"${OPTARG#??}"}" "-${OPTARG#??}"' ${1+'"$@"'}
OPTARG= ;;
esac
case $1 in
-f | --flag)
[ "${OPTARG:-}" ] && OPTARG=${OPTARG#*\=} && set -- noarg "$1" && break
eval '[ ${OPTARG+x} ] &&:' && OPTARG='1' || OPTARG=''
FLAG="$OPTARG"
;;
-p | --param)
[ $# -le 1 ] && set -- required "$1" && break
OPTARG=$2
PARAM="$OPTARG"
shift ;;
-o | --option)
set -- "$1" "$@"
[ ${OPTARG+x} ] && {
case $1 in --no-*) set -- noarg "${1%%\=*}"; break; esac
[ "${OPTARG:-}" ] && { shift; OPTARG=$2; } || OPTARG='default'
} || OPTARG=''
OPTION="$OPTARG"
shift ;;
-h | --help)
usage
exit 0 ;;
--version)
echo "${VERSION}"
exit 0 ;;
--) shift
while [ $# -gt 0 ]; do
REST="${REST} \"\${$((${OPTIND:-0}-$#))}\""
shift
done
break ;;
[-]?*) set -- unknown "$1" && break ;;
*) REST="${REST} \"\${$((${OPTIND:-0}-$#))}\""
esac
shift
done
[ $# -eq 0 ] && { OPTIND=1; unset OPTARG; return 0; }
case $1 in
unknown) set -- "Unrecognized option: $2" "$@" ;;
noarg) set -- "Does not allow an argument: $2" "$@" ;;
required) set -- "Requires an argument: $2" "$@" ;;
pattern:*) set -- "Does not match the pattern (${1#*:}): $2" "$@" ;;
*) set -- "Validation error ($1): $2" "$@"
esac
echo "$1" >&2
exit 1
}
usage() {
cat<<'GETOPTIONSHERE'
Usage: example.sh [options] [arguments]
-f, --flag --flag option
-p, --param PARAM --param option
-o, --option[=OPTION] --option option
-h, --help
--version
GETOPTIONSHERE
}
There are two related error messages that may tell you something is wrong with declarations and/or imports.
The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.
The second you might see, if you had a method in your States class like:
- (void)logout:(NSTimer *)timer
after adding the #import is this:
No visible @interface for "States" declares the selector 'logout:'
If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.
So in your case, you would need a:
- (void)logout:(NSTimer *)timer;
in your States class's .h to make one or both of these related errors disappear.
I have faced this issue and I just removed the server from eclipse and re-configured it... And everything started working fine... I have faced it two three times and the same thing worked.
I found the following approach to be the most effective for sampling a DataFrame:
print(df[A:B]) ## 'A' and 'B' are the first and last records in range
For example, print(df[10:15])
will print rows 10 through 15 - inclusive - from your data set.
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
Thanks to nrathaus and /var/log/auth.log
investigation on debug level comes the following.
Another reason is that your home directory may have permissions different than 755.
From the docs
Reduction operations A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, called reduce() and collect(), as well as multiple specialized reduction forms such as sum(), max(), or count().
Of course, such operations can be readily implemented as simple sequential loops, as in:
int sum = 0; for (int x : numbers) { sum += x; }
However, there are good reasons to prefer a reduce operation over a mutative accumulation such as the above. Not only is a reduction "more abstract" -- it operates on the stream as a whole rather than individual elements -- but a properly constructed reduce operation is inherently parallelizable, so long as the function(s) used to process the elements are associative and stateless. For example, given a stream of numbers for which we want to find the sum, we can write:
int sum = numbers.stream().reduce(0, (x,y) -> x+y);
or:
int sum = numbers.stream().reduce(0, Integer::sum);
These reduction operations can run safely in parallel with almost no modification:
int sum = numbers.parallelStream().reduce(0, Integer::sum);
So, for a map you would use:
integers.values().stream().mapToInt(i -> i).reduce(0, (x,y) -> x+y);
Or:
integers.values().stream().reduce(0, Integer::sum);
If you can support it CSS Grid is probably the cleanest way for making a one-dimensional list into a two column layout with responsive interiors.
ul {_x000D_
max-width: 400px;_x000D_
display: grid;_x000D_
grid-template-columns: 50% 50%;_x000D_
padding-left: 0;_x000D_
border: 1px solid blue;_x000D_
}_x000D_
_x000D_
li {_x000D_
list-style: inside;_x000D_
border: 1px dashed red;_x000D_
padding: 10px;_x000D_
}
_x000D_
<ul>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
<li>6</li>_x000D_
<li>7</li>_x000D_
<li>8</li>_x000D_
<li>9</li>_x000D_
<ul>
_x000D_
These are the two key lines which will give you your 2 column layout
display: grid;
grid-template-columns: 50% 50%;
A while ago i wrote a detailed article about Hibernate key generators: http://blog.eyallupu.com/2011/01/hibernatejpa-identity-generators.html
Choosing the correct generator is a complicated task but it is important to try and get it right as soon as possible - a late migration might be a nightmare.
A little off topic but a good chance to raise a point usually overlooked which is sharing keys between applications (via API). Personally I always prefer surrogate keys and if I need to communicate my objects with other systems I don't expose my key (even though it is a surrogate one) – I use an additional ‘external key’. As a consultant I have seen more than once 'great' system integrations using object keys (the 'it is there let's just use it' approach) just to find a year or two later that one side has issues with the key range or something of the kind requiring a deep migration on the system exposing its internal keys. Exposing your key means exposing a fundamental aspect of your code to external constrains shouldn’t really be exposed to.
You just need to make it mutable:
StringBuilder
unsafe
world and play with pointers (dangerous though)and try to iterate through the array of characters the least amount of times. Note the HashSet
here, as it avoids to traverse the character sequence inside the loop. Should you need an even faster lookup, you can replace HashSet
by an optimized lookup for char
(based on an array[256]
).
Example with StringBuilder
public static void MultiReplace(this StringBuilder builder,
char[] toReplace,
char replacement)
{
HashSet<char> set = new HashSet<char>(toReplace);
for (int i = 0; i < builder.Length; ++i)
{
var currentCharacter = builder[i];
if (set.Contains(currentCharacter))
{
builder[i] = replacement;
}
}
}
Edit - Optimized version
public static void MultiReplace(this StringBuilder builder,
char[] toReplace,
char replacement)
{
var set = new bool[256];
foreach (var charToReplace in toReplace)
{
set[charToReplace] = true;
}
for (int i = 0; i < builder.Length; ++i)
{
var currentCharacter = builder[i];
if (set[currentCharacter])
{
builder[i] = replacement;
}
}
}
Then you just use it like this:
var builder = new StringBuilder("my bad,url&slugs");
builder.MultiReplace(new []{' ', '&', ','}, '-');
var result = builder.ToString();
You could use addEventListener to add as many listeners as you want.
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
Also add script
tag after the element to make sure Save
element is loaded at the time when script runs
Rather than moving script tag you could call it when dom is loaded. Then you should place your code inside the
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
});
Combining the regex for the fourth option with any of the others doesn't work within one regex. 4 + 1 would mean either the string starts with @ or doesn't contain @ at all. You're going to need two separate comparisons to do that.
As of Swift 2.0, you can add a protocol extension. In my opinion, this is a better approach because the return type is Self
rather than UIView
, so the caller doesn't need to cast to the view class.
import UIKit
protocol UIViewLoading {}
extension UIView : UIViewLoading {}
extension UIViewLoading where Self : UIView {
// note that this method returns an instance of type `Self`, rather than UIView
static func loadFromNib() -> Self {
let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
let nib = UINib(nibName: nibName, bundle: nil)
return nib.instantiateWithOwner(self, options: nil).first as! Self
}
}
I installed and deinstalled ajdt-plugin and got the same problem.
Check <Project><Properties><Builders>
.
It should have a 'Java Builder'.
This code should be in the .project file (file is in the root of your project):
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
instead of using the ==
sign, more safer use the ===
sign when compare, the code that you post is work well
In the init.py of the settings directory write the correct import, like:
from Project.settings.base import *
No need to change wsgi.py or manage.py
I've done a bit of development for S3 and I have not found a simple way to download a whole bucket.
If you want to code in Java the jets3t lib is easy to use to create a list of buckets and iterate over that list to download them.
First, get a public private key set from the AWS management consule so you can create an S3service object:
AWSCredentials awsCredentials = new AWSCredentials(YourAccessKey, YourAwsSecretKey);
s3Service = new RestS3Service(awsCredentials);
Then, get an array of your buckets objects:
S3Object[] objects = s3Service.listObjects(YourBucketNameString);
Finally, iterate over that array to download the objects one at a time with:
S3Object obj = s3Service.getObject(bucket, fileName);
file = obj.getDataInputStream();
I put the connection code in a threadsafe singleton. The necessary try/catch syntax has been omitted for obvious reasons.
If you'd rather code in Python you could use Boto instead.
After looking around BucketExplorer, "Downloading the whole bucket" may do what you want.
If you are using Spring JDBC, you can use Spring's GeneratedKeyHolder class to get the inserted ID.
See this answer... How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)
"They have the same effect. However, XHTML, a cleaner, newer version of HTML, recommends the use of the <strong>
tag. Strong is better because it is easier to read - its meaning is clearer. Additionally, <strong>
conveys a meaning - showing the text strongly - while <b>
(for bold) conveys a method - bolding the text. With strong, your code still makes sense if you use CSS stylesheets to change what the methods of making the text strong is.
The same goes for the difference between <i>
and <em>
".
Google dixit:
http://wiki.answers.com/Q/What_is_the_difference_between_HTML_tags_b_and_strong
rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.
You cannot cast an int to a char* to get a string. Try this:
std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();
In C# this is how to get the resolution Screen:
button click or form load:
string screenWidth = Screen.PrimaryScreen.Bounds.Width.ToString();
string screenHeight = Screen.PrimaryScreen.Bounds.Height.ToString();
Label1.Text = ("Resolution: " + screenWidth + "x" + screenHeight);
I just got this after creating a new Objective-C project in Xcode 10, after I added a Core Data model file to the project.
I found two ways to fix this:
The model contains a "contents" file with this line:
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="14460.32" systemVersion="17G5019" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
In there is a sourceLanguage="Swift"
entry. Change it to sourceLanguage="Objective-C"
and the error goes away.
To find the "contents" file, right click on the .xcdatamodeld
in Xcode and do "Show in Finder". Right-click on the actual (Finder) file and do "Show Package Contents"
Also: Changing the model's language will stop Xcode from generating managed object subclass files in Swift.
Check the generated code at MyAreaAreaRegistration.cs and make sure that the controller parameter is set to your default controller, otherwise the controller will be called bot for some reason ASP.NET MVC won't search for the views at the area folder
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"SomeArea_default",
"SomeArea/{controller}/{action}/{id}",
new { controller = "SomeController", action = "Index", id = UrlParameter.Optional }
);
}
A simple solution to the answer:
parted /dev/sda
Display the help on unit. Then toggle it to the units you want.
To show free space on the device, use:
print free
If you need to find the largest and second largest element in an existing array, see the answers above (Schwern's answer contains the approach I would've used).
However; needing to find the largest and second largest element in an existing array typically indicates a design flaw. Entire arrays don't magically appear - they come from somewhere, which means that the most efficient approach is to keep track of "current largest and current second largest" while the array is being created.
For example; for your original code the data is coming from the user; and by keeping track of "largest and second largest value that the user entered" inside of the loop that gets values from the user the overhead of tracking the information will be hidden by the time spent waiting for the user to press key/s, you no longer need to do a search afterwards while the user is waiting for results, and you no longer need an array at all.
It'd be like this:
int main() {
int largest1 = 0, largest2 = 0, i, temp;
printf("enter number of elements you want in array");
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &temp);
if(temp >= largest1) {
largest2 = largest1;
largest1 = temp;
} else if(temp > largest2) {
largest2 = temp;
}
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}
You have to use a Class
instance because of the generic type erasure during compilation.
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch(ClassCastException e) {
return null;
}
}
The declaration of that method is:
public T cast(Object o)
This can also be used for array types. It would look like this:
final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);
Note that when someObject
is passed to convertToInstanceOfObject
it has the compile time type Object
.
There are some important issues that I think all of the existing answers have missed.
Weak typing means allowing access to the underlying representation. In C, I can create a pointer to characters, then tell the compiler I want to use it as a pointer to integers:
char sz[] = "abcdefg";
int *i = (int *)sz;
On a little-endian platform with 32-bit integers, this makes i
into an array of the numbers 0x64636261
and 0x00676665
. In fact, you can even cast pointers themselves to integers (of the appropriate size):
intptr_t i = (intptr_t)&sz;
And of course this means I can overwrite memory anywhere in the system.*
char *spam = (char *)0x12345678
spam[0] = 0;
* Of course modern OS's use virtual memory and page protection so I can only overwrite my own process's memory, but there's nothing about C itself that offers such protection, as anyone who ever coded on, say, Classic Mac OS or Win16 can tell you.
Traditional Lisp allowed similar kinds of hackery; on some platforms, double-word floats and cons cells were the same type, and you could just pass one to a function expecting the other and it would "work".
Most languages today aren't quite as weak as C and Lisp were, but many of them are still somewhat leaky. For example, any OO language that has an unchecked "downcast",* that's a type leak: you're essentially telling the compiler "I know I didn't give you enough information to know this is safe, but I'm pretty sure it is," when the whole point of a type system is that the compiler always has enough information to know what's safe.
* A checked downcast doesn't make the language's type system any weaker just because it moves the check to runtime. If it did, then subtype polymorphism (aka virtual or fully-dynamic function calls) would be the same violation of the type system, and I don't think anyone wants to say that.
Very few "scripting" languages are weak in this sense. Even in Perl or Tcl, you can't take a string and just interpret its bytes as an integer.* But it's worth noting that in CPython (and similarly for many other interpreters for many languages), if you're really persistent, you can use ctypes
to load up libpython
, cast an object's id
to a POINTER(Py_Object)
, and force the type system to leak. Whether this makes the type system weak or not depends on your use cases—if you're trying to implement an in-language restricted execution sandbox to ensure security, you do have to deal with these kinds of escapes…
* You can use a function like struct.unpack
to read the bytes and build a new int out of "how C would represent these bytes", but that's obviously not leaky; even Haskell allows that.
Meanwhile, implicit conversion is really a different thing from a weak or leaky type system.
Every language, even Haskell, has functions to, say, convert an integer to a string or a float. But some languages will do some of those conversions for you automatically—e.g., in C, if you call a function that wants a float
, and you pass it in int
, it gets converted for you. This can definitely lead to bugs with, e.g., unexpected overflows, but they're not the same kinds of bugs you get from a weak type system. And C isn't really being any weaker here; you can add an int and a float in Haskell, or even concatenate a float to a string, you just have to do it more explicitly.
And with dynamic languages, this is pretty murky. There's no such thing as "a function that wants a float" in Python or Perl. But there are overloaded functions that do different things with different types, and there's a strong intuitive sense that, e.g., adding a string to something else is "a function that wants a string". In that sense, Perl, Tcl, and JavaScript appear to do a lot of implicit conversions ("a" + 1
gives you "a1"
), while Python does a lot fewer ("a" + 1
raises an exception, but 1.0 + 1
does give you 2.0
*). It's just hard to put that sense into formal terms—why shouldn't there be a +
that takes a string and an int, when there are obviously other functions, like indexing, that do?
* Actually, in modern Python, that can be explained in terms of OO subtyping, since isinstance(2, numbers.Real)
is true. I don't think there's any sense in which 2
is an instance of the string type in Perl or JavaScript… although in Tcl, it actually is, since everything is an instance of string.
Finally, there's another, completely orthogonal, definition of "strong" vs. "weak" typing, where "strong" means powerful/flexible/expressive.
For example, Haskell lets you define a type that's a number, a string, a list of this type, or a map from strings to this type, which is a perfectly way to represent anything that can be decoded from JSON. There's no way to define such a type in Java. But at least Java has parametric (generic) types, so you can write a function that takes a List of T and know that the elements are of type T; other languages, like early Java, forced you to use a List of Object and downcast. But at least Java lets you create new types with their own methods; C only lets you create structures. And BCPL didn't even have that. And so on down to assembly, where the only types are different bit lengths.
So, in that sense, Haskell's type system is stronger than modern Java's, which is stronger than earlier Java's, which is stronger than C's, which is stronger than BCPL's.
So, where does Python fit into that spectrum? That's a bit tricky. In many cases, duck typing allows you to simulate everything you can do in Haskell, and even some things you can't; sure, errors are caught at runtime instead of compile time, but they're still caught. However, there are cases where duck typing isn't sufficient. For example, in Haskell, you can tell that an empty list of ints is a list of ints, so you can decide that reducing +
over that list should return 0*; in Python, an empty list is an empty list; there's no type information to help you decide what reducing +
over it should do.
* In fact, Haskell doesn't let you do this; if you call the reduce function that doesn't take a start value on an empty list, you get an error. But its type system is powerful enough that you could make this work, and Python's isn't.
From What's this "serialization" thing all about?:
It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."
So, implement the Serializable
interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.
Because you want to store or send an object.
It makes storing and sending objects easy. It has nothing to do with security.
I coded a function (used in Django project for DecimalField) but it can be used in Python project :
This code :
Code with tests :
def convert_decimal_to_right(value, max_digits, decimal_places, signed=True):
integer_digits = max_digits - decimal_places
max_value = float((10**integer_digits)-float(float(1)/float((10**decimal_places))))
if signed:
min_value = max_value*-1
else:
min_value = 0
if value > max_value:
value = max_value
if value < min_value:
value = min_value
return round(value, decimal_places)
value = 12.12345
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.12
value = 12.126
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.13
value = 1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : 99.99
value = -1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : -99.99
value = -1234.123
nb = convert_decimal_to_right(value, 4, 2, signed = False)
# nb : 0
value = 12.123
nb = convert_decimal_to_right(value, 8, 4)
# nb : 12.123
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
bootstrap 3 has a class to align the text within a div
<div class="text-right">
will align the text on the right
<div class="pull-right">
will pull to the right all the content not only the text
It is really very disappointing that you can't do it with styles (<item name="android:textAllCaps">true</item>
) or on each XML layout file with the textAllCaps attribute, and the only way to do it is actually using theString.toUpperCase() on each of the strings when you do a textViewXXX.setText(theString).
In my case, I did not wanted to have theString.toUpperCase() everywhere in my code but to have a centralized place to do it because I had some Activities and lists items layouts with TextViews that where supposed to be capitalized all the time (a title) and other who did not... so... some people may think is an overkill, but I created my own CapitalizedTextView class extending android.widget.TextView and overrode the setText method capitalizing the text on the fly.
At least, if the design changes or I need to remove the capitalized text in future versions, I just need to change to normal TextView in the layout files.
Now, take in consideration that I did this because the App's Designer actually wanted this text (the titles) in CAPS all over the App no matter the original content capitalization, and also I had other normal TextViews where the capitalization came with the the actual content.
This is the class:
package com.realactionsoft.android.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.TextView;
public class CapitalizedTextView extends TextView implements ViewTreeObserver.OnPreDrawListener {
public CapitalizedTextView(Context context) {
super(context);
}
public CapitalizedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CapitalizedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text.toString().toUpperCase(), type);
}
}
And whenever you need to use it, just declare it with all the package in the XML layout:
<com.realactionsoft.android.widget.CapitalizedTextView
android:id="@+id/text_view_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Some will argue that the correct way to style text on a TextView is to use a SpannableString, but I think that would be even a greater overkill, not to mention more resource-consuming because you'll be instantiating another class than TextView.
First check whether the folder name is right or wrong since while you copying to one folder from other accidently it takes other folder address eg it take C
instead of F
So from OPTION>DIRECTORY
change the folder name
To go into why size_t
needed to exist and how we got here:
In pragmatic terms, size_t
and ptrdiff_t
are guaranteed to be 64 bits wide on a 64-bit implementation, 32 bits wide on a 32-bit implementation, and so on. They could not force any existing type to mean that, on every compiler, without breaking legacy code.
A size_t
or ptrdiff_t
is not necessarily the same as an intptr_t
or uintptr_t
. They were different on certain architectures that were still in use when size_t
and ptrdiff_t
were added to the Standard in the late ’80s, and becoming obsolete when C99 added many new types but not gone yet (such as 16-bit Windows). The x86 in 16-bit protected mode had a segmented memory where the largest possible array or structure could be only 65,536 bytes in size, but a far
pointer needed to be 32 bits wide, wider than the registers. On those, intptr_t
would have been 32 bits wide but size_t
and ptrdiff_t
could be 16 bits wide and fit in a register. And who knew what kind of operating system might be written in the future? In theory, the i386 architecture offers a 32-bit segmentation model with 48-bit pointers that no operating system has ever actually used.
The type of a memory offset could not be long
because far too much legacy code assumes that long
is exactly 32 bits wide. This assumption was even built into the UNIX and Windows APIs. Unfortunately, a lot of other legacy code also assumed that a long
is wide enough to hold a pointer, a file offset, the number of seconds that have elapsed since 1970, and so on. POSIX now provides a standardized way to force the latter assumption to be true instead of the former, but neither is a portable assumption to make.
It couldn’t be int
because only a tiny handful of compilers in the ’90s made int
64 bits wide. Then they really got weird by keeping long
32 bits wide. The next revision of the Standard declared it illegal for int
to be wider than long
, but int
is still 32 bits wide on most 64-bit systems.
It couldn’t be long long int
, which anyway was added later, since that was created to be at least 64 bits wide even on 32-bit systems.
So, a new type was needed. Even if it weren’t, all those other types meant something other than an offset within an array or object. And if there was one lesson from the fiasco of 32-to-64-bit migration, it was to be specific about what properties a type needed to have, and not use one that meant different things in different programs.
It means the file containing main
doesn't have access to the player
structure definition (i.e. doesn't know what it looks like).
Try including it in header.h
or make a constructor-like function that allocates it if it's to be an opaque object.
If your goal is to hide the implementation of the structure, do this in a C file that has access to the struct:
struct player *
init_player(...)
{
struct player *p = calloc(1, sizeof *p);
/* ... */
return p;
}
However if the implementation shouldn't be hidden - i.e. main
should legally say p->canPlay = 1
it would be better to put the definition of the structure in header.h
.
I’m tired of looking for free translators and the best option for me was Selenium (more precisely selenide and webdrivermanager) and https://translate.google.com
import io.github.bonigarcia.wdm.ChromeDriverManager;
import com.codeborne.selenide.Configuration;
import io.github.bonigarcia.wdm.DriverManagerType;
import static com.codeborne.selenide.Selenide.*;
public class Main {
public static void main(String[] args) throws IOException, ParseException {
ChromeDriverManager.getInstance(DriverManagerType.CHROME).version("76.0.3809.126").setup();
Configuration.startMaximized = true;
open("https://translate.google.com/?hl=ru#view=home&op=translate&sl=en&tl=ru");
String[] strings = /some strings to translate
for (String data: strings) {
$x("//textarea[@id='source']").clear();
$x("//textarea[@id='source']").sendKeys(data);
String translation = $x("//span[@class='tlid-translation translation']").getText();
}
}
}
If you have the suhosin extension enabled, it can prevent scripts from setting the memory limit beyond what it started with or some defined cap.
http://www.hardened-php.net/suhosin/configuration.html#suhosin.memory_limit
if you want to pass an entire model go like so in the layout:
@model ViewAsModelBase
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8"/>
<link href="/img/phytech_icon.ico" rel="shortcut icon" type="image/x-icon" />
<title>@ViewBag.Title</title>
@RenderSection("styles", required: false)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
@RenderSection("scripts", required: false)
@RenderSection("head", required: false)
</head>
<body>
@Html.Action("_Header","Controller", new {model = Model})
<section id="content">
@RenderBody()
</section>
@RenderSection("footer", required: false)
</body>
</html>
and add this in the controller:
public ActionResult _Header(ViewAsModelBase model)
Firstly create a new class that extends the WorldView
class. I called my new class Background
. So in this new class import all the Java packages you will need in order to override the paintBackground
method. This should be:
import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;
Next after the class name make sure that it says extends WorldView
. Something like this:
public class Background extends WorldView
Then declare the variables game of type Game
and an image variable of type Image
something like this:
private Game game;
private Image image;
Then in the constructor of this class make sure the game of type Game
is in the signature of the constructor and that in the call to super
you will have to initialise the WorldView
, initialise the game and initialise the image variables, something like this:
super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();
Then you just override the paintBackground
method in exactly the same way as you did when overriding the paint
method in the Player
class. Just like this:
public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}
Now finally you have to declare a class level reference to the new class you just made in the Game
class and initialise this in the Game
constructor, something like this:
private Background image;
And in the Game constructor:
image = new Background(this);
Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable frame
has been declared:
frame.add(image);
Make sure you add this code just before frame.pack();
.
Also make sure you use a background image that isn't too big!
Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.
A standard solution for this problem is to allow slashes by making the parameter that may contain slashes the last parameter in the url.
For a product code url you would then have...
mysite.com/product/details/PR12345/22
For a search term you'd have
http://project/search_exam/0/search_subject/0/keyword/Psychology/Management
(The keyword here is Psychology/Management)
It's not a massive amount of work to process the first "named" parameters then concat the remaining ones to be product code or keyword.
Some frameworks have this facility built in to their routing definitions.
This is not applicable to use case involving two parameters that my contain slashes.
Install first FreeTDS, then configure one of the two ODBC engines to use FreeTDS as its ODBC driver. Then use the commandline interface of the ODBC engine.
unixODBC has isql, iODBC has iodbctest
You can also use your favorite programming language (I've successfully used Perl, C, Python and Ruby to connect to MSSQL)
I'm personally using FreeTDS + iODBC:
$more /etc/freetds/freetds.conf
[10.0.1.251]
host = 10.0.1.251
port = 1433
tds version = 8.0
$ more /etc/odbc.ini
[ACCT]
Driver = /usr/local/freetds/lib/libtdsodbc.so
Description = ODBC to SQLServer via FreeTDS
Trace = No
Servername = 10.0.1.251
Database = accounts_ver8
In order to set the value of integer variable we simply assign the value to it.
eg g1val = 0
where as set keyword is used to assign value to object.
Sub test()
Dim g1val, g2val As Integer
g1val = 0
g2val = 0
For i = 3 To 18
If g1val > Cells(33, i).Value Then
g1val = g1val
Else
g1val = Cells(33, i).Value
End If
Next i
For j = 32 To 57
If g2val > Cells(31, j).Value Then
g2val = g2val
Else
g2val = Cells(31, j).Value
End If
Next j
End Sub
To correctly save the instance state of Fragment
you should do the following:
1. In the fragment, save instance state by overriding onSaveInstanceState()
and restore in onActivityCreated()
:
class MyFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
if (savedInstanceState != null) {
//Restore the fragment's state here
}
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's state here
}
}
2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState()
and restore in onCreate()
.
class MyActivity extends Activity {
private MyFragment
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
//Restore the fragment's instance
mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
...
}
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
}
}
Hope this helps.
Use :
var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//List all .png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
If you have other extensions, you can make it an array and then go through that one by one using in_array()
.
P.s : The above source code is not tested.
Mongoose now supports this natively with findOneAndUpdate (calls MongoDB findAndModify).
The upsert = true option creates the object if it doesn't exist. defaults to false.
var query = {'username': req.user.username};
req.newData.username = req.user.username;
MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
if (err) return res.send(500, {error: err});
return res.send('Succesfully saved.');
});
In older versions Mongoose does not support these hooks with this method:
I have done this in the past, and have always used this:
With Me.RecordsetClone
.MoveFirst
Do Until .EOF
If Me.Dirty Then
Me.Dirty = False
End If
.MoveNext
Me.Bookmark = .Bookmark
Loop
End With
Some people would use the form's Recordset, which doesn't require setting the bookmark (i.e., navigating the form's Recordset navigates the form's edit buffer automatically, so the user sees the move immediately), but I prefer the indirection of the RecordsetClone.
let label = UILabel(frame: CGRect(x:0,y: 0,width: 250,height: 50))
label.textAlignment = .center
label.textColor = .white
label.font = UIFont(name: "Avenir-Light", size: 15.0)
label.text = "This is a Label"
self.view.addSubview(label)
Your variable energies
probably has the wrong shape:
>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'
And that's what happens if you read columnar data using your approach:
>>> data
array([[ 1., 2., 3.],
[ 3., 4., 5.],
[ 5., 6., 7.],
[ 8., 9., 10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
[ 3.],
[ 5.],
[ 8.]])
Probably you can simply use
>>> data[:,0]
array([ 1., 3., 5., 8.])
instead.
(P.S. Your code looks like it's undecided about whether it's data
or elementdata
. I've assumed it's simply a typo.)
I am using both in my app.
Robospice works faster than Retrofit whenever I parse the nested JSON class. Because Spice Manger will do everything for you. In Retrofit you need to create GsonConverter and deserialize it.
I created two fragments in the same activity and called the same time with two same kind of URLs.
09-23 20:12:32.830 16002-16002/com.urbanpro.seeker E/RETROFIT? RestAdapter Init
09-23 20:12:32.833 16002-16002/com.urbanpro.seeker E/RETROFIT? calling the method
09-23 20:12:32.837 16002-16002/com.urbanpro.seeker E/ROBOSPICE? initialzig spice manager
09-23 20:12:32.860 16002-16002/com.urbanpro.seeker E/ROBOSPICE? Executing the method
09-23 20:12:33.537 16002-16002/com.urbanpro.seeker E/ROBOSPICE? on SUcceess
09-23 20:12:33.553 16002-16002/com.urbanpro.seeker E/ROBOSPICE? gettting the all contents
09-23 20:12:33.601 16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation starts
09-23 20:12:33.603 16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation ends
I think there are a few things to understand when working with API Gateway integration with Lambda.
There used to be only Lambda Integration which requires mapping templates. I suppose this is why still seeing many examples using it.
As of September 2017, you no longer have to configure mappings to access the request body.
Lambda Proxy Integration, If you enable it, API Gateway will map every request to JSON and pass it to Lambda as the event object. In the Lambda function you’ll be able to retrieve query string parameters, headers, stage variables, path parameters, request context, and the body from it.
Without enabling Lambda Proxy Integration, you’ll have to create a mapping template in the Integration Request section of API Gateway and decide how to map the HTTP request to JSON yourself. And you’d likely have to create an Integration Response mapping if you were to pass information back to the client.
Before Lambda Proxy Integration was added, users were forced to map requests and responses manually, which was a source of consternation, especially with more complex mappings.
Words need to navigate the thinking. To get the terminologies straight.
Lambda Proxy Integration = Pass through
Simply pass the HTTP request through to lambda.
Lambda Integration = Template transformation
Go through a transformation process using the Apache Velocity template and you need to write the template by yourself.
Using Lambda Proxy Integration, the body in the event of lambda is a string escaped with backslash, not a JSON.
"body": "{\"foo\":\"bar\"}"
If tested in a JSON formatter.
Parse error on line 1:
{\"foo\":\"bar\"}
-^
Expecting 'STRING', '}', got 'undefined'
The document below is about response but it should apply to request.
The body field, if you are returning JSON, must be converted to a string or it will cause further problems with the response. You can use JSON.stringify to handle this in Node.js functions; other runtimes will require different solutions, but the concept is the same.
For JavaScript to access it as a JSON object, need to convert it back into JSON object with json.parse in JapaScript, json.dumps in Python.
Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side.
The AWS documentation shows what to do.
if (event.body !== null && event.body !== undefined) {
let body = JSON.parse(event.body)
if (body.time)
time = body.time;
}
...
var response = {
statusCode: responseCode,
headers: {
"x-custom-header" : "my custom header value"
},
body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
callback(null, response);
I got resolver the problem in this way:
tree
in bash.Example
Example
WORKING !!!!
if (myString != null && !myString.isEmpty()) {
return true;
}
else {
return false;
}
Updated
For Kotlin we check if the string is null or not by following
return myString.isNullOrEmpty() // Returns `true` if this nullable String is either `null` or empty, false otherwise
return myString.isEmpty() // Returns `true` if this char sequence is empty (contains no characters), false otherwise
In C++
Any variable at file scope and that is not nested inside a class or function, is visible throughout all translation units in a program. This is called external linkage because at link time the name is visible to the linker everywhere, external to that translation unit.
Global variables and ordinary functions have external linkage.
Static object or function name at file scope is local to translation unit. That is called as Internal Linkage
Linkage refers only to elements that have addresses at link/load time; thus, class declarations and local variables have no linkage.
I was facing some problem from SQL PLUS Command Promt.
So I resolve this issue from windows CMD ,I follow such steps--->
1: open CMD (Windows)
2: type show pdbs;
now u have to unmount the data base which is mounted
3: type alter pluggable database database_Name open;
4: type show pdbs;(for cross check)
It works for me
Simplest way is to use the html5 FormAction
and FormMethod
<input type="submit"
formaction="Save"
formmethod="post"
value="Save" />
<input type="submit"
formaction="SaveForLatter"
formmethod="post"
value="Save For Latter" />
<input type="submit"
formaction="SaveAndPublish"
formmethod="post"
value="Save And Publish" />
[HttpPost]
public ActionResult Save(CustomerViewModel model) {...}
[HttpPost]
public ActionResult SaveForLatter(CustomerViewModel model){...}
[HttpPost]
public ActionResult SaveAndPublish(CustomerViewModel model){...}
There are many other ways which we can use, see this article ASP.Net MVC multiple submit button use in different ways
I have the same problem....
I change my project name and i have this problem...my solution was the checking project refences and use /
in my web.xml (instead of /*
)
You can't set session side session variables from Javascript
. If you want to do this you need to create an AJAX
POST to update this on the server though if the selection of a car is a major event it might just be easier to POST this.
lets put this in a simple term. An element is a set of opening and closing tags in use.
Element
<h1>...</h1>
Tag H1 opening tag
<h1>
H1 closing tag
</h1>
For Python 3, it is
import sys
max = sys.maxsize
min = -sys.maxsize - 1
Select-String
worked best for me. All the other options listed here, such as findstr
, didn't work with large files.
Here's an example:
select-string -pattern "<pattern>" -path "<path>"
note: This requires Powershell
I'd recommend using a regular expressions instead of string operations for this:
Set fso = CreateObject("Scripting.FileSystemObject")
filename = "C:\VBS\filediprova.txt"
newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"
Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global = False
re.IgnoreCase = True
text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")
The regular expression will match a line feed (\n
) followed by a line containing the string Test Case
followed by a number (\d
), and the replacement will prepend that with the text you want to insert (variable newtext
). Setting re.Global = False
makes the replacement stop after the first match.
If the line breaks in your text file are encoded as CR-LF
(carriage return + line feed) you'll have to change \n
into \r\n
and vbLf
into vbCrLf
.
If you have to modify several text files, you could do it in a loop like this:
For Each f In fso.GetFolder("C:\VBS").Files
If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
text = f.OpenAsTextStream.ReadAll
f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
End If
Next
In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.
If you guys see any issues with this please let me know and I'll fix it (etc. etc.)
Save it in a file called git-rm-ntb
(call it whatever) on PATH
and run:
git-rm-ntb <remote1:optional> <remote2:optional> ...
clean()
{
REMOTES="$@";
if [ -z "$REMOTES" ]; then
REMOTES=$(git remote);
fi
REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
RBRANCHES=()
while read REMOTE; do
CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
done < <(echo "$REMOTES" )
[[ $RBRANCHES ]] || exit
LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
for i in "${LBRANCHES[@]}"; do
skip=
for j in "${RBRANCHES[@]}"; do
[[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
done
[[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
done
}
clean $@
Following all instructions, this is what I did and worked:
mysql> SELECT CONNECTION_ID();//This is my ID for this session.
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 20 |
+-----------------+
1 row in set (0.00 sec)
mysql> select @max_allowed_packet //Mysql do not found @max_allowed_packet
+---------------------+
| @max_allowed_packet |
+---------------------+
| NULL |
+---------------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet; //That is better... I have max_allowed_packet=32M inside my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 33554432 |
+-----------------------------+
1 row in set (0.00 sec)
mysql> **SET GLOBAL max_allowed_packet=1073741824**; //Now I'm changing the value.
Query OK, 0 rows affected (0.00 sec)
mysql> select @max_allowed_packet; //Mysql not found @max_allowed_packet
+---------------------+
| @max_allowed_packet |
+---------------------+
| NULL |
+---------------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The new value. And I still have max_allowed_packet=32M inisde my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 1073741824 |
+-----------------------------+
1 row in set (0.00 sec)
So, as we can see, the max_allowed_packet has been changed outside from my.ini.
Lets leave the session and check again:
mysql> exit
Bye
C:\Windows\System32>mysql -uroot -pPassword
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 5.6.26-log MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SELECT CONNECTION_ID();//This is my ID for this session.
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 21 |
+-----------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The new value still here and And I still have max_allowed_packet=32M inisde my.ini
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 1073741824 |
+-----------------------------+
1 row in set (0.00 sec)
Now I will stop the server
2016-02-03 10:28:30 - Server is stopped
mysql> SELECT CONNECTION_ID();
ERROR 2013 (HY000): Lost connection to MySQL server during query
Now I will start the server
2016-02-03 10:31:54 - Server is running
C:\Windows\System32>mysql -uroot -pPassword
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 5.6.26-log MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SELECT CONNECTION_ID();
+-----------------+
| CONNECTION_ID() |
+-----------------+
| 9 |
+-----------------+
1 row in set (0.00 sec)
mysql> Select @@global.max_allowed_packet;//The previous new value has gone. Now I see what I have inside my.ini again.
+-----------------------------+
| @@global.max_allowed_packet |
+-----------------------------+
| 33554432 |
+-----------------------------+
1 row in set (0.00 sec)
Conclusion, after SET GLOBAL max_allowed_packet=1073741824, the server will have the new max_allowed_packet until it is restarted, as someone stated previously.
You could do something like this:
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3
It might initially seem strange to add True
to True
this way, but I don't think it's unpythonic; after all, bool
is a subclass of int
in all versions since 2.3:
>>> issubclass(bool, int)
True
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
I actually once pushed with --force
and .git
repository and got scolded by Linus BIG TIME. In general this will create a lot of problems for other people. A simple answer is "Don't do it".
I see others gave the recipe for doing so anyway, so I won't repeat them here. But here is a tip to recover from the situation after you have pushed out the amended commit with --force (or +master).
git reflog
to find the old commit that you amended (call it old
, and we'll call the new commit you created by amending new
).old
and new
, recording the tree of new
, like git checkout new && git merge -s ours old
.git merge master
git push . HEAD:master
Then people who were unfortunate enough to have based their work on the commit you obliterated by amending and forcing a push will see the resulting merge will see that you favor new
over old
. Their later merges will not see the conflicts between old
and new
that resulted from your amending, so they do not have to suffer.
For most applications you would like to set a minimum level but not a maximum level.
For example, when debugging your code set the minimum level to DEBUG, and in production set it to WARN.
There are just so many gotchas when creating deployment packages for AWS Lambda (for Python). I have spent hours and hours on debugging sessions until I found a formula that rarely fails.
I have created a script that automates the entire process and therefore makes it less error prone. I have also wrote tutorial that explains how everything works. You may want to check it out:
max(stats, key=stats.get)
char numeralChar = '4';
int numeral = (int) (numeralChar - '0');
The answere by Patrick and by Jesse Chisholm made me do the following:
#define QUEEN 'Q'
#define JACK 'J'
#define CHECK_QUEEN(s) (s==QUEEN)
#define CHECK_JACK(s) (s==JACK)
#define USER 'Q'
[... later on in code ...]
#if CHECK_QUEEN(USER)
compile_queen_func();
#elif CHECK_JACK(USER)
compile_jack_func();
#elif
#error "unknown user"
#endif
Instead of #define USER 'Q'
#define USER QUEEN
should also work but was not tested also works and might be easier to handle.
EDIT: According to the comment of @Jean-François Fabre I adapted my answer.
I liked learnvst's answer of using the tables because it is quite readable (which is one purpose of writing Markdown).
However, in the case of GitBook's Markdown parser I had to, in addition to an empty header line, add a separator line under it, for the table to be recognized and properly rendered:
| - | - |
|---|---|
| I am text to the left | ![Flowers](/flowers.jpeg) |
| ![Flowers](/flowers.jpeg) | I am text to the right |
Separator lines need to include at least three dashes ---
.
You can use this pod called 'SVGParser'. https://cocoapods.org/pods/SVGParser.
After adding it in your pod file, all you have to do is to import this module to the class that you want to use it. You should show the SVG image in an ImageView.
There are three cases you can show this SVGimage:
You can also find an example project in GitHub: https://github.com/AndreyMomot/SVGParser. Just download the project and run it to see how it works.
Make sure you have selected the correct version of Visual Studio. This is trickier than it seems because Visual Studio 2015 is actually Visual Studio 14, and similarly Visual Studio 2012 is Visual Studio 11. I had incorrectly selected Visual Studio 15 which is actually Visual Studio 2017, when I had 2015 installed.
Yes, it's possible to use inline if-expressions:
{{ 'Update' if files else 'Continue' }}
I've used a simple technique that works nicely for small cases with no special tags and no additional context. Sometimes this comes in handy
{% for i in '0123456789'|make_list %}
{{ forloop.counter }}
{% endfor %}
Full code that shows now and 10 minutes added.....
$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;
Try like this:
$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);
Pay particular attention to the set()
call's 3rd parameter. false
prevents CodeIgniter from quoting the 2nd parameter -- this allows the value to be treated as a table column and not a string value. For any data that doesn't need to special treatment, you can lump all of those declarations into the $data
array.
The query generated by above code:
UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'
Get the remote PR branch into local branch:
git fetch origin ‘remote_branch’:‘local_branch_name’
Set the upstream of local branch to remote branch.
git branch --set-upstream-to=origin/PR_Branch_Name local_branch
When you want to push the local changes to PR branch again
git push origin HEAD:remote_PR_Branch_name
Do you just want to know how to write a line to a file? First, you need to open the file:
f = open("filename.txt", 'w')
Then, you need to write the string to the file:
f.write("dict = {'one': 1, 'two': 2}" + '\n')
You can repeat this for each line (the +'\n'
adds a newline if you want it).
Finally, you need to close the file:
f.close()
You can also be slightly more clever and use with
:
with open("filename.txt", 'w') as f:
f.write("dict = {'one': 1, 'two': 2}" + '\n')
### repeat for all desired lines
This will automatically close the file, even if exceptions are raised.
But I suspect this is not what you are asking...
hstore
is more of a "wide column" storage type, it is a flat (non-nested) dictionary of key-value pairs, always stored in a reasonably efficient binary format (a hash table, hence the name).json
stores JSON documents as text, performing validation when the documents are stored, and parsing them on output if needed (i.e. accessing individual fields); it should support the entire JSON spec. Since the entire JSON text is stored, its formatting is preserved.jsonb
takes shortcuts for performance reasons: JSON data is parsed on input and stored in binary format, key orderings in dictionaries are not maintained, and neither are duplicate keys. Accessing individual elements in the JSONB field is fast as it doesn't require parsing the JSON text all the time. On output, JSON data is reconstructed and initial formatting is lost.IMO, there is no significant reason for not using jsonb
once it is available, if you are working with machine-readable data.
The goal here is to remove the given package and its dependencies without breaking another package's dependencies. I use this command:
brew deps [FORMULA] | xargs brew remove --ignore-dependencies && brew missing | xargs brew install
Note: Edited to reflect @alphadogg's helpful comment.
It depends why the something is on the same line in the first place.
clear
in the case of floats, display: block
in the case of inline content naturally flowing, nothing will defeat position: absolute
as the previous element will be taken out of the normal flow by it.
This is the only syntax that worked for me
$('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked');
DISCLAIMER: overlay has been deprecated.
You can still use this if you absolutely have to, but try not to.
This only works on WebKit browsers, but I like it a lot.
Will behave like auto
on other browsers.
.yourContent{
overflow-y: overlay;
}
This will make the scrollbar appear only as an overlay, thus not affecting the width of your element!
Remove the quotes here:
is:
ORDER BY = 'post_datetime DESC' AND LIMIT = '3'
Should be:
ORDER BY post_datetime DESC LIMIT 3
I found this post very useful so here is the solution in PHP. I've been using this successfully and just wanted to save another dev some time.
/**
* Get a center latitude,longitude from an array of like geopoints
*
* @param array data 2 dimensional array of latitudes and longitudes
* For Example:
* $data = array
* (
* 0 = > array(45.849382, 76.322333),
* 1 = > array(45.843543, 75.324143),
* 2 = > array(45.765744, 76.543223),
* 3 = > array(45.784234, 74.542335)
* );
*/
function GetCenterFromDegrees($data)
{
if (!is_array($data)) return FALSE;
$num_coords = count($data);
$X = 0.0;
$Y = 0.0;
$Z = 0.0;
foreach ($data as $coord)
{
$lat = $coord[0] * pi() / 180;
$lon = $coord[1] * pi() / 180;
$a = cos($lat) * cos($lon);
$b = cos($lat) * sin($lon);
$c = sin($lat);
$X += $a;
$Y += $b;
$Z += $c;
}
$X /= $num_coords;
$Y /= $num_coords;
$Z /= $num_coords;
$lon = atan2($Y, $X);
$hyp = sqrt($X * $X + $Y * $Y);
$lat = atan2($Z, $hyp);
return array($lat * 180 / pi(), $lon * 180 / pi());
}
if you what to obtain "ONE" by giving in 100 then
initialize hash map by
hashmap = new HashMap<Object,String>();
haspmap.put(100,"one");
and retrieve value by
hashMap.get(100)
hope that helps.
As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:
U+0022
("
, the quotation mark)U+005C
(\
, the backslash or reverse solidus) U+0000
to U+001F
(the ASCII control characters)In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:
U+002F
(/
)U+0027
('
)U+003C
(<
)U+003E
(>
)U+0026
(&
)U+0085
(Next Line)U+2028
(Line Separator)U+2029
(Paragraph Separator)Some of the above characters can be escaped with the following short escape sequences defined in the standard:
\"
represents the quotation mark character (U+0022).\\
represents the reverse solidus character (U+005C).\/
represents the solidus character (U+002F).\b
represents the backspace character (U+0008).\f
represents the form feed character (U+000C).\n
represents the line feed character (U+000A).\r
represents the carriage return character (U+000D).\t
represents the character tabulation character (U+0009).The other characters which need to be escaped will use the \uXXXX
notation, that is \u
followed by the four hexadecimal digits that encode the code point.
The \uXXXX
can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).
Here's how I ended up doing this:
<div id="divform">
<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
<div>Certificate 1: <input type="file" name="cert1"/></div>
<div>Certificate 2: <input type="file" name="cert2"/></div>
<div><input type="button" value="Upload" onclick="closeSelf();"/></div>
</form>
</div>
<div id="closelink" style="display:none">
<a href="javascript:window.close()">Click Here to Close this Page</a>
</div>
function closeSelf(){
document.forms['certform'].submit();
hide(document.getElementById('divform'));
unHide(document.getElementById('closelink'));
}
Where hide()
and unhide()
set the style.display
to 'none'
and 'block'
respectively.
Not exactly what I had in mind, but this will have to do for the time being. Works on IE, Safari, FF and Chrome.
1 - right click the highlight whose color you want to change
2 - select "Properties" in the popup menu
3 - choose the new color (as coobird suggested)
This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.
Here is an example where the things to add come from a dictionary
>>> L = [0, 0, 0, 0]
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
>>> for item in things_to_add:
... L[item['idx']] += item['amount']
...
>>> L
[0, 1, 1, 0]
Here is an example adding elements from another list
>>> L = [0, 0, 0, 0]
>>> things_to_add = [0, 1, 1, 0]
>>> for idx, amount in enumerate(things_to_add):
... L[idx] += amount
...
>>> L
[0, 1, 1, 0]
You could also achieve the above with a list comprehension and zip
L[:] = [sum(i) for i in zip(L, things_to_add)]
Here is an example adding from a list of tuples
>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
... L[idx] += amount
...
>>> L
[0, 1, 1, 0]
I do not know why everyone has seem to overlook the site.css file in the Content folder. Look at line 22 in this file and you will see the settings for input to be controlled. It would appear that your site is not referencing this style sheet.
I added this:
input, select, textarea { max-width: 280px;}
to your fiddle and it works just fine.
You should never ever update bootstrap.css or bootstrap.min.css. Doing so will set you up to fail when bootstrap gets updated. That is why the site.css file is included. This is where you can make changes to site that will still give you the responsive design you are looking for.
Timedelta objects have read-only instance attributes .days
, .seconds
, and .microseconds
.
In Pyspark you can simply specify each condition separately:
val Lead_all = Leads.join(Utm_Master,
(Leaddetails.LeadSource == Utm_Master.LeadSource) &
(Leaddetails.Utm_Source == Utm_Master.Utm_Source) &
(Leaddetails.Utm_Medium == Utm_Master.Utm_Medium) &
(Leaddetails.Utm_Campaign == Utm_Master.Utm_Campaign))
Just be sure to use operators and parenthesis correctly.
You can use this one check:
create or replace function to_n(c varchar2) return number is
begin return to_number(c);
exception when others then return -123456;
end;
select id, n from t where to_n(n) = -123456;
Here is an alternative implementation.
Basically if you able to edit page at other domain you can place another iframe page that belongs to your server which saving height to cookies. With an interval read cookies when it is updated, update the height of the iframe. That is all.
Edit: 2019 December
The solution above basically uses another iframe inside of an iframe 3rd iframe is belongs to the top page domain, which you call this page with a query string that saves size value to a cookie, outer page checks this query with some interval. But it is not a good solution so you should follow this one:
In Top page :
window.addEventListener("message", (m)=>{iframeResizingFunction(m)});
Here you can check m.origin
to see where is it comes from.
In frame page:
window.parent.postMessage({ width: 640, height:480 }, "*")
Although, please don't forget this is not so secure way. To make it secure update * value (targetOrigin) with your desired value. Please follow documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Postgres SQL : version 9.6
Total records on tables : mjr_agent = 145, mjr_transaction_item = 91800
1.Using with EXISTS
[Average Query Time : 1.42s]
SELECT count(txi.id)
FROM
mjr_transaction_item txi
WHERE
EXISTS ( SELECT 1 FROM mjr_agent agnt WHERE agnt.agent_group = 0 AND (txi.src_id = agnt.code OR txi.dest_id = agnt.code) )
2.Using with two lines IN
Clause [Average Query Time : 0.37s]
SELECT count(txi.id) FROM mjr_transaction_item txi
WHERE
txi.src_id IN ( SELECT agnt.code FROM mjr_agent agnt WHERE agnt.agent_group = 0 )
OR txi.dest_id IN ( SELECT agnt.code FROM mjr_agent agnt WHERE agnt.agent_group = 0 )
3.Using with INNNER JOIN
pattern [Average Query Time : 2.9s]
SELECT count(DISTINCT(txi.id)) FROM mjr_transaction_item txi
INNER JOIN mjr_agent agnt ON agnt.code = txi.src_id OR agnt.code = txi.dest_id
WHERE
agnt.agent_group = 0
So , I choosed second option.
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
This applies to all languages:
You want to have an event/listener model. You create a listener to wait for a particular event. The event would be created (or signaled) in your worker thread. This will block the thread until the signal is received instead of constantly polling to see if a condition is met, like the solution you currently have.
Your situation is one of the most common causes for deadlocks- make sure you signal the other thread regardless of errors that may have occurred. Example- if your application throws an exception- and never calls the method to signal the other that things have completed. This will make it so the other thread never 'wakes up'.
I suggest that you look into the concepts of using events and event handlers to better understand this paradigm before implementing your case.
Alternatively you can use a blocking function call using a mutex- which will cause the thread to wait for the resource to be free. To do this you need good thread synchronization- such as:
Thread-A Locks lock-a
Run thread-B
Thread-B waits for lock-a
Thread-A unlocks lock-a (causing Thread-B to continue)
Thread-A waits for lock-b
Thread-B completes and unlocks lock-b
Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(15, 15);
arrlist.add(22, 22);
arrlist.add(30, 30);
arrlist.add(40, 40);
// adding element 25 at third position
arrlist.add(2, 25);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
$javac com/tutorialspoint/ArrayListDemo.java
$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0 at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661) at java.util.ArrayList.add(ArrayList.java:473) at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)
Expanding on the accepted answer, if the input is:
1,NYC
2,ABQ
...
you will still be able to apply the same logic, like this:
#include <fstream>
std::ifstream infile("thefile.txt");
if (infile.is_open()) {
int number;
std::string str;
char c;
while (infile >> number >> c >> str && c == ',')
std::cout << number << " " << str << "\n";
}
infile.close();
The simplest way is to just redirect the output, like so:
Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt
>
will cause the output file to be overwritten if it already exists.
>>
will append new text to the end of the output file if it already exists.
ISO 8601 may contains seconds see http://en.wikipedia.org/wiki/ISO_8601#Times
so the code should be
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.
Another case is if there are a lot of things in the 1st-level cache and you'd like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together. This is the case that Aleksei's answer covers.
this type name is Decode/Unescape Unicode. this site link online convertor.
This command helped me on linux mint when i had exact same problem
gcc filename.c -L/usr/include -lreadline -o filename
You could use alias if you compile it many times Forexample:
alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'
Did you try using clientVia to see the message sent, using SOAP toolkit or something like that? This could help to see if the error is coming from the client itself or from somewhere else.
I was NOT getting the ServerName wrong. Inside your VirtualHost configuration that is causing this warning message, it is the generic one near the top of your httpd.conf which is by default commented out.
Change
#ServerName www.example.com:80
to:
ServerName 127.0.0.1:80
If you're looking for a document-level key event handling, then binding it during componentDidMount
is the best way (as shown by Brad Colthurst's codepen example):
class ActionPanel extends React.Component {
constructor(props){
super(props);
this.escFunction = this.escFunction.bind(this);
}
escFunction(event){
if(event.keyCode === 27) {
//Do whatever when esc is pressed
}
}
componentDidMount(){
document.addEventListener("keydown", this.escFunction, false);
}
componentWillUnmount(){
document.removeEventListener("keydown", this.escFunction, false);
}
render(){
return (
<input/>
)
}
}
Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.
EDIT: If you are using hooks, you can use this useEffect
structure to produce a similar effect:
const ActionPanel = (props) => {
const escFunction = useCallback((event) => {
if(event.keyCode === 27) {
//Do whatever when esc is pressed
}
}, []);
useEffect(() => {
document.addEventListener("keydown", escFunction, false);
return () => {
document.removeEventListener("keydown", escFunction, false);
};
}, []);
return (
<input />
)
};
The answer to your question is yes and no, depending on what you mean by "inline function". If you're using the term like it's used in C++ development then the answer is no, you can't do that - even a lambda expression is a function call. While it's true that you can define inline lambda expressions to replace function declarations in C#, the compiler still ends up creating an anonymous function.
Here's some really simple code I used to test this (VS2015):
static void Main(string[] args)
{
Func<int, int> incr = a => a + 1;
Console.WriteLine($"P1 = {incr(5)}");
}
What does the compiler generate? I used a nifty tool called ILSpy that shows the actual IL assembly generated. Have a look (I've omitted a lot of class setup stuff)
This is the Main function:
IL_001f: stloc.0
IL_0020: ldstr "P1 = {0}"
IL_0025: ldloc.0
IL_0026: ldc.i4.5
IL_0027: callvirt instance !1 class [mscorlib]System.Func`2<int32, int32>::Invoke(!0)
IL_002c: box [mscorlib]System.Int32
IL_0031: call string [mscorlib]System.String::Format(string, object)
IL_0036: call void [mscorlib]System.Console::WriteLine(string)
IL_003b: ret
See those lines IL_0026 and IL_0027? Those two instructions load the number 5 and call a function. Then IL_0031 and IL_0036 format and print the result.
And here's the function called:
.method assembly hidebysig
instance int32 '<Main>b__0_0' (
int32 a
) cil managed
{
// Method begins at RVA 0x20ac
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
} // end of method '<>c'::'<Main>b__0_0'
It's a really short function, but it is a function.
Is this worth any effort to optimize? Nah. Maybe if you're calling it thousands of times a second, but if performance is that important then you should consider calling native code written in C/C++ to do the work.
In my experience readability and maintainability are almost always more important than optimizing for a few microseconds gain in speed. Use functions to make your code readable and to control variable scoping and don't worry about performance.
"Premature optimization is the root of all evil (or at least most of it) in programming." -- Donald Knuth
"A program that doesn't run correctly doesn't need to run fast" -- Me
You can use the "Network" tab in the browser (shift+ctrl+i) or Firebug.
But an even better solution - in my opinion - is in addition to use an external program such as Fiddler to monitor/catch the traffic between browser and server.
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
Start your activity with request code :
StartActivityForResult(intent,1234);
And you can close it from any other activity like this :
finishActivity(1234);
Here is slightly modified version. Changes are noted as code commentary.
BEGIN TRANSACTION
declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500)
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'pct%'
AND TABLE_NAME LIKE 'TestData%'
open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
-- And then fetch
fetch next from Tests into @test, @tableName
-- And then, if no row is fetched, exit the loop
if @@fetch_status <> 0
begin
break
end
-- Quotename is needed if you ever use special characters
-- in table/column names. Spaces, reserved words etc.
-- Other changes add apostrophes at right places.
set @cmd = N'exec sp_rename '''
+ quotename(@tableName)
+ '.'
+ quotename(@test)
+ N''','''
+ RIGHT(@test,LEN(@test)-3)
+ '_Pct'''
+ N', ''column'''
print @cmd
EXEC sp_executeSQL @cmd
END
close Tests
deallocate Tests
ROLLBACK TRANSACTION
--COMMIT TRANSACTION
var result = replaceSpace.replace(/ /g, ";");
Here, / /g
is a regex (regular expression). The flag g
means global. It causes all matches to be replaced.
Use heroku's fork
Use the new "heroku fork" command! It will copy all the environment and you have to update the github repo after!
heroku fork -a sourceapp targetapp
Clone it local
git clone [email protected]:youamazingapp.git
Make a new repo on github and add it
git remote add origin https://github.com/yourname/your_repo.git
Push on github
git push origin master
If you are using Windows/Visual Studio and need to convert a string to wstring you could use:
#include <AtlBase.h>
#include <atlconv.h>
...
string s = "some string";
CA2W ca2w(s.c_str());
wstring w = ca2w;
printf("%s = %ls", s.c_str(), w.c_str());
Same procedure for converting a wstring to string (sometimes you will need to specify a codepage):
#include <AtlBase.h>
#include <atlconv.h>
...
wstring w = L"some wstring";
CW2A cw2a(w.c_str());
string s = cw2a;
printf("%s = %ls", s.c_str(), w.c_str());
You could specify a codepage and even UTF8 (that's pretty nice when working with JNI/Java). A standard way of converting a std::wstring to utf8 std::string is showed in this answer.
//
// using ATL
CA2W ca2w(str, CP_UTF8);
//
// or the standard way taken from the answer above
#include <codecvt>
#include <string>
// convert UTF-8 string to wstring
std::wstring utf8_to_wstring (const std::string& str) {
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
return myconv.from_bytes(str);
}
// convert wstring to UTF-8 string
std::string wstring_to_utf8 (const std::wstring& str) {
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
return myconv.to_bytes(str);
}
If you want to know more about codepages there is an interesting article on Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets.
These CA2W (Convert Ansi to Wide=unicode) macros are part of ATL and MFC String Conversion Macros, samples included.
Sometimes you will need to disable the security warning #4995', I don't know of other workaround (to me it happen when I compiled for WindowsXp in VS2012).
#pragma warning(push)
#pragma warning(disable: 4995)
#include <AtlBase.h>
#include <atlconv.h>
#pragma warning(pop)
Edit: Well, according to this article the article by Joel appears to be: "while entertaining, it is pretty light on actual technical details". Article: What Every Programmer Absolutely, Positively Needs To Know About Encoding And Character Sets To Work With Text.
I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.
For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.
Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.
http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html