@hbhakhra's answer will do.
If you're interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)
You will find:
DEVICE - A value chosen by the device implementer containing the development name or code name identifying the configuration of the hardware features and industrial design of the device. The value of this field MUST be encodable as 7-bit ASCII and match the regular expression “^[a-zA-Z0-9_-]+$”.
MODEL - A value chosen by the device implementer containing the name of the device as known to the end user. This SHOULD be the same name under which the device is marketed and sold to end users. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").
MANUFACTURER - The trade name of the Original Equipment Manufacturer (OEM) of the product. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").
what jamietre said, but
Private Sub SomeVBASub
Cancel=False
DoStuff
If not Cancel Then DoAnotherStuff
If not Cancel Then AndFinallyDothis
End Sub
OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.
#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif
Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:
BARNABY_API int add(){
}
This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.
WAMP stands for Windows,Apache,Mysql,Php
XAMPP stands for X-os,Apache,Mysql,Php,Perl. (x-os means it can use for any operating system)
It is cross-platform software
It possesses many other essential modules such as phpMyAdmin, OpenSSL, MediaWiki, WordPress, Joomla and more.
it is easy to configure and use.
It is easy to Use. (Changing Configuration)
WAMP is Available for both 64 bit and 32-bit system.
if you are running projects which have specific version requirements WAMP is better choice because you can switch between multiple versions. for example 7x and PHP 5x or Magento2.2.4 won't work on php7.2 but Magento2.3.needs php7.2 or up to work.
i suggest using laragon :
Laragon works out of the box with not only MySQL/MariaDB but also PostgreSQL & MongoDB. With Laragon, they are portable & reliable so you can focus on what matters Laragon is a portable, isolated, fast & powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend.
Laragon is great for building and managing modern web applications. It is focused on performance - designed around stability, simplicity, flexibility and freedom.
Laragon is very lightweight and will stay as lean as possible. The core binary itself is less than 2MB and uses less than 4MB RAM when running.
Laragon doesn’t use Windows services. It has its own service orchestration which manages services asynchronously and non-blocking so you’ll find things run fast & smoothly with Laragon.
Pretty URLs
Use app.test
instead of localhost/app
.
Portable
You can move Laragon folder around (to another disks, to another laptops, sync to Cloud,…) without any worries.
Isolated
Laragon has an isolated environment with your OS - it will keep your system clean.
Easy Operation
Unlike others which pre-config for you, Laragon auto-configsall
the complicated things. That why you can add another versions of PHP, Python, Ruby, Java, Go, Apache, Nginx, MySQL, PostgreSQL, MongoDB,… effortlessly.
Modern & Powerful
Laragon comes with modern architect which is suitable to build modern web apps. You can work with both Apache & Nginx as they are fully-managed.
Also, Laragon makes things a lot easier:Wanna have a Wordpress CMS? Just 1 click.Wanna show your local project to customers? Just 1 click.Wanna enable/disable a PHP extension? Just 1 click.
There's also the Event.eventPhase
property which can tell you if the event is at target or comes from somewhere else, and it is fully supported by browsers.
Expanding on the already great snippet from the accepted answer, this is the output using the eventPhase
property
var logElement = document.getElementById('log');
function log(msg) {
if (logElement.innerHTML == "<p>No logs</p>")
logElement.innerHTML = "";
logElement.innerHTML += ('<p>' + msg + '</p>');
}
function humanizeEvent(eventPhase){
switch(eventPhase){
case 1: //Event.CAPTURING_PHASE
return "Event is being propagated through the target's ancestor objects";
case 2: //Event.AT_TARGET
return "The event has arrived at the event's target";
case 3: //Event.BUBBLING_PHASE
return "The event is propagating back up through the target's ancestors in reverse order";
}
}
function capture(e) {
log('capture: ' + this.firstChild.nodeValue.trim() + "; " +
humanizeEvent(e.eventPhase));
}
function bubble(e) {
log('bubble: ' + this.firstChild.nodeValue.trim() + "; " +
humanizeEvent(e.eventPhase));
}
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', capture, true);
divs[i].addEventListener('click', bubble, false);
}
_x000D_
p {
line-height: 0;
}
div {
display:inline-block;
padding: 5px;
background: #fff;
border: 1px solid #aaa;
cursor: pointer;
}
div:hover {
border: 1px solid #faa;
background: #fdd;
}
_x000D_
<div>1
<div>2
<div>3
<div>4
<div>5</div>
</div>
</div>
</div>
</div>
<button onclick="document.getElementById('log').innerHTML = '<p>No logs</p>';">Clear logs</button>
<section id="log"></section>
_x000D_
This is one of those things that can be difficult to search for if you don't already know where to look.
[
is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it's documented in the Bash manual.
There's also an external command that does the same thing; on many systems, it's provided by the GNU Coreutils package.
[
is equivalent to the test
command, except that [
requires ]
as its last argument, and test
does not.
Assuming the bash documentation is installed on your system, if you type info bash
and search for 'test'
or '['
(the apostrophes are part of the search), you'll find the documentation for the [
command, also known as the test
command. If you use man bash
instead of info bash
, search for ^ *test
(the word test
at the beginning of a line, following some number of spaces).
Following the reference to "Bash Conditional Expressions" will lead you to the description of -ne
, which is the numeric inequality operator ("ne" stands for "not equal). By contrast, !=
is the string inequality operator.
You can also find bash documentation on the web.
test
and [
)-ne
is under "arg1 OP arg2")test
The official definition of the test
command is the POSIX standard (to which the bash implementation should conform reasonably well, perhaps with some extensions).
Both @Collin Jackson and @Sniper are right. You can follow these steps to set up launch images in android and iOS respectively. Then in your MyApp(), in your initState(), you can use Future.delayed to set up a timer or call any api. Until the response is returned from the Future, your launch icons will be shown and then as the response come, you can move to the screen you want to go to after the splash screen. You can see this link : Flutter Splash Screen
you can use this code .may be solve the problem
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);
So does C99.
The IEEE 754 floating point representation used by all modern processors has several special bit patterns reserved for positive infinity (sign=0, exp=~0, frac=0), negative infinity (sign=1, exp=~0, frac=0), and many NaN (Not a Number: exp=~0, frac?0).
All you need to worry about: some arithmetic may cause floating point exceptions/traps, but those aren't limited to only these "interesting" constants.
Quite amazing how all answers talk about IIS, as if that were the only web server that mattered. Even back in 2010 when the question was asked, Apache had between 60% and 70% of the market share. Anyway,
min(serverMaximumSize, clientMaximumSize)
.Here are the POST body sizes for some of the more popular HTTP servers:
An object file is just what you get when you compile one (or several) source file(s).
It can be either a fully completed executable or library, or intermediate files.
The object files typically contain native code, linker information, debugging symbols and so forth.
There is no such file open mode as "wr" in your code:
fopen("logs.txt", "wr")
The file open modes in PHP http://php.net/manual/en/function.fopen.php is the same as in C: http://www.cplusplus.com/reference/cstdio/fopen/
There are the following main open modes "r" for read, "w" for write and "a" for append, and you cannot combine them. You can add other modifiers like "+" for update, "b" for binary. The new C standard adds a new standard subspecifier ("x"), supported by PHP, that can be appended to any "w" specifier (to form "wx", "wbx", "w+x" or "w+bx"/"wb+x"). This subspecifier forces the function to fail if the file exists, instead of overwriting it.
Besides that, in PHP 5.2.6, the 'c' main open mode was added. You cannot combine 'c' with 'a', 'r', 'w'. The 'c' opens the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). 'c+' Open the file for reading and writing; otherwise it has the same behavior as 'c'.
Additionally, and in PHP 7.1.2 the 'e' option was added that can be combined with other modes. It set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.
So, for the task as you have described it, the best file open mode would be 'a'. It opens the file for writing only. It places the file pointer at the end of the file. If the file does not exist, it attempts to create it. In this mode, fseek() has no effect, writes are always appended.
Here is what you need, as has been already pointed out above:
fopen("logs.txt", "a")
In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.
Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.
If your ListView row item refers to a separate XML file, be sure to add android:longClickable="true"
to that layout file in addition to setting setOnItemLongClickListener()
to your ListView.
purls $.params()
used without a parameter will give you a key-value object of the parameters.
jQuerys $.param()
will build a querystring from the supplied object/array.
var params = parsedUrl.param();
delete params["page"];
var newUrl = "?page=" + $(this).val() + "&" + $.param(params);
Update
I've no idea why I used delete
here...
var params = parsedUrl.param();
params["page"] = $(this).val();
var newUrl = "?" + $.param(params);
For Angular 7 users:
Here I show you that you can activate or deactivate a simple class attribute named "blurred" with just a boolean. Therefore u need to use [ngClass]
.
TS class
blurredStatus = true
HTML
<div class="inner-wrapper" [ngClass]="{'blurred':blurredStatus}"></div>
SELECT *
FROM sys.tables t
INNER JOIN sys.objects o on o.object_id = t.object_id
WHERE o.is_ms_shipped = 0;
GET Request with JSON Query Param
package com.rest.jersey.jerseyclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientGET {
public static void main(String[] args) {
try {
String BASE_URI="http://vaquarkhan.net:8080/khanWeb";
Client client = Client.create();
WebResource webResource = client.resource(BASE_URI);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
/*if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
*/
String output = webResource.path("/msg/sms").queryParam("search","{\"name\":\"vaquar\",\"surname\":\"khan\",\"ext\":\"2020\",\"age\":\"34\""}").get(String.class);
//String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Post Request :
package com.rest.jersey.jerseyclient;
import com.rest.jersey.dto.KhanDTOInput;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class JerseyClientPOST {
public static void main(String[] args) {
try {
KhanDTOInput khanDTOInput = new KhanDTOInput("vaquar", "khan", "20", "E", null, "2222", "8308511500");
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
// final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
// client.addFilter(authFilter);
// client.addFilter(new LoggingFilter());
//
WebResource webResource = client
.resource("http://vaquarkhan.net:12221/khanWeb/messages/sms/api/v1/userapi");
ClientResponse response = webResource.accept("application/json")
.type("application/json").put(ClientResponse.class, khanDTOInput);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code :" + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Server response .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I use a very simple but efficient technique in my app.js ( my entry point ) I define a variable like
let authUser = {};
Then I assign to it from my route page ( like after successful login )
authUser = matchedUser
It May be not the best approach but it fits my needs.
A C Function-Declaration Backgrounder
In C, function declarations don't work like they do in other languages: The C compiler itself doesn't search backward and forward in the file to find the function's declaration from the place you call it, and it doesn't scan the file multiple times to figure out the relationships either: The compiler only scans forward in the file exactly once, from top to bottom. Connecting function calls to function declarations is part of the linker's job, and is only done after the file is compiled down to raw assembly instructions.
This means that as the compiler scans forward through the file, the very first time the compiler encounters the name of a function, one of two things have to be the case: It either is seeing the function declaration itself, in which case the compiler knows exactly what the function is and what types it takes as arguments and what types it returns — or it's a call to the function, and the compiler has to guess how the function will eventually be declared.
(There's a third option, where the name is used in a function prototype, but we'll ignore that for now, since if you're seeing this problem in the first place, you're probably not using prototypes.)
History Lesson
In the earliest days of C, the fact that the compiler had to guess types wasn't really an issue: All of the types were more-or-less the same — pretty much everything was either an int or a pointer, and they were the same size. (In fact, in B, the language that preceded C, there were no types at all; everything was just an int or pointer and its type was determined solely by how you used it!) So the compiler could safely guess the behavior of any function just based on the number of parameters that were passed: If you passed two parameters, the compiler would push two things onto the call stack, and presumably the callee would have two arguments declared, and that would all line up. If you passed only one parameter but the function expected two, it would still sort-of work, and the second argument would just be ignored/garbage. If you passed three parameters and the function expected two, it would also still sort-of work, and the third parameter would be ignored and stomped on by the function's local variables. (Some old C code still expects these mismatched-argument rules will work, too.)
But having the compiler let you pass anything to anything isn't really a good way to design a programming language. It worked well in the early days because the early C programmers were mostly wizards, and they knew not to pass the wrong type to functions, and even if they did get the types wrong, there were always tools like lint
that could do deeper double-checking of your C code and warn you about such things.
Fast-forward to today, and we're not quite in the same boat. C has grown up, and a lot of people are programming in it who aren't wizards, and to accommodate them (and to accommodate everyone else who regularly used lint
anyway), the compilers have taken on many of the abilities that were previously part of lint
— especially the part where they check your code to ensure it's type-safe. Early C compilers would let you write int foo = "hello";
and it would just blithely assign the pointer to the integer, and it was up to you to make sure you weren't doing anything stupid. Modern C compilers complain loudly when you get your types wrong, and that's a good thing.
Type Conflicts
So what's all this got to do with the mysterious conflicting-type error on the line of the function declaration? As I said above, C compilers still have to either know or guess what a name means the first time they see that name as they scan forward through the file: They can know what it means it if it's an actual function declaration itself (or a function "prototype," more on that shortly), but if it's just a call to the function, they have to guess. And, sadly, the guess is often wrong.
When the compiler saw your call to do_something()
, it looked at how it was invoked, and it concluded that do_something()
would eventually be declared like this:
int do_something(char arg1[], char arg2[])
{
...
}
Why did it conclude that? Because that's how you called it! (Some C compilers may conclude that it was int do_something(int arg1, int arg2)
, or simply int do_something(...)
, both of which are even farther from what you want, but the important point is that regardless of how the compiler guesses the types, it guesses them differently from what your actual function uses.)
Later on, as the compiler scans forward in the file, it sees your actual declaration of char *do_something(char *, char *)
. That function declaration isn't even close to the declaration that the compiler guessed, which means that the line where the compiler compiled the call was compiled wrong, and the program is just not going to work. So it rightly prints an error telling you that your code isn't going to work as written.
You might be wondering, "Why does it assume I'm returning an int
?" Well, it assumes that type because there's no information to the contrary: printf()
can take in any type in its variable arguments, so without a better answer, int
is as good a guess as any. (Many early C compilers always assumed int
for every unspecified type, and assumed you meant ...
for the arguments for every function declared f()
— not void
— which is why many modern code standards recommend always putting void
in for the arguments if there really aren't supposed to be any.)
The Fix
There are two common fixes for the function-declaration error.
The first solution, which is recommended by many other answers here, is to put a prototype in the source code above the place where the function is first called. A prototype looks just like the function's declaration, but it has a semicolon where the body should be:
char *do_something(char *dest, const char *src);
By putting the prototype first, the compiler then knows what the function will eventually look like, so it doesn't have to guess. By convention, programmers often put prototypes at the top of the file, just under the #include
statements, to ensure that they'll always be defined before any potential usages of them.
The other solution, which also shows up in some real-world code, is to simply reorder your functions so that the function declarations are always before anything that calls them! You could move the entire char *do_something(char *dest, const char *src) { ... }
function above the first call to it, and the compiler then would know exactly what the function looks like and wouldn't have to guess.
In practice, most people use function prototypes, because you can also take function prototypes and move them into header (.h
) files so that code in other .c
files can call those functions. But either solution works, and many codebases use both.
C99 and C11
It is useful to note that the rules are slightly different in the newer versions of the C standard. In the earlier versions (C89 and K&R), the compiler really would guess the types at function-call time (and K&R-era compilers often wouldn't even warn you if they were wrong). C99 and C11 both require that the function declaration/prototype must precede the first call, and it's an error if it doesn't. But many modern C compilers — mainly for backward compatibility with earlier code — will only warn about a missing prototype and not consider it an error.
Well, you can't add styling using pseudo selectors like :hover
, :after
, :nth-child
, or anything like that using jQuery.
If you want to add a CSS rule like that you have to create a <style>
element and add that :hover
rule to it just like you would in CSS. Then you would have to add that <style>
element to the page.
Using the .hover
function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:
$('head').append('<style>.myclass:hover div {background-color : red;}</style>')
If you want to read more on adding CSS with javascript you can check out one of David Walsh's Blog posts.
Using svcutil, you can create interfaces and classes (data contracts) from the WSDL.
svcutil your.wsdl (or svcutil your.wsdl /l:vb if you want Visual Basic)
This will create a file called "your.cs" in C# (or "your.vb" in VB.NET) which contains all the necessary items.
Now, you need to create a class "MyService" which will implement the service interface (IServiceInterface) - or the several service interfaces - and this is your server instance.
Now a class by itself doesn't really help yet - you'll need to host the service somewhere. You need to either create your own ServiceHost instance which hosts the service, configure endpoints and so forth - or you can host your service inside IIS.
(9.61 + "").replace('.',':')
Or if your 9.61
is already a string:
"9.61".replace('.',':')
If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query).
var exceptionList = new List<string> { "exception1", "exception2" };
var query = myEntities.MyEntity
.Select(e => e.Name)
.Where(e => !exceptionList.Contains(e.Name));
If you're excluding based on another database query using Except
might be a better choice. (Here is a link to the supported Set extensions in LINQ to Entities)
var exceptionList = myEntities.MyOtherEntity
.Select(e => e.Name);
var query = myEntities.MyEntity
.Select(e => e.Name)
.Except(exceptionList);
This assumes a complex entity in which you are excluding certain ones depending some property of another table and want the names of the entities that are not excluded. If you wanted the entire entity, then you'd need to construct the exceptions as instances of the entity class such that they would satisfy the default equality operator (see docs).
A hint for anyone experiencing this. This can happen when a switchMap
doesn't receive an observable return value (like null). Simply add a default case, so it always returns an observable.
switchMap((dateRange) => {
if (dateRange === 'Last 24 hours') {
return $observable1;
}
if (dateRange === 'Last 7 Days') {
return $observable2;
}
if (dateRange === 'Last 30 Days') {
return $observable3;
}
// This line will work for default cases
return $observableElse;
})
Math.floor rounds a number down to the nearest integer
function generateRandomInteger (min, max) {
return Math.floor(random(min,max))
}`
So to generate a random integer between 4 and 8 inclusive, call the above function with the following arguments:
generateRandomInteger (4,9)
As I outline in this other answer here on StackOverflow, you can do this by timing the download of files of various sizes (start small, ramp up if the connection seems to allow it), ensuring through cache headers and such that the file is really being read from the remote server and not being retrieved from cache. This doesn't necessarily require that you have a server of your own (the files could be coming from S3 or similar), but you will need somewhere to get the files from in order to test connection speed.
That said, point-in-time bandwidth tests are notoriously unreliable, being as they are impacted by other items being downloaded in other windows, the speed of your server, links en route, etc., etc. But you can get a rough idea using this sort of technique.
There is an unnecessary hashtag; change the code to this:
var e = document.getElementById("ticket_category_clone").value;
The answers using grep are wrong. You need to add an -x option to match the entire line otherwise lines like #text to add
will still match when looking to add exactly text to add
.
So the correct solution is something like:
grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar
Step 1: Run the application using following parameters.
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
Above arguments bind the application to the port 9999.
Step 2: Launch jconsole by executing the command jconsole in command prompt or terminal.
Select ‘Remote Process:’ and enter the url as {IP_Address}:9999 and click on Connect button to connect to the remote application.
You can refer this link for complete application.
Sorting in an ORDER BY
is done by the first column, and then by each additional column in the specified statement.
For instance, consider the following data:
Column1 Column2
======= =======
1 Smith
2 Jones
1 Anderson
3 Andrews
The query
SELECT Column1, Column2 FROM thedata ORDER BY Column1, Column2
would first sort by all of the values in Column1
and then sort the columns by Column2
to produce this:
Column1 Column2
======= =======
1 Anderson
1 Smith
2 Jones
3 Andrews
In other words, the data is first sorted in Column1
order, and then each subset (Column1
rows that have 1
as their value) are sorted in order of the second column.
The difference between the two statements you posted is that the rows in the first one would be sorted first by prod_price
(price order, from lowest to highest), and then by order of name (meaning that if two items have the same price, the one with the lower alpha value for name would be listed first), while the second would sort in name order only (meaning that prices would appear in order based on the prod_name
without regard for price).
What is the point of the exercise?
As people pointed out already, you could have a non-generic function taking the largest item, and compiler will automatically convert up smaller ints for you.
static bool IntegerFunction(Int64 value) { }
If your function is on performance-critical path (very unlikely, IMO), you could provide overloads for all needed functions.
static bool IntegerFunction(Int64 value) { }
...
static bool IntegerFunction(Int16 value) { }
After a lot of research: This actually works:
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.custom_actionbar);
ActionBar.LayoutParams p = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
p.gravity = Gravity.CENTER;
You have to define custom_actionbar.xml layout which is as per your requirement e.g. :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#2e2e2e"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/top_banner"
android:layout_gravity="center"
/>
</LinearLayout>
Your NSSet
approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet
to begin with?
I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet
to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray];
NSArray *arrayWithoutDuplicates = [orderedSet array];
If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:
NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
[mutableArray removeObjectAtIndex:index];
}
index--;
}
[copy release];
Here is an alternative which uses a custom output iterator. This example behaves correctly for the case of an empty list. This example demonstrates how to create a custom output iterator, similar to std::ostream_iterator
.
#include <iterator>
#include <vector>
#include <iostream>
#include <sstream>
struct CommaIterator
:
public std::iterator<std::output_iterator_tag, void, void, void, void>
{
std::ostream *os;
std::string comma;
bool first;
CommaIterator(std::ostream& os, const std::string& comma)
:
os(&os), comma(comma), first(true)
{
}
CommaIterator& operator++() { return *this; }
CommaIterator& operator++(int) { return *this; }
CommaIterator& operator*() { return *this; }
template <class T>
CommaIterator& operator=(const T& t) {
if(first)
first = false;
else
*os << comma;
*os << t;
return *this;
}
};
int main () {
// The vector to convert
std::vector<int> v(3,3);
// Convert vector to string
std::ostringstream oss;
std::copy(v.begin(), v.end(), CommaIterator(oss, ","));
std::string result = oss.str();
const char *c_result = result.c_str();
// Display the result;
std::cout << c_result << "\n";
}
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
You cannot call a function that requires arguments in a template. Write a template tag or filter instead.
Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.
def load(fname):
''' Load the file using std open'''
f = open(fname,'r')
data = []
for line in f.readlines():
data.append(line.replace('\n','').split(' '))
f.close()
return data
For a text file with 4000x4000 words this is about 10 times faster than loadtxt
.
Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions
In response to the final part of your question, which is still unanswered... When you write $('#video').duration
, you're asking for the duration
property of the jQuery collection object, which doesn't exist. The native DOM video element does have the duration. You can get that in a few ways.
Here's one:
// get the native element directly
document.getElementById('video').duration
Here's another:
// get it out of the jQuery object
$('#video').get(0).duration
And another:
// use the event object
v.bind('loadeddata', function(e) {
console.log(e.target.duration);
});
There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.
http://linuxcommand.org/lc3_man_pages/readh.html
-e use Readline to obtain the line in an interactive shell
Change your read to read -e and annoying line input hang goes away.
Try this query:
SELECT sysdate FROM schema_name.table_name;
This should display the timestamp that you might need.
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.
create a new separate environment in Anaconda dedicated to TensorFlow as follows:
conda create -n newenvt anaconda python=python_version
replace python_version by your python version
activate the new environment as follows:
activate newenvt
Then install tensorflow into the new environment (newenvt) as follows:
conda install tensorflow
Now you can check it by issuing the following python code and it will work fine.
import tensorflow
I recently ran into this problem too and unfortunately had many occurences of names beginning with Mc and Mac, I ended up using a version of scottb's code which I changed to handle these prefixes so it's here in case anyone wants to use it.
There are still edge cases which this misses but the worst thing that can happen is that a letter will be lower case when it should be capitalized.
/**
* Get a nicely formatted representation of the name.
* Don't send this the whole name at once, instead send it the components.<br>
* For example: andrew macnamara would be returned as:<br>
* Andrew Macnamara if processed as a single string<br>
* Andrew MacNamara if processed as 2 strings.
* @param name
* @return correctly formatted name
*/
public static String getNameTitleCase (String name) {
final String ACTIONABLE_DELIMITERS = " '-/";
StringBuilder sb = new StringBuilder();
if (name !=null && !name.isEmpty()){
boolean capitaliseNext = true;
for (char c : name.toCharArray()) {
c = (capitaliseNext)?Character.toUpperCase(c):Character.toLowerCase(c);
sb.append(c);
capitaliseNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0);
}
name = sb.toString();
if (name.startsWith("Mc") && name.length() > 2 ) {
char c = name.charAt(2);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,2));
sb.append (name.substring(2,3).toUpperCase());
sb.append (name.substring(3));
name=sb.toString();
}
} else if (name.startsWith("Mac") && name.length() > 3) {
char c = name.charAt(3);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,3));
sb.append (name.substring(3,4).toUpperCase());
sb.append (name.substring(4));
name=sb.toString();
}
}
}
return name;
}
Please note that there is a mistake in the url provided in this answer:
For a PUT mapping request: the url should be as follows:
http://localhost:9200/name_of_index/_mappings/document_type
and NOT
In my case is because of styles.xml
set the wrong parent theme, i.e. NoActionBar
theme of course getSupportActionbar()
is null:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
Changed it to something else fixed it:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
Knuth left this as an exercise (Vol 3, 5.2.5). There do exist in-place merge sorts. They must be implemented carefully.
First, naive in-place merge such as described here isn't the right solution. It downgrades the performance to O(N2).
The idea is to sort part of the array while using the rest as working area for merging.
For example like the following merge function.
void wmerge(Key* xs, int i, int m, int j, int n, int w) {
while (i < m && j < n)
swap(xs, w++, xs[i] < xs[j] ? i++ : j++);
while (i < m)
swap(xs, w++, i++);
while (j < n)
swap(xs, w++, j++);
}
It takes the array xs
, the two sorted sub-arrays are represented as ranges [i, m)
and [j, n)
respectively. The working area starts from w
. Compare with the standard merge algorithm given in most textbooks, this one exchanges the contents between the sorted sub-array and the working area. As the result, the previous working area contains the merged sorted elements, while the previous elements stored in the working area are moved to the two sub-arrays.
However, there are two constraints that must be satisfied:
With this merging algorithm defined, it's easy to imagine a solution, which can sort half of the array; The next question is, how to deal with the rest of the unsorted part stored in work area as shown below:
... unsorted 1/2 array ... | ... sorted 1/2 array ...
One intuitive idea is to recursive sort another half of the working area, thus there are only 1/4 elements haven't been sorted yet.
... unsorted 1/4 array ... | sorted 1/4 array B | sorted 1/2 array A ...
The key point at this stage is that we must merge the sorted 1/4 elements B with the sorted 1/2 elements A sooner or later.
Is the working area left, which only holds 1/4 elements, big enough to merge A and B? Unfortunately, it isn't.
However, the second constraint mentioned above gives us a hint, that we can exploit it by arranging the working area to overlap with either sub-array if we can ensure the merging sequence that the unmerged elements won't be overwritten.
Actually, instead of sorting the second half of the working area, we can sort the first half, and put the working area between the two sorted arrays like this:
... sorted 1/4 array B | unsorted work area | ... sorted 1/2 array A ...
This setup effectively arranges the work area overlap with the sub-array A. This idea is proposed in [Jyrki Katajainen, Tomi Pasanen, Jukka Teuhola. ``Practical in-place mergesort''. Nordic Journal of Computing, 1996].
So the only thing left is to repeat the above step, which reduces the working area from 1/2, 1/4, 1/8, … When the working area becomes small enough (for example, only two elements left), we can switch to a trivial insertion sort to end this algorithm.
Here is the implementation in ANSI C based on this paper.
void imsort(Key* xs, int l, int u);
void swap(Key* xs, int i, int j) {
Key tmp = xs[i]; xs[i] = xs[j]; xs[j] = tmp;
}
/*
* sort xs[l, u), and put result to working area w.
* constraint, len(w) == u - l
*/
void wsort(Key* xs, int l, int u, int w) {
int m;
if (u - l > 1) {
m = l + (u - l) / 2;
imsort(xs, l, m);
imsort(xs, m, u);
wmerge(xs, l, m, m, u, w);
}
else
while (l < u)
swap(xs, l++, w++);
}
void imsort(Key* xs, int l, int u) {
int m, n, w;
if (u - l > 1) {
m = l + (u - l) / 2;
w = l + u - m;
wsort(xs, l, m, w); /* the last half contains sorted elements */
while (w - l > 2) {
n = w;
w = l + (n - l + 1) / 2;
wsort(xs, w, n, l); /* the first half of the previous working area contains sorted elements */
wmerge(xs, l, l + n - w, n, u, w);
}
for (n = w; n > l; --n) /*switch to insertion sort*/
for (m = n; m < u && xs[m] < xs[m-1]; ++m)
swap(xs, m, m - 1);
}
}
Where wmerge is defined previously.
The full source code can be found here and the detailed explanation can be found here
By the way, this version isn't the fastest merge sort because it needs more swap operations. According to my test, it's faster than the standard version, which allocates extra spaces in every recursion. But it's slower than the optimized version, which doubles the original array in advance and uses it for further merging.
Avoid sqlite3_clear_bindings(stmt)
.
The code in the test sets the bindings every time through which should be enough.
The C API intro from the SQLite docs says:
Prior to calling sqlite3_step() for the first time or immediately after sqlite3_reset(), the application can invoke the sqlite3_bind() interfaces to attach values to the parameters. Each call to sqlite3_bind() overrides prior bindings on the same parameter
There is nothing in the docs for sqlite3_clear_bindings
saying you must call it in addition to simply setting the bindings.
More detail: Avoid_sqlite3_clear_bindings()
Use this lean and short syntax:
{ this.state.show && <MyCustomComponent /> }
If you recently reached here as I did when searching for the same error in vain you may find it to be an update to NSS causing failure on CentOS. Test by running yum update and see if you get errors, curl also creates this error. Solution is simple enough just install NSS manually.
Read on...
If you're like me it threw up an error similar to this:
curl: (77) Problem with the SSL CA cert (path? access rights?)
This took some time to solve but found that it wasn't the CA cert because by recreating them and checking all the configuration I had ruled it out. It could have been libcurl so I went in search of updates.
As mentioned I recreated CA certs. You can do this also but it may be a waste of time. http://wiki.centos.org/HowTos/Https
The next step (probably should of been my first) was to check that everything was up-to-date by simply running yum.
$ yum update
$ yum upgrade
This gave me an affirmative answer that there was a bigger problem at play:
Downloading Packages:
error: rpmts_HdrFromFdno: Header V3 RSA/SHA1 Signature, key ID c105b9de: BAD
Problem opening package nss-softokn-freebl-3.14.3–19.el6_6.x86_64.rpm
I started reading about Certificate Verification with NSS and how this new update may be related to my problems.
So yum is broken. This is because nss-softokn-* needs nss-softokn-freebl-* need each other to function. The problem is they don't check each others version for compatibility and in some cases it ends up breaking yum.
Lets go fix things:
$ wget http://mirrors.linode.com/centos/6.6/updates/x86_64/Packages/nsssoftokn-freebl-3.14.3-19.el6_6.x86_64.rpm
$ rpm -Uvh nss-softokn-freebl-3.14.3–19.el6_6.x86_64.rpm
$ yum update
You should of course download from your nearest mirror and check for the correct version / OS etc. We basically download and install the update from the rpm to fix yum. As @grumpysysadmin pointed out you can shorten the commands down. @cwgtex contributed that you should install the upgrade using the RPM command making the process even simplier.
To fix things with wordpress you need to restart your http server.
$ service httpd restart
Try again and success!
When [dropping] the encoding settings mentioned above all characters [are rendered] correctly but the encoding that is detected shows either windows-1252 or ISO-8859-1 depending on the browser.
Then that's what you're really sending. None of the encoding settings in your bullet list will actually modify your output in any way; all they do is tell the browser what encoding to assume when interpreting what you send. That's why you're getting those ?s - you're telling the browser that what you're sending is UTF-8, but it's really ISO-8859-1.
Towards the second half of Create REST API using ASP.NET MVC that speaks both JSON and plain XML, to quote:
Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."
He then implements an action filter that maps the JSON to C# objects with code shown.
This method will be slower than the the recursive and enumerative methods here, but uses Wilson's theorem, and is just a single line:
from math import factorial
def is_prime(x):
return factorial(x - 1) % x == x - 1
This is really easy using a JavaScript library, e.g. using jQuery you could write:
$(document).ready(function(){
$.ajax({ url: "database/update.html",
context: document.body,
success: function(){
alert("done");
}});
});
Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:
<html>
<body onload="updateDB();">
</body>
<script language="javascript">
function updateDB() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "database/update.html", true);
xhr.send(null);
/* ignore result */
}
</script>
</html>
See also:
Add the following command to your .vimrc to turn of the end-of-line option:
autocmd FileType php setlocal noeol binary fileformat=dos
However, PHP itself will ignore that last end-of-line - it shouldn't be an issue. I am almost certain that in your case there is something else which is adding the last newline character, or possibly there is a mixup with windows/unix line ending types (\n
or \r\n
, etc).
Update:
An alternative solution might be to just add this line to your .vimrc:
set fileformats+=dos
I suggest Validator.nu's parser, based on the HTML5 parsing algorithm. It is the parser used in Mozilla from 2010-05-03
The simple solution, which no one have mentioned yet, is to just ignore the problem. If I try to use an int
as a template type in a function template that expects a container class such as vector or list, then I will get a compile error. Crude and simple, but it solves the problem. The compiler will try to use the type you specify, and if that fails, it generates a compile error.
The only problem with that is that the error messages you get are going to be tricky to read. It is nevertheless a very common way to do this. The standard library is full of function or class templates that expect certain behavior from the template type, and do nothing to check that the types used are valid.
If you want nicer error messages (or if you want to catch cases that wouldn't produce a compiler error, but still don't make sense) you can, depending on how complex you want to make it, use either Boost's static assert or the Boost concept_check library.
With an up-to-date compiler you have a built_in static_assert
, which could be used instead.
You say you have a database on PhpMyAdmin, so you are using MySQL. PHP provides functions for connecting to a MySQL database.
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
In the while loop (which runs every time we encounter a result row), we echo which creates a new table row. I also add a to contain the fields.
This is a very basic template. You see the other answers using mysqli_connect instead of mysql_connect. mysqli stands for mysql improved. It offers a better range of features. You notice it is also a little bit more complex. It depends on what you need.
You can use isLetter(char c) static method of Character class in Java.lang .
public boolean isAlpha(String s) {
char[] charArr = s.toCharArray();
for(char c : charArr) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
If you're using less , and it's not loading the icons font you must check out the font path go to the file variable.less and change the @icon-font-path path , that worked for me.
I also looked for a simple console replacement, just to dump text. So what I did was this function:
function remoteLog (arg) {
var file = '/files/remoteLog.php';
$.post(file, {text: arg});
}
The remote PHP file recorded all the output to a database in arg
. It took me 5 minutes (OK, on the server side I used a simple logging library that records and displays text messages, but still...).
After adding files to the stage, you need to commit them with git commit -m "comment"
after git add .
. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>
.
If you want to keep the default config but want md5 authentication with socket connection for one specific user/db connection, add a "local" line BEFORE the "local all/all" line:
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local dbname username md5 # <-- this line
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 ident
# IPv6 local connections:
host all all ::1/128 ident
Transfer the task of assigning the object ID from Hibernate to the database by using:
<generator class="native"/>
This solved the problem for me.
There is a proper way to split the filename and the extension: Extract filename and extension in Bash
You can apply it like this:
date=$(date +"%m%d%y")
for FILE in folder1/*.csv
do
bname=$(basename "$FILE")
extension="${bname##*.}"
filenamewoext="${bname%.*}"
newfilename="${filenamewoext}${date}.${extension}
cp folder1/${FILE} folder2/${newfilename}
done
Here is an example of SIGSEGV.
root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
int * p ;
* p = 0x1234;
return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c
root@pierr-desktop:/opt/playGround# ./test
Segmentation fault
And here is the detail.
How to handle it?
Avoid it as much as possible in the first place.
Program defensively: use assert(), check for NULL pointer , check for buffer overflow.
Use static analysis tools to examine your code.
compile your code with -Werror -Wall.
Has somebody review your code.
When that actually happened.
Examine you code carefully.
Check what you have changed since the last time you code run successfully without crash.
Hopefully, gdb will give you a call stack so that you know where the crash happened.
EDIT : sorry for a rush. It should be *p = 0x1234;
instead of p = 0x1234
;
I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.
<a href="javascript:alert('Please be sure to set your printer to Landscape.');window.print();">Print Me...</a>
or
<body onload="alert('Please be sure to set your printer to Landscape.');window.print();">
etc.
</body>
In Python 2.7 or Python 3
Instead of making a Popen
object directly, you can use the subprocess.check_output()
function to store output of a command in a string:
from subprocess import check_output
out = check_output(["ntpq", "-p"])
In Python 2.4-2.6
Use the communicate
method.
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()
out
is what you want.
Important note about the other answers
Note how I passed in the command. The "ntpq -p"
example brings up another matter. Since Popen
does not invoke the shell, you would use a list of the command and options—["ntpq", "-p"]
.
What you want is something like this:
document.getElementByClassName("example").click();
Using jQuery, it would be something like this:
$(".example").trigger("click");
document.getElementById('table1').rows[0].cells.length
cells is not a property of a table, rows are. Cells is a property of a row though
let videoUrl = //URL: Your Video URL
//Create player first using your URL
let yourplayer = AVPlayer(url: videoUrl)
//Create player controller and set it’s player
let playerController = AVPlayerViewController()
playerController.player = yourplayer
//Final step To present controller with player in your view controller
present(playerController, animated: true, completion: {
playerController.player!.play()
})
I know this is pretty old question but it topped the list when I searched. So I wanted to update with another method.
In the strings.xml file you can do the \n or you can simply press enter:
<string name="Your string name" > This is your string. This is the second line of your string.\n\n Third line of your string.</string>
This will result in the following on your TextView:
This is your string.
This is the second line of your string.
Third line of your string.
This is because there were two returns between the beginning declaration of the string and the new line. I also added the \n to it for clarity, as either can be used. I like to use the carriage returns in the xml to be able to see a list or whatever multiline string I have. My two cents.
I have seen the same warning when my data has extra space, tabs, newlines or other characters in my column which is decimal(10,2)
to solve that, I had to remove those characters from value.
here is how I handled it.
LOAD DATA LOCAL INFILE 'c:/Users/Hitesh/Downloads/InventoryMasterReportHitesh.csv'
INTO TABLE stores_inventory_tmp
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(@col1, @col2, @col3, @col4, @col5)
SET sku = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col1,'\t',''), '$',''), '\r', ''), '\n', ''))
, product_name = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col2,'\t',''), '$',''), '\r', ''), '\n', ''))
, department_number = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col3,'\t',''), '$',''), '\r', ''), '\n', ''))
, department_name = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col4,'\t',''), '$',''), '\r', ''), '\n', ''))
, price = TRIM(REPLACE(REPLACE(REPLACE(REPLACE(@col5,'\t',''), '$',''), '\r', ''), '\n', ''))
;
I've got that hint from this answer
I had a Automated Billing setup online and the credit card said it say good Thru 10/09, but the card was rejected the first week in October and again the next week. Each time it was rejected it cost me a $10 fee. Don't assume it good thru the end of the month if you have automatic billing setup.
If you want to change ng-view you'll have to use the '#'
$window.location.href= "#operation";
You can't do this with jQuery, visible="false"
in asp.net means the control isn't rendered into the page. If you want the control to go to the client, you need to do style="display: none;"
so it's actually in the HTML, otherwise there's literally nothing for the client to show, since the element wasn't in the HTML your server sent.
If you remove the visible
attribute and add the style
attribute you can then use jQuery to show it, like this:
$("#elementID").show();
To change visibility
, you need to use .css()
, like this:
$("#elem").css('visibility', 'visible');
Unless you need to have the element occupy page space though, use display: none;
instead of visibility: hidden;
in your CSS, then just do:
$("#elem").show();
The .show()
and .hide()
functions deal with display
instead of visibility
, like most of the jQuery functions :)
It is most efficient to do your aggregation by integer and then convert back to datetime for presentation.
select
cast(daybucket - 1 as datetime) as count_date,
counted_leads
from
(select
cast(created_date as int) as DayBucket,
count(*) as counted_leads
from mytable
group by cast(created_date as int) ) as countByDay
you need javascript and some client side calculations: http://jsfiddle.net/omegaiori/NERE8/2/
you will need jquery to effectively achieve what you want. this function is very simple but very effective:
(function () {
var heights = $("#wrapper").outerHeight(true);
var outerHeights = $("#first").outerHeight(true);
jQuery('#second').css('height', (heights - outerHeights) + "px");
})();
first it detects the wrapper height, as it is set to 100% it's different everytime (it depends on what screen you are landing).
in the second step it gives the #second
div the appropriate height subtracting from the wrapper height the #first
div height. the result is the available height left in the wrapper div
I had the same error and it occured when changing the mysql/data
folder to another folder.
I just copied all folders inside mysql/data
folder to a new location except for two files. Those are ib_logfile0
and ib_logfile1
; those are automatically created when starting the MySQL server.
That worked for me.
EDIT: See the other answers for better solutions
The original newbie approaches that I offered were (opt1):
$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");
And (opt2):
$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");
That was quick and easy and got the original poster going immediately.
Hence the accepted answer.
As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"
I tend to use Spring's Named JDBC Parameters so I can write a standard string like "select * from blah where colX=':someValue'"; I think that's pretty readable.
An alternative would be to supply the string in a separate .sql file and read the contents in using a utility method.
Oh, also worth having a look at Squill: https://squill.dev.java.net/docs/tutorial.html
Swift 5.1 or later
extension StringProtocol {
var firstUppercased: String { prefix(1).uppercased() + dropFirst() }
var firstCapitalized: String { prefix(1).capitalized + dropFirst() }
}
Swift 5
extension StringProtocol {
var firstUppercased: String { return prefix(1).uppercased() + dropFirst() }
var firstCapitalized: String { return prefix(1).capitalized + dropFirst() }
}
"Swift".first // "S"
"Swift".last // "t"
"hello world!!!".firstUppercased // "Hello world!!!"
"?".firstCapitalized // "?"
"?".firstCapitalized // "?"
"?".firstCapitalized // "?"
If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:
zip -r <AppName>.war *
I've tested it with Tomcat 8 on the Mac, but it should work anywhere
This will work for most of the website names :
SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....
You need to make sure that a mac compatible version of java exists on your computer. Do java -version from terminal to check that. If not, download the apple jdk from the apple website. (Sun doesn't make one for apple themselves, IIRC.)
From there, follow the same command line instructions from compiling your program that you would use for java on any other platform.
Try this method;
Shorthand method:
let variable1 = '';_x000D_
_x000D_
let variable2 = variable1 || 'new'_x000D_
console.log(variable2); // new
_x000D_
Longhand method:
let variable1 = 'ya';_x000D_
let varibale2;_x000D_
_x000D_
if (variable1 !== null || variable1 !== undefined || variable1 !== '')_x000D_
variable2 = variable1;_x000D_
_x000D_
console.log(variable2); // ya
_x000D_
Here is my method to cast an object but not to a generic type variable, rather to a System.Type
dynamically:
I create a lambda expression at run-time using System.Linq.Expressions
, of type Func<object, object>
, that unboxes its input, performs the desired type conversion then gives the result boxed. A new one is needed not only for all types that get casted to, but also for the types that get casted (because of the unboxing step). Creating these expressions is highly time consuming, because of the reflection, the compilation and the dynamic method building that is done under the hood. Luckily once created, the expressions can be invoked repeatedly and without high overhead, so I cache each one.
private static Func<object, object> MakeCastDelegate(Type from, Type to)
{
var p = Expression.Parameter(typeof(object)); //do not inline
return Expression.Lambda<Func<object, object>>(
Expression.Convert(Expression.ConvertChecked(Expression.Convert(p, from), to), typeof(object)),
p).Compile();
}
private static readonly Dictionary<Tuple<Type, Type>, Func<object, object>> CastCache
= new Dictionary<Tuple<Type, Type>, Func<object, object>>();
public static Func<object, object> GetCastDelegate(Type from, Type to)
{
lock (CastCache)
{
var key = new Tuple<Type, Type>(from, to);
Func<object, object> cast_delegate;
if (!CastCache.TryGetValue(key, out cast_delegate))
{
cast_delegate = MakeCastDelegate(from, to);
CastCache.Add(key, cast_delegate);
}
return cast_delegate;
}
}
public static object Cast(Type t, object o)
{
return GetCastDelegate(o.GetType(), t).Invoke(o);
}
Note that this isn't magic. Casting doesn't occur in code, as it does with the dynamic
keyword, only the underlying data of the object gets converted. At compile-time we are still left to painstakingly figure out exactly what type our object might be, making this solution impractical. I wrote this as a hack to invoke conversion operators defined by arbitrary types, but maybe somebody out there can find a better use case.
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
Is it possible (work only online and load only your page or file): https://w3schools.com/xml/xml_http.asp Try my code:
function load_page(){
qr=new XMLHttpRequest();
qr.open('get','YOUR_file_or_page.htm');
qr.send();
qr.onload=function(){YOUR_div_id.innerHTML=qr.responseText}
};load_page();
qr.onreadystatechange instead qr.onload also use.
Add .idea
and *.iml
to .gitignore
, you don't need those files to successfully import and compile the project.
A more modern answer for an old question:
MainActivity.kt
private var myMenuIconEnabled by Delegates.observable(true) { _, old, new ->
if (new != old) invalidateOptionsMenu()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<Button>(R.id.my_button).setOnClickListener { myMenuIconEnabled = false }
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main_activity, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
menu.findItem(R.id.action_my_action).isEnabled = myMenuIconEnabled
return super.onPrepareOptionsMenu(menu)
}
menu_main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_my_action"
android:icon="@drawable/ic_my_icon_24dp"
app:iconTint="@drawable/menu_item_icon_selector"
android:title="My title"
app:showAsAction="always" />
</menu>
menu_item_icon_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?enabledMenuIconColor" android:state_enabled="true" />
<item android:color="?disabledMenuIconColor" />
attrs.xml
<resources>
<attr name="enabledMenuIconColor" format="reference|color"/>
<attr name="disabledMenuIconColor" format="reference|color"/>
</resources>
styles.xml or themes.xml
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="disabledMenuIconColor">@color/white_30_alpha</item>
<item name="enabledMenuIconColor">@android:color/white</item>
Here goes a straightforward example:
# Do something, or tell me why it failed
my_update_function <- function(x){
tryCatch(
# This is what I want to do...
{
y = x * 2
return(y)
},
# ... but if an error occurs, tell me what happened:
error=function(error_message) {
message("This is my custom message.")
message("And below is the error message from R:")
message(error_message)
return(NA)
}
)
}
If you also want to capture a "warning", just add warning=
similar to the error=
part.
You can add a multi-line label with the following:
JLabel label = new JLabel("My label");
label.setText("<html>This is a<br>multline label!<br> Try it yourself!</html>");
From here, simply add the label to the frame using the add() method, and you're all set!
So this question is nearly 10 years old, but it popped up on one of my searches, and I think that there are better solutions when programming in Qt: Signals & slots, timers, and finite state machines. The delays that are required can be implemented without sleeping the application in a way that interrupts other functions, and without concurrent programming and without spinning the processor - the Qt application will sleep when there are no events to process.
A hack for this is to have a sequence of timers with their timeout() signal connected to the slot for the event, which then kicks off the second timer. This is nice because it is simple. It's not so nice because it quickly becomes difficult to troubleshoot and maintain if there are logical branches, which there generally will be outside of any toy example.
A better, more flexible option is the State Machine infrastructure within Qt. There you can configure an framework for an arbitrary sequence of events with multiple states and branches. An FSM is much easier to define, expand and maintain over time.
:focus
pseudo-classAs pure CSS solution, you could achieve sort of the effect by using a tabindex
attribute for the image, and :focus
pseudo-class as follows:
<img class="crossRotate" src="http://placehold.it/100" tabindex="1" />
.crossRotate {
outline: 0;
/* other styles... */
}
.crossRotate:focus {
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
Note: Using this approach, the image gets rotated onclick (focused), to negate the rotation, you'll need to click somewhere out of the image (blured).
:checked
pseudo-classThis is one of my favorite methods. In this approach, there's a hidden checkbox input and a <label>
element which wraps the image.
Once you click on the image, the hidden input is checked because of using for
attribute for the label.
Hence by using the :checked
pseudo-class and adjacent sibling selector +
, we could get the image to be rotated:
<input type="checkbox" id="hacky-input">
<label for="hacky-input">
<img class="crossRotate" src="http://placehold.it/100">
</label>
#hacky-input {
display: none; /* Hide the input */
}
#hacky-input:checked + label img.crossRotate {
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
WORKING DEMO #2 (Applying the rotate
to the label gives a better experience).
If using JavaScript/jQuery is an option, you could toggle a .active
class by .toggleClass()
to trigger the rotation effect, as follows:
$('.crossRotate').on('click', function(){
$(this).toggleClass('active');
});
.crossRotate.active {
/* vendor-prefixes here... */
transform: rotate(45deg);
}
Try sleep(int number_of_seconds)
I'm not sure when this was written, but currently to add or remove a default from a column in a migration, you can use the following:
change_column_null :products, :name, false
Rails 5:
change_column_default :products, :approved, from: true, to: false
http://edgeguides.rubyonrails.org/active_record_migrations.html#changing-columns
Rails 4.2:
change_column_default :products, :approved, false
http://guides.rubyonrails.org/v4.2/active_record_migrations.html#changing-columns
Which is a neat way of avoiding looking through your migrations or schema for the column specifications.
Pass by value sends a COPY of the data stored in the variable you specify, pass by reference sends a direct link to the variable itself. So if you pass a variable by reference and then change the variable inside the block you passed it into, the original variable will be changed. If you simply pass by value, the original variable will not be able to be changed by the block you passed it into but you will get a copy of whatever it contained at the time of the call.
Easiest way is to turn the list to tuple
first
t = tuple(l)
query = "select name from studens where id IN {}".format(t)
DataGridViewColumn column0 = dataGridViewGroup.Columns[0];
DataGridViewColumn column1 = dataGridViewGroup.Columns[1];
column1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
column1.Width = 120;
if you are on linux, edit the /etc/php/php.ini
(or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment
;extension=imap.so
so that it becomes like this:
extension=imap.so
Then, restart the apache by
# /etc/rc.d/httpd restart
This is useful when you want to compare data that correspond to different units. In that case, you want to remove the units. To do that in a consistent way of all the data, you transform the data in a way that the variance is unitary and that the mean of the series is 0.
You can convert a set into an ArrayList
, where you can sort the ArrayList
using Collections.sort(List)
.
Here is the code:
keySet = (Set) map.keySet();
ArrayList list = new ArrayList(keySet);
Collections.sort(list);
firstOrCreate() checks for all the arguments to be present before it finds a match.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'abcd',
'lastName' => 'efgh',
'veristyName'=>'xyz',
]);
Then it check only the email
It's not suitable for every situation, because not all items can have a non-proportional maximum, but slapping a good ol' max-width
on the offending element/container can put it back in line.
If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials
(see on MSDN).
Your code looks fine if you need to run a request from server side code or under a different user.
Please note that you should be careful when storing passwords - consider using the SecureString
version of the constructor.
Don't forget that some numbers will repeat! so you need to do something like....
my totalQuestions was 47.
func getRandomNumbers(totalQuestions:Int) -> NSMutableArray
{
var arrayOfRandomQuestions: [Int] = []
print("arraySizeRequired = 40")
print("totalQuestions = \(totalQuestions)")
//This will output a 40 random numbers between 0 and totalQuestions (47)
while arrayOfRandomQuestions.count < 40
{
let limit: UInt32 = UInt32(totalQuestions)
let theRandomNumber = (Int(arc4random_uniform(limit)))
if arrayOfRandomQuestions.contains(theRandomNumber)
{
print("ping")
}
else
{
//item not found
arrayOfRandomQuestions.append(theRandomNumber)
}
}
print("Random Number set = \(arrayOfRandomQuestions)")
print("arrayOutputCount = \(arrayOfRandomQuestions.count)")
return arrayOfRandomQuestions as! NSMutableArray
}
char* c = new char[length]();
It seems that there is in fact a pure CSS solution, requiring only the css attr
expression, generated content and attribute selectors (which suggests that it works as far back as IE8):
https://jsfiddle.net/z42r2vv0/2/
a {
position: relative;
display: inline-block;
margin-top: 20px;
}
a[title]:hover::after {
content: attr(title);
position: absolute;
top: -100%;
left: 0;
}
_x000D_
<a href="http://www.google.com/" title="Hello world!">
Hover over me
</a>
_x000D_
update w/ input from @ViROscar: please note that it's not necessary to use any specific attribute, although I've used the "title" attribute in the example above; actually my recommendation would be to use the "alt" attribute, as there is some chance that the content will be accessible to users unable to benefit from CSS.
update again I'm not changing the code because the "title" attribute has basically come to mean the "tooltip" attribute, and it's probably not a good idea to hide important text inside a field only accessible on hover, but if you're interested in making this text accessible the "aria-label" attribute seems like the best place for it: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute
What you could do is something like this (pseudocode):
<container table>
<tr>
<td>
<"300px" table>
<td>
<fixed layout table>
Basically, split up the table into two tables and have it contained by another table.
For people working in public open source projects, if you face this behaviour, it is most likely that the file you are editing is excluded from the git repository using .gitignore
. I faced the same behaviour, and after hours I found that the file I was making the change is excluded in .gitignore
because it is a settings file, and every one will have their own local version.
You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.
Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.
DELIMITER isn't really a MySQL language command, it's a client command.
DELIMITER $$
/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$
/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/
CREATE DEFINER=`student`@`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count FROM employees where department=the_department;
END$$
/*DELIMITER is set to it's default*/
DELIMITER ;
I had the same problem with Pool()
in Python 3.6.3.
Error received: TypeError: can't pickle _thread.RLock objects
Let's say we want to add some number num_to_add
to each element of some list num_list
in parallel. The code is schematically like this:
class DataGenerator:
def __init__(self, num_list, num_to_add)
self.num_list = num_list # e.g. [4,2,5,7]
self.num_to_add = num_to_add # e.g. 1
self.run()
def run(self):
new_num_list = Manager().list()
pool = Pool(processes=50)
results = [pool.apply_async(run_parallel, (num, new_num_list))
for num in num_list]
roots = [r.get() for r in results]
pool.close()
pool.terminate()
pool.join()
def run_parallel(self, num, shared_new_num_list):
new_num = num + self.num_to_add # uses class parameter
shared_new_num_list.append(new_num)
The problem here is that self
in function run_parallel()
can't be pickled as it is a class instance. Moving this parallelized function run_parallel()
out of the class helped. But it's not the best solution as this function probably needs to use class parameters like self.num_to_add
and then you have to pass it as an argument.
Solution:
def run_parallel(num, shared_new_num_list, to_add): # to_add is passed as an argument
new_num = num + to_add
shared_new_num_list.append(new_num)
class DataGenerator:
def __init__(self, num_list, num_to_add)
self.num_list = num_list # e.g. [4,2,5,7]
self.num_to_add = num_to_add # e.g. 1
self.run()
def run(self):
new_num_list = Manager().list()
pool = Pool(processes=50)
results = [pool.apply_async(run_parallel, (num, new_num_list, self.num_to_add)) # num_to_add is passed as an argument
for num in num_list]
roots = [r.get() for r in results]
pool.close()
pool.terminate()
pool.join()
Other suggestions above didn't help me.
You can search for "Ajax Behavior Events" in PrimeFaces User's Guide, and you will find plenty of them for all supported components. That's also what PrimeFaces lead Optimus Prime suggest to do in this related question at the PrimeFaces forum <p:ajax>
event list?
There is no onblur
event, that's the HTML attribute name, but there is a blur
event. It's just without the "on" prefix like as the HTML attribute name. You can also look at all "on*" attributes of the tag documentation of the component in question to see which are all available, e.g. <p:inputText>
.
You need to remove the scanner closing lines: scan.close();
It happened to me before and that was the reason.
I fully support @Charles Bretana's answer. However, if it's not working, please make sure that there is only one <section>
element AND that configSections
is the first child of the root element:
configsections
must be the first element in your app.Config
after configuration:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
<!-- add log 4 net config !-->
<!-- add others e.g. <startup> !-->
</configuration>
In my case
Solution:
Go to itunes inside the page of my app and inside the first tab "App Information" under the right hand side has a section "Others Information" click on the "edit user permission" and grant xcode user the permission to read the information of the app.
DONE
I'm working with Angular5 and I had to add the "name" attribute to get the binding to work... The "id" is not required for binding.
<input type="checkbox" id="rememberMe" name="rememberMe" [(ngModel)]="rememberMe">
For retrieving data using Ajax + jQuery, you should write the following code:
<html>
<script type="text/javascript" src="jquery-1.3.2.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
For mysqli connection, write this:
<?php
$con=mysqli_connect("localhost","root","");
For displaying the data from database, you should write this :
<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[2]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "</tr>";
}
echo "</table>";
?>
Make sure that in the path generated in your logs -in your case:
/Users/MyApplicationName/app/build/outputs/apk/app-debug.apk
folder "outputs" indeed has an "apk" folder.
That was my problem, if it's not there, you will need to run the "assembleRelease" task in gradle by following the below screenshot;
Click on Tools menu > Import and Export Settings > Reset all settings > Next > "No, just reset settings, overwriting all current settings" > Next > Finish.
There are different way:
global service
service shared by parent and injected to the child
providers
or viewProviders
in the parent instead of boostrap(...)
and only available to children of parent.parent injected to the child and accessed directly by the child
export class Profile implements OnInit {
constructor(@Host() parent: App) {
parent.userStatus ...
}
export class Profile implements OnInit {
@Input() userStatus:UserStatus;
...
}
<profile [userStatus]="userStatus">
import os
def fs_tree_to_dict(path_):
file_token = ''
for root, dirs, files in os.walk(path_):
tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs}
tree.update({f: file_token for f in files})
return tree # note we discontinue iteration trough os.walk
If anybody is interested - that recursive function returns nested structure of dictionaries. Keys are file system
names (of directories and files), values are either:
file_token
)The strings designating files are empty in this example. They can also be e.g. given file contents or its owner info or privileges or whatever object different than a dict. Unless it's a dictionary it can be easily distinguished from a "directory type" in further operations.
Having such a tree in a filesystem:
# bash:
$ tree /tmp/ex
/tmp/ex
+-- d_a
¦ +-- d_a_a
¦ +-- d_a_b
¦ ¦ +-- f1.txt
¦ +-- d_a_c
¦ +-- fa.txt
+-- d_b
¦ +-- fb1.txt
¦ +-- fb2.txt
+-- d_c
The result will be:
# python 2 or 3:
>>> fs_tree_to_dict("/tmp/ex")
{
'd_a': {
'd_a_a': {},
'd_a_b': {
'f1.txt': ''
},
'd_a_c': {},
'fa.txt': ''
},
'd_b': {
'fb1.txt': '',
'fb2.txt': ''
},
'd_c': {}
}
If you like that, I've already created a package (python 2 & 3) with this stuff (and a nice pyfakefs
helper):
https://pypi.org/project/fsforge/
Here is my example:
.box{_x000D_
_x000D_
width: 400px; _x000D_
height: 80px; _x000D_
background-color: #C9C; _x000D_
text-align: center; _x000D_
font: 20px normal Arial, Helvetica, sans-serif; _x000D_
color: #fff; _x000D_
padding: 100px 0 0 0;_x000D_
-webkit-box-shadow: 0 8px 6px -6px black;_x000D_
-moz-box-shadow: 0 8px 6px -6px black;_x000D_
box-shadow: 0 8px 6px -6px black;_x000D_
}
_x000D_
<div class="box">_x000D_
</div>
_x000D_
If choice
is available, use this:
choice /C X /T 10 /D X > nul
where /T 10
is the number of seconds to delay.
Note the syntax can vary depending on your Windows version, so use CHOICE /?
to be sure.
jQuery needs to be the first script you import. The first script on your page
<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>
appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
The Simplest GitHub Pull Request is from the web interface without using git.
Click the pencil icon,
search for text near the location, make any edits you want then preview them to confirm. Give the proposed change a description up to 50 characters and optionally an extended description then click the Propose file Change button.
If you're reading this you won't have write access to the repository (project folders) so GitHub will create a copy of the repository (actually a branch) in your account. Click the Create pull request button.
If the instance variables are same as the variables that are declared in the constructor then we use "this" to assign data.
class Example{
int assign;// instance variable
Example(int assign){ // variable inside constructor
this.assign=assign;
}
}
Hope this helps.
The biggest difference is their functionality. push_back
always puts a new element at the end of the vector
and insert
allows you to select new element's position. This impacts the performance. vector
elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert
forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert
might often be less efficient than push_back
.
It goes something like:
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
It would be nice to have sensible names and fields for your tables for a better example. :)
Update
I think for your query this might be more appropriate:
var dealercontacts = from contact in DealerContact
join dealer in Dealer on contact.DealerId equals dealer.ID
select contact;
Since you are looking for the contacts, not the dealers.
Great and exhaustive answerby @Kev!
Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location>
tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.
Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut
is in minutes, while the request executionTimeout
is in seconds!
And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).
<configuration>
...
<compilation debug="false" ...>
... other stuff ..
<location path="~/Admin/SomePage.aspx">
<system.web>
<sessionState timeout="240" />
<httpRuntime executionTimeout="14400" />
</system.web>
</location>
...
</configuration>
After running into this issue myself, on a huge database, I wasn't completely impressed with the performance of any of the other answers. I want to keep only the latest duplicate row, and delete the rest.
In a one-query statement, without a temp table, this worked best for me,
DELETE e.*
FROM employee e
WHERE id IN
(SELECT id
FROM (SELECT MIN(id) as id
FROM employee e2
GROUP BY first_name, last_name
HAVING COUNT(*) > 1) x);
The only caveat is that I have to run the query multiple times, but even with that, I found it worked better for me than the other options.
What even is ‘children’?
The React docs say that you can use
props.children
on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.My simple explanation of what
this.props.children
does is that it is used to display whatever you include between the opening and closing tags when invoking a component.A simple example:
Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no
this
keyword so just useprops.children
const Picture = (props) => {
return (
<div>
<img src={props.src}/>
{props.children}
</div>
)
}
This component contains an
<img>
that is receiving someprops
and then it is displaying{props.children}
.Whenever this component is invoked
{props.children}
will also be displayed and this is just a reference to what is between the opening and closing tags of the component.
//App.js
render () {
return (
<div className='container'>
<Picture key={picture.id} src={picture.src}>
//what is placed here is passed as props.children
</Picture>
</div>
)
}
Instead of invoking the component with a self-closing tag
<Picture />
if you invoke it will full opening and closing tags<Picture> </Picture>
you can then place more code between it.This de-couples the
<Picture>
component from its content and makes it more reusable.
Reference: A quick intro to React’s props.children
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
With PowerShell 5.1 in Windows 10 you can use:
Get-SmbMapping | Remove-SmbMapping -Confirm:$false
Add this code to global.asax
below on Application_Start
:
Update from .Ignore
to .Serialize
. It must work.
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
Use regular expression is best way to doing this as already mentioned by ashish sahu
public int getInt(String s){
return Integer.parseInt(s.replaceAll("[\\D]", ""));
}
For C# .Net to find and replace any guid looking string from the given text,
Use this RegEx:
[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?
Example C# code:
var result = Regex.Replace(
source,
@"[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?",
@"${ __UUID}",
RegexOptions.IgnoreCase
);
Surely works! And it matches & replaces the following styles, which are all equivalent and acceptable formats for a GUID.
"aa761232bd4211cfaacd00aa0057b243"
"AA761232-BD42-11CF-AACD-00AA0057B243"
"{AA761232-BD42-11CF-AACD-00AA0057B243}"
"(AA761232-BD42-11CF-AACD-00AA0057B243)"
DAO is native to Access and by far the best for general use. ADO has its place, but it is unlikely that this is it.
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db=CurrentDB
strSQL = "select * from table where some condition"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
rs.Edit
rs!SomeField = "Abc"
rs!OtherField = 2
rs!ADate = Date()
rs.Update
rs.MoveNext
Loop
import tarfile
tar = tarfile.open("sample.tar.gz", "w:gz")
for name in ["file1", "file2", "file3"]:
tar.add(name)
tar.close()
If you want to create a tar.bz2 compressed file, just replace file extension name with ".tar.bz2" and "w:gz" with "w:bz2".
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml
LocalDateTime#plusHours
LocalDateTime
is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation.
Use LocalDateTime#plusHours
to get a copy of this LocalDateTime
with the specified number of hours added.
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// ZoneId.systemDefault() returns the timezone of your JVM. It is also the
// default timezone for date-time type i.e.
// LocalDateTime.now(ZoneId.systemDefault()) is same as LocalDateTime.now().
// Change the timezone as per your requirement e.g. ZoneId.of("Europe/London")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
System.out.println(ldt);
LocalDateTime after8Hours = ldt.plusHours(8);
System.out.println(after8Hours);
// Custom format
DateTimeFormatter dtfTimeFormat24H = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss", Locale.ENGLISH);
DateTimeFormatter dtfTimeFormat12h = DateTimeFormatter.ofPattern("dd/MM/uuuu hh:mm:ss a", Locale.ENGLISH);
System.out.println(dtfTimeFormat24H.format(after8Hours));
System.out.println(dtfTimeFormat12h.format(after8Hours));
}
}
Output:
2021-01-07T15:24:52.736612
2021-01-07T23:24:52.736612
07/01/2021 23:24:52
07/01/2021 11:24:52 PM
Learn more about the modern date-time API from Trail: Date Time.
Using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
Date currentDateTime = calendar.getTime();
System.out.println(currentDateTime);
// After 8 hours
calendar.add(Calendar.HOUR_OF_DAY, 8);
Date after8Hours = calendar.getTime();
System.out.println(after8Hours);
// Custom formats
SimpleDateFormat sdf24H = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
// Change the timezone as per your requirement e.g.
// TimeZone.getTimeZone("Europe/London")
sdf24H.setTimeZone(TimeZone.getDefault());
SimpleDateFormat sdf12h = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", Locale.ENGLISH);
sdf12h.setTimeZone(TimeZone.getDefault());
System.out.println(sdf24H.format(after8Hours));
System.out.println(sdf12h.format(after8Hours));
}
}
Output:
Thu Jan 07 15:34:10 GMT 2021
Thu Jan 07 23:34:10 GMT 2021
07/01/2021 23:34:10
07/01/2021 11:34:10 PM
String
with the pattern of your choice using date-time formatting API.
java.time.format
e.g. java.time.format.DateTimeFormatter
, java.time.format.DateTimeFormatterBuilder
etc.java.text
e.g. java.text.SimpleDateFormat
, java.text.DateFormat
etc.java.util.Date
object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970
. When you print an object of java.util.Date
, its toString
method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat
and obtain the formatted string from it.java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
I have been having this issue for a couple of weeks and finally decided to sit down and try and fix it. I have no interest in config file editing as I'm primarily a Windows user.
In a fit of "clickyness" I noticed that the ubuntu server location was set "for United kingdom". I switched this over to "Main Server" and hey presto... it all stared updating.
So, it seems like the regionalised server (for the UK at least) has a very limited support window so if you are an infrequent user it is likely it will not have a valid upgrade path from your current version to the latest.
Edit: I only just noticted the previous reply, after posting. 100% agree.
For SQL Server 2008, I would imagine the procedure is similar...?
On page 358 of the book Python scripting for computational science by Hans Petter Langtangen, it clearly states that
__repr__
aims at a complete string representation of the object;__str__
is to return a nice string for printing.So, I prefer to understand them as
from the user's point of view although this is a misunderstanding I made when learning python.
A small but good example is also given on the same page as follows:
In [38]: str('s')
Out[38]: 's'
In [39]: repr('s')
Out[39]: "'s'"
In [40]: eval(str('s'))
Traceback (most recent call last):
File "<ipython-input-40-abd46c0c43e7>", line 1, in <module>
eval(str('s'))
File "<string>", line 1, in <module>
NameError: name 's' is not defined
In [41]: eval(repr('s'))
Out[41]: 's'
According to the official docs, browsers do not like it when you use the
Access-Control-Allow-Origin: "*"
header if you're also using the
Access-Control-Allow-Credentials: "true"
header. Instead, they want you to allow their origin specifically. If you still want to allow all origins, you can do some simple Apache magic to get it to work (make sure you have mod_headers
enabled):
Header set Access-Control-Allow-Origin "%{HTTP_ORIGIN}e" env=HTTP_ORIGIN
Browsers are required to send the Origin
header on all cross-domain requests. The docs specifically state that you need to echo this header back in the Access-Control-Allow-Origin
header if you are accepting/planning on accepting the request. That's what this Header
directive is doing.
Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid
Try the code below. It will work if you enter multiple lines in a single column.
create table products (prod_id number , prod_desc varchar2(50));
insert into products values(1,'test first
test second
test third');
select replace(replace(prod_desc,chr(10),' '),chr(13),' ') from products where prod_id=2;
Output :test first test second test third
Solution1 - set global config, by running this command:
git config --system core.longpaths true
Solution2 - or you can edit directly your specific git config file like below:
YourRepoFolder -> .git -> config:
[core]
repositoryformatversion = 0
filemode = false
...
longpaths = true <-- (add this line under core section)
Solution3 - when cloning a new repository: here.
There's a few ways of doing this. However, here is one of the easiest ways to do this and it's reusable.
What is happening is that we're getting all the properties of the parent class and updating those same properties on the child class. Where baseObj would be the parent object and T would be the child class.
public static T ConvertToDerived<T>(object baseObj) where T : new()
{
var derivedObj = new T();
var members = baseObj.GetType().GetMembers();
foreach (var member in members)
{
object val = null;
if (member.MemberType == MemberTypes.Field)
{
val = ((FieldInfo)member).GetValue(baseObj);
((FieldInfo)member).SetValue(derivedObj, val);
}
else if (member.MemberType == MemberTypes.Property)
{
val = ((PropertyInfo)member).GetValue(baseObj);
if (val is IList && val.GetType().IsGenericType)
{
var listType = val.GetType().GetGenericArguments().Single();
var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(listType));
foreach (var item in (IList)val)
{
list.Add(item);
}
((PropertyInfo)member).SetValue(baseObj, list, null);
}
if (((PropertyInfo)member).CanWrite)
((PropertyInfo)member).SetValue(derivedObj, val);
}
}
return derivedObj;
}
try it.......i solve this problem using code:-
EditText inputArea;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputArea = (EditText) findViewById(R.id.inputArea);
//This line is you answer.Its unable your click ability in this Edit Text
//just write
inputArea.setInputType(0);
}
nothing u can input by default calculator on anything but u can set any string.
try it
I had Java 1.8 but had to downgrade to Java 1.6 for some reason. When I uninstalled java 1.8 and ran the command "Java -Version" from the command prompt, I got the error -
Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'
has value '1.6', but '1.8' is required. Error: could not find java.dll Error: Could not find Java SE Runtime Environment.
Uninstalling 1.6 and then reinstalling 1.6 fixed the issue for me :-)
I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:
PySizer, "a memory profiler for Python," found at http://pysizer.8325.org/. However the page seems to indicate that the project hasn't been updated for a while, and refers to...
Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at http://guppy-pe.sourceforge.net/#Heapy.
Hope that helps.
See my answer to the question Importing modules from parent folder for related information, including why my answer doesn't use the unreliable __file__
variable. This simple solution should be cross-compatible with different operating systems as the modules os
and inspect
come as part of Python.
First, you need to import parts of the inspect and os modules.
from inspect import getsourcefile
from os.path import abspath
Next, use the following line anywhere else it's needed in your Python code:
abspath(getsourcefile(lambda:0))
From the built-in module os
(description below), the abspath
tool is imported.
OS routines for Mac, NT, or Posix depending on what system we're on.
Then getsourcefile
(description below) is imported from the built-in module inspect
.
Get useful information from live Python objects.
abspath(path)
returns the absolute/full version of a file pathgetsourcefile(lambda:0)
somehow gets the internal source file of the lambda function object, so returns '<pyshell#nn>'
in the Python shell or returns the file path of the Python code currently being executed.Using abspath
on the result of getsourcefile(lambda:0)
should make sure that the file path generated is the full file path of the Python file.
This explained solution was originally based on code from the answer at How do I get the path of the current executed file in Python?.
You may use Oracle pipelined functions
Basically, when you would like a PLSQL (or java or c) routine to be the «source» of data -- instead of a table -- you would use a pipelined function.
Simple Example - Generating Some Random Data
How could you create N unique random numbers depending on the input argument?
create type array
as table of number;
create function gen_numbers(n in number default null)
return array
PIPELINED
as
begin
for i in 1 .. nvl(n,999999999)
loop
pipe row(i);
end loop;
return;
end;
Suppose we needed three rows for something. We can now do that in one of two ways:
select * from TABLE(gen_numbers(3));
COLUMN_VALUE
1
2
3
or
select * from TABLE(gen_numbers)
where rownum <= 3;
COLUMN_VALUE
1
2
3
No one said a pure xaml solution has to be complicated. Here's a simple one, with 1 data trigger on the text box. Margin and position as desired
<Grid>
<ComboBox x:Name="mybox" ItemsSource="{Binding}"/>
<TextBlock Text="Select Something" IsHitTestVisible="False">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=mybox,Path=SelectedItem}" Value="{x:Null}">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
If you're doing this in your erb view (for Rails), be mindful of the <%
and <%=
differences. What you'd want is:
<% (1..x).each do |i| %>
Code to display using <%= stuff %> that you want to display
<% end %>
For plain Ruby, you can refer to: http://www.tutorialspoint.com/ruby/ruby_loops.htm
Concatenate the attribute selectors:
input[name="Sex"][value="M"]
You should create a map of actions using the statusCode
setting:
$.ajax({
statusCode: {
400: function() {
alert('400 status code! user error');
},
500: function() {
alert('500 status code! server error');
}
}
});
Reference (Scroll to: 'statusCode')
EDIT (In response to comments)
If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error:
instead of statusCode:
error:function (xhr, ajaxOptions, thrownError){
switch (xhr.status) {
case 404:
// Take action, referencing xhr.responseText as needed.
}
}
I know I'm late on this one, but I'll add this comment anyway, as others may well come here in the future with similar questions.
Beware of tweaking column sizes dependent on locale. For a start, it sets you up for a maintenance nightmare, leaving aside the fact that people migrate, and take their names with them.
For example, Spanish people with those extra surnames can move to and live in an English-speaking country, and can reasonably expect their full name to be used. Russians have patronymics in addition to their surnames, some African names can be considerably longer than most European names.
Go with making each column as wide as you can reasonably do, taking into account the potential row count. I use 40 characters each for first name, other given names and surname and have never found any problems.
You can return a JSON with the URL and change the window.location using JavaScript at client side. I prefer this way than calling a JavaScript function from the server, which I think that it's breaking the separation of concerns.
Server side:
return Json(new {result = "Redirect", url = Url.Action("ActionName", "ControllerName")});
Client side:
if (response.result == 'Redirect')
window.location = response.url;
Of course you can add more logic because there could be an error on the server side and in that case the result property could indicate this situation and avoid the redirection.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
Note: The snippet would only work if the iframe is with the same origin.
Other answers proposed the load
event, but it fires after the new page in the iframe is loaded. You might need to be notified immediately after the URL changes, not after the new page is loaded.
Here's a plain JavaScript solution:
function iframeURLChange(iframe, callback) {_x000D_
var unloadHandler = function () {_x000D_
// Timeout needed because the URL changes immediately after_x000D_
// the `unload` event is dispatched._x000D_
setTimeout(function () {_x000D_
callback(iframe.contentWindow.location.href);_x000D_
}, 0);_x000D_
};_x000D_
_x000D_
function attachUnload() {_x000D_
// Remove the unloadHandler in case it was already attached._x000D_
// Otherwise, the change will be dispatched twice._x000D_
iframe.contentWindow.removeEventListener("unload", unloadHandler);_x000D_
iframe.contentWindow.addEventListener("unload", unloadHandler);_x000D_
}_x000D_
_x000D_
iframe.addEventListener("load", attachUnload);_x000D_
attachUnload();_x000D_
}_x000D_
_x000D_
iframeURLChange(document.getElementById("mainframe"), function (newURL) {_x000D_
console.log("URL changed:", newURL);_x000D_
});
_x000D_
<iframe id="mainframe" src=""></iframe>
_x000D_
This will successfully track the src
attribute changes, as well as any URL changes made from within the iframe itself.
Tested in all modern browsers.
I made a gist with this code as well. You can check my other answer too. It goes a bit in-depth into how this works.
Use the following command at command prompt:
java -jar jenkins.war --httpPort=9090
If you want to use https use the following command:
java -jar jenkins.war --httpsPort=9090
Details are here
While I totally agree there is no simple solution. There continues to be a single point of failure. Either the dockerfile, etcd, and so on. Apcera has a plan that looks like sidekick - dual authentication. In other words two container cannot talk unless there is a Apcera configuration rule. In their demo the uid/pwd was in the clear and could not be reused until the admin configured the linkage. For this to work, however, it probably meant patching Docker or at least the network plugin (if there is such a thing).
It's possible that your configuration variables are cached. Verify your config/app.php
as well as your .env
file then try
php artisan cache:clear
on the command line.
Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
. If you want to use strptime, you need to strip out those variations first.
The goal is to generate a UTC datetime object.
If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z
:
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400
or 2008-09-03T20:56:35.450686+05:00
use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500
making it more consistent/easier to parse.
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
If your system does not support the %z
strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'
) then you need to manually offset the time from Z
(UTC). Note %z
may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (i.e., Jython, Cython, etc.).
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"([+|-])",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
sign = split_timestamp[1]
offset = split_timestamp[2]
else:
sign = None
offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
# Create timedelta based on offset
offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
# Offset datetime with timedelta
output_datetime = output_datetime + offset_delta
Easy way to get the column name
Sub column()
cell=cells(1,1)
column = Replace(cell.Address(False, False), cell.Row, "")
msgbox column
End Sub
I hope it helps =)
This way should work, change "char" to "Character":
public static void main(String[] args){
Character[] list = {'m', 'e', 'y'};
System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}
To remove the variable from the current environment (not permanently):
set FOOBAR=
To permanently remove the variable from the user environment (which is the default place setx
puts it):
REG delete HKCU\Environment /F /V FOOBAR
If the variable is set in the system environment (e.g. if you originally set it with setx /M
), as an administrator run:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
Note: The REG
commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.
If you need to use the latest versions of SciPy rather than the packaged version, without going through the hassle of building BLAS and LAPACK, you can follow the below procedure.
Install linear algebra libraries from repository (for Ubuntu),
sudo apt-get install gfortran libopenblas-dev liblapack-dev
Then install SciPy, (after downloading the SciPy source): python setup.py install
or
pip install scipy
As the case may be.
If by "Ignore Duplicate Error statments", to abort the current statement and continue to the next statement without aborting the trnsaction then just put BEGIN TRY.. END TRY around each statement:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH /*required, but you dont have to do anything */ END CATCH
...
I like to use flutter_mobx for this and work on the state.
Next I use an observer:
Container(child: Observer(builder: (_) {
var method;
if (!controller.isDisabledButton) method = controller.methodController;
return RaiseButton(child: Text('Test') onPressed: method);
}));
On the Controller:
@observable
bool isDisabledButton = true;
Then inside the control you can manipulate this variable as you want.
Refs.: Flutter mobx
Try this custom function.
public static string DataTableToJsonObj(DataTable dt)
{
DataSet ds = new DataSet();
ds.Merge(dt);
StringBuilder jsonString = new StringBuilder();
if (ds.Tables[0].Rows.Count > 0)
{
jsonString.Append("[");
for (int rows = 0; rows < ds.Tables[0].Rows.Count; rows++)
{
jsonString.Append("{");
for (int cols = 0; cols < ds.Tables[0].Columns.Count; cols++)
{
jsonString.Append(@"""" + ds.Tables[0].Columns[cols].ColumnName + @""":");
/*
//IF NOT LAST PROPERTY
if (cols < ds.Tables[0].Columns.Count - 1)
{
GenerateJsonProperty(ds, rows, cols, jsonString);
}
//IF LAST PROPERTY
else if (cols == ds.Tables[0].Columns.Count - 1)
{
GenerateJsonProperty(ds, rows, cols, jsonString, true);
}
*/
var b = (cols < ds.Tables[0].Columns.Count - 1)
? GenerateJsonProperty(ds, rows, cols, jsonString)
: (cols != ds.Tables[0].Columns.Count - 1)
|| GenerateJsonProperty(ds, rows, cols, jsonString, true);
}
jsonString.Append(rows == ds.Tables[0].Rows.Count - 1 ? "}" : "},");
}
jsonString.Append("]");
return jsonString.ToString();
}
return null;
}
private static bool GenerateJsonProperty(DataSet ds, int rows, int cols, StringBuilder jsonString, bool isLast = false)
{
// IF LAST PROPERTY THEN REMOVE 'COMMA' IF NOT LAST PROPERTY THEN ADD 'COMMA'
string addComma = isLast ? "" : ",";
if (ds.Tables[0].Rows[rows][cols] == DBNull.Value)
{
jsonString.Append(" null " + addComma);
}
else if (ds.Tables[0].Columns[cols].DataType == typeof(DateTime))
{
jsonString.Append(@"""" + (((DateTime)ds.Tables[0].Rows[rows][cols]).ToString("yyyy-MM-dd HH':'mm':'ss")) + @"""" + addComma);
}
else if (ds.Tables[0].Columns[cols].DataType == typeof(string))
{
jsonString.Append(@"""" + (ds.Tables[0].Rows[rows][cols]) + @"""" + addComma);
}
else if (ds.Tables[0].Columns[cols].DataType == typeof(bool))
{
jsonString.Append(Convert.ToBoolean(ds.Tables[0].Rows[rows][cols]) ? "true" : "fasle");
}
else
{
jsonString.Append(ds.Tables[0].Rows[rows][cols] + addComma);
}
return true;
}
Making it more visible might help. One example:
Table 1:
ID_STUDENT STUDENT_NAME
1 Raony
2 Diogo
3 Eduardo
4 Luiz
Table 2:
ID_STUDENT LOCKER
3 l1
4 l2
5 l3
What I get when I do:
-Inner join of Table 1 and Table 2:
- Inner join returns both tables merged only when the key
(ID_STUDENT) exists in both tables
ID_STUDENT STUDENT_NAME LOCKER
3 Eduardo l1
4 Luiz l2
-Left join of Table 1 and Table 2:
- Left join merges both tables with all records form table 1, in
other words, there might be non-populated fields from table 2
ID_ESTUDANTE NOME_ESTUDANTE LOCKER
1 Raony -
2 Diogo -
3 Eduardo l1
4 Luiz l2
-Right join of table 1 and table 2:
- Right join merges both tables with all records from table 2, in
other words, there might be non-populated fields from table 1
ID_STUDENT STUDENT_NAME LOCKER
3 Eduardo l1
4 Luiz l2
5 - l3
-Outter join of table 1 and table 2:
- Returns all records from both tables, in other words, there
might be non-populated fields either from table 1 or 2.
ID_STUDENT STUDENT_NAME LOCKER
1 Raony -
2 Diogo -
3 Eduardo l1
4 Luiz l2
5 - l3
Install from package manager:
sudo apt-get install phantomjs
SELECT
[current].rowInt,
[current].Value,
ISNULL([next].Value, 0) - [current].Value
FROM
sourceTable AS [current]
LEFT JOIN
sourceTable AS [next]
ON [next].rowInt = (SELECT MIN(rowInt) FROM sourceTable WHERE rowInt > [current].rowInt)
EDIT:
Thinking about it, using a subquery in the select (ala Quassnoi's answer) may be more efficient. I would trial different versions, and look at the execution plans to see which would perform best on the size of data set that you have...
EDIT2:
I still see this garnering votes, though it's unlikely many people still use SQL Server 2005.
If you have access to Windowed Functions such as LEAD()
, then use that instead...
SELECT
RowInt,
Value,
LEAD(Value, 1, 0) OVER (ORDER BY RowInt) - Value
FROM
sourceTable
I got the same error on my vscode where I had a library installed and the code working when running from the terminal, but for some reason, the vscode pylint was not able to pick the installed package returning the infamous error:
Unable to import 'someLibrary.someModule' pylint(import-error)
The problem might arise due to the multiple Python installations. Basically you have installed a library/package on one, and vscode pylint is installed and running from another installation. For example, on macOS and many Linux distros, there are by default Python2 installed and when you install Python3 this might cause confusion. Also on windows the Chocolatey package manager might cause some mess and you end up with multiple Python installations. To figure it out if you are on a *nix machine (i.e., macOS, GNU/Linux, BSD...), use the which
command, and if you are on Windows, use the where
command to find the installed Python interpreters. For example, on *nix machines:
which python3
and on Windows
where python
then you may want to uninstall the ones you don't want. and the one you want to use check if the package causing above issue is installed by
python -c "import someLibrary"
if you get an error then you should install it by for example pip
:
pip install someLibrary
then on vscode press ??P if you are on a mac and CtrlShiftP on other operating systems. Then type-select the >python: Select Interpreter
option and select the one you know have the library installed. At this moment vscode might asks you to install pyling again, which you just go on with.
argThat
plus lambdathat is how you can fail your argument verification:
verify(mock).mymethod(argThat(
(x)->false
));
where
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
argThat
plus assertsthe above test will "say" Expected: lambda$... Was: YourClass.toSting...
. You can get a more specific cause of the failure if to use asserts in the the lambda:
verify(mock).mymethod(argThat( x -> {
assertThat(x).isNotNull();
assertThat(x.description).contains("KEY");
return true;
}));
??BUT??: THIS ONLY WORKS WHEN
true
).If the verified method called 2+ times, mockito passes all the called combinations to each verifier. So mockito expects your verifier silently returns true
for one of the argument set, and false
(no assert exceptions) for other valid calls. That expectation is not a problem for 1 method call - it should just return true 1 time.
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
Now the failed test will say: Expected: Obj.description to contain 'KEY'. Was: 'Actual description'
. NOTE: I used assertJ
asserts, but it's up to you which assertion framework to use.
argThat
with multiple arguments.If you use argThat
, all arguments must be provided with matches. E.g.:
verify(mock).mymethod(eq("VALUE_1"), argThat((x)->false));
// above is correct as eq() is also an argument matcher.
verify(mock).mymethod("VALUE_1", argThat((x)->false));
// above is incorrect; an exceptoin will be thrown, as the fist arg. is given without an argument matcher.
where:
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
eq
matcherthe easiest way to check if the argument is equal:
verify(mock).mymethod(eq(expectedValue));
// NOTE: ^ where the parentheses must be closed.
if comparison by ref is acceptable, then go on with:
verify(mock).mymethod(expectedArg);
// NOTE: ^ where the parentheses must be closed.
THE ROOT CAUSE of original question failure was the wrong place of the paranthes: verify(mock.mymethod...
. That was wrong. The right would be: verify(mock).*
// Using json as php array
$json = '[{"user_id":"1","user_name":"Sayeed Amin","time":"2019-11-06 13:21:26"}]';
//or use from file
//$json = file_get_contents('results.json');
$someArray = json_decode($json, true);
foreach ($someArray as $key => $value) {
echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}
Since you're using bash, the fastest way would be:
shopt -s extglob # Allow extended globbing
var=" lakdjsf lkadsjf "
echo "${var//+([[:space:]])/}"
It's fastest because it uses built-in functions instead of firing up extra processes.
However, if you want to do it in a POSIX-compliant way, use sed
:
var=" lakdjsf lkadsjf "
echo "$var" | sed 's/[[:space:]]//g'
Just type
document.querySelector('video').playbackRate = 1.25;
in JS console of your modern browser.
Controller :
public ActionResult Refresh(string ID)
{
DetailsViewModel vm = new DetailsViewModel(); // Model
vm.productDetails = _product.GetproductDetails(ID);
/* "productDetails " is a property in "DetailsViewModel"
"GetProductDetails" is a method in "Product" class
"_product" is an interface of "Product" class */
return PartialView("_Details", vm); // Details is a partial view
}
In yore index page you should to have refresh link :
<a href="#" id="refreshItem">Refresh</a>
This Script should be also in your index page:
<script type="text/javascript">
$(function () {
$('a[id=refreshItem]:last').click(function (e) {
e.preventDefault();
var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name
$.ajax({
type: 'GET',
url: url,
cache: false,
success: function (grid) {
$('#tabItemDetails').html(grid);
clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
}
});
});
});
I'm coding a chess engine named foolsmate. The best move extraction using a minimax-based tree search to depth 9 (from a certain position) took:
on Win32
configuration: ~17.0s
;
after switching to x64
configuration: ~10.3s
;
This is 41% of acceleration!
For example 8/12/1976. Copy your date column. Highlight the copied column and click Data> Text to Columns> Delimited> Next. In the delimiters column check "Other" and input / and then click Next and Finish. You'll have 3 columns and the first column will be 1/8. Highlight it and click the comma in the Number section and it will give you the month as 8.00, so then reduce it by clicking the comma in Home/Numbers and you'll now have 8 in the first column, 18 in the second column and 1976 in the third column. In the first empty cell to the right use the concatenate function and leave out the year column. If your month is column A, day is column B and year is column C, it will look like this: =concatenate(A2,"/",B2) and hit enter. It will look like 8/18, however, when you click on the cell you'll see the concatenate formula. Highlight the cell(s), then copy and paste special values. Now you can sort by date. It's really quick when you get the hang of it.
Apache's commons-lang library has a static function org.apache.commons.lang3.EnumUtils.getEnum which will map a String to your Enum type. Same answer essentially as Geoffreys but why roll your own when it's out there in the wild already.
Difference between app.use
& app.get
:
app.use
? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.
app.get
? It is only for handling GET HTTP requests.
Now, there is a confusion between app.use
& app.all
. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests.
But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.
app.use()
? It takes only one callback.
app.all()
? It can take multiple callbacks.
app.use()
will only see whether url starts with specified path.
But, app.all()
will match the complete path.
For example,
app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject
app.all( "/book" , handler);
// will match /book
// won't match /book/author
// won't match /book/subject
app.all( "/book/*" , handler);
// won't match /book
// will match /book/author
// will match /book/subject
next()
call inside the app.use()
will call either the next middleware or any route handler, but next()
call inside app.all()
will invoke the next route handler (app.all()
, app.get/post/put...
etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.You cannot delete an managed object in C# . That's why is called MANAGED language. So you don't have to troble yourself with delete (just like in c++).
It is true that you can set it's instance to null. But that is not going to help you that much because you have no control of your GC (Garbage collector) to delete some objects apart from Collect. And this is not what you want because this will delete all your collection from a generation.
So how is it done then ? So : GC searches periodically objects that are not used anymore and it deletes the object with an internal mechanism that should not concern you.
When you set an instance to null you just notify that your object has no referene anymore ant that could help CG to collect it faster !!!
if u want to write a JSON object to the response then change the header content type to application/json
response.writeHead(200, {"Content-Type": "application/json"});
var d = new Date(parseURL.query.iso);
var postData = {
"hour" : d.getHours(),
"minute" : d.getMinutes(),
"second" : d.getSeconds()
}
response.write(postData)
response.end();
To convert any object to string there are several methods in Java
String convertedToString = String.valueOf(Object); //method 1
String convertedToString = "" + Object; //method 2
String convertedToString = Object.toString(); //method 3
I would prefer the first and third
EDIT
If working in kotlin, the official android language
val number: Int = 12345
String convertAndAppendToString = "number = $number" //method 1
String convertObjectMemberToString = "number = ${Object.number}" //method 2
String convertedToString = Object.toString() //method 3
The input in the markup is missing "type"
, the input (text I assume) has the attribute name="name"
and ID="cname"
, the provided code by Ayo calls the input named "cname"* where it should be "name".
To disable the errors windows related with certificates you can start Chrome from console and use this option: --ignore-certificate-errors
.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --ignore-certificate-errors
You should use it for testing purposes. A more complete list of options is here: http://peter.sh/experiments/chromium-command-line-switches/
I agree with superjoe30 above, but I don't have enough reputation yet to leave a comment.
I was a C.S. professor for 4 years. The languages were Basic, and then Pascal, but it doesn't really matter what the language is.
The biggest lesson I learned as a new prof was, no matter how simple I thought a concept was, it is not simple to a newbie. Never go any faster than your student can go. I can't emphasize that enough. Go really, really slow.
I would start with very simple stuff, read and print, maybe a simple calculation, just to get the student used to putting something in and getting something out. Then IF statements. Then really simple FOR loops, always in terms of something the student could write and have some fun with.
Then I would spend about 3 weeks teaching a very simple sort of machine language for a phony decimal machine called SIMPL, that you could single-step. The reason for doing this so the student could see where the "rubber meets the road", that computers do things step-by-step, and it makes a difference what order things happen in. Without that, students tend to think the computer can sort of read their mind and do everything all at once.
Then back to Basic. A couple weeks on arrays, because that is a big speed bump. Then sequential files, which is another speed bump. What I mean by "speed bump" is the student can be sailing along feeling quite confident, and then you hit them with a concept like arrays, and they are totally lost again, until you ease them through it.
Then, with those skills under their belts, I would have them pick a term project, because that is what makes programming interesting. Without a use for it, it's really boring. I would suggest a variety of projects, such as games, accounting programs, science programs, etc. It's really great to see them get turned on. Often they would ask me for help, and that's great, because you know they're learning.
While they were doing their projects, we would continue to cover more advanced programming techniques - searching, sorting, merging, how to make a simple database, etc.
Good luck. Teaching is hard work but satisfying when you see students grow.
You may not want to disable all ssl Verificatication and so you can just disable the hostName verification via this which is a bit less scary than the alternative:
HttpsURLConnection.setDefaultHostnameVerifier(
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
[EDIT]
As mentioned by conapart3 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
is now deprecated, so it may be removed in a later version, so you may be forced in the future to roll your own, although I would still say I would steer away from any solutions where all verification is turned off.