Until Android 7.1 you will get it with:
Build.SERIAL
On Android 8 (SDK 26) and above, this field will return UNKNOWN
and must be accessed with:
Build.getSerial()
which requires the dangerous permission
android.permission.READ_PHONE_STATE
.
Since Android Q using Build.getSerial()
gets a bit more complicated by requiring:
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE
(which can only be acquired by system apps), or for the calling package to be the device or profile owner and have the READ_PHONE_STATE
permission. This means most apps won't be able to uses this feature. See the Android Q announcement from Google.
If you just require a unique identifier, it's best to avoid using hardware identifiers as Google continuously tries to make it harder to access them for privacy reasons. You could just generate a UUID.randomUUID().toString();
and save it the first time it needs to be accessed in e.g. shared preferences. Alternatively you could use ANDROID_ID
which is a 8 byte long hex string unique to the device, user and (only Android 8+) app installation. For more info on that topic, see Best practices for unique identifiers.
As @haserman says:
TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();
But it's necessary including the permission in the manifest file:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
The easiest way to do it is to add mb-5
to your classes. That is <div class='row mb-5'>
.
NOTE:
mb
varies betweeen 1 to 5TLDR; Try setting JAVA_HOME worked fine for me on OSX
export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
To install the JDKs 8 ( LTS ) from AdoptOpenJDK:
# brew tap adoptopenjdk/openjdk
brew cask install adoptopenjdk/openjdk/adoptopenjdk8
You do not need to use an anonymous function with setTimeout
. You can do something like this:
setTimeout(doSomething, 3000);
function doSomething() {
//do whatever you want here
}
You can solve your problem with help of Attribute routing
Controller
[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }
URI in jquery
api/category/1
Route Configuration
using System.Web.Http;
namespace WebApplication
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
}
and your default routing is working as default convention-based routing
Controller
public string Get(int id)
{
return "object of id id";
}
URI in Jquery
/api/records/1
Route Configuration
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Review article for more information Attribute routing and onvention-based routing here & this
After August 7, 2016 you can still make your call like this:
http://graph.facebook.com/?id=https://www.apple.com/
but the response format is going to be different: it won't be
{
"id": "http://www.apple.com",
"shares": 1146997
}
but instead it will be
{
"og_object": {
"id": "388265801869",
"description": "Get a first look at iPhone 7, Apple Watch Series 2, and the new AirPods \u2014 the future of wireless headphones. Visit the site to learn more.",
"title": "Apple",
"type": "website",
"updated_time": "2016-09-20T08:21:03+0000"
},
"share": {
"comment_count": 1,
"share_count": 1094227
},
"id": "https://www.apple.com"
}
So you will have to process the response like this:
reponse_variable.share.share_count
In case someone is looking for a universal event handler the following code can be used more or less (assuming that name property is set for every input):
this.handleInputChange = (e) => {
item[e.target.name] = e.target.type === "checkbox" ? e.target.checked : e.target.value;
}
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
You are running the [
(aka test
) command with the argument "false", not running the command false
. Since "false" is a non-empty string, the test
command always succeeds. To actually run the command, drop the [
command.
if false; then
echo "True"
else
echo "False"
fi
A DLL uses the PE executable format, and it's not too tricky to read that information out of the file.
See this MSDN article on the PE File Format for an overview. You need to read the MS-DOS header, then read the IMAGE_NT_HEADERS structure. This contains the IMAGE_FILE_HEADER structure which contains the info you need in the Machine member which contains one of the following values
This information should be at a fixed offset in the file, but I'd still recommend traversing the file and checking the signature of the MS-DOS header and the IMAGE_NT_HEADERS to be sure you cope with any future changes.
You can also use the ImageHelp API to do this - load the DLL with LoadImage and you'll get a LOADED_IMAGE structure which will contain a pointer to an IMAGE_NT_HEADERS structure. Deallocate the LOADED_IMAGE with ImageUnload.
Here's rough Perl script which gets the job done. It checks the file has a DOS header, then reads the PE offset from the IMAGE_DOS_HEADER 60 bytes into the file.
It then seeks to the start of the PE part, reads the signature and checks it, and then extracts the value we're interested in.
#!/usr/bin/perl
#
# usage: petype <exefile>
#
$exe = $ARGV[0];
open(EXE, $exe) or die "can't open $exe: $!";
binmode(EXE);
if (read(EXE, $doshdr, 64)) {
($magic,$skip,$offset)=unpack('a2a58l', $doshdr);
die("Not an executable") if ($magic ne 'MZ');
seek(EXE,$offset,SEEK_SET);
if (read(EXE, $pehdr, 6)){
($sig,$skip,$machine)=unpack('a2a2v', $pehdr);
die("No a PE Executable") if ($sig ne 'PE');
if ($machine == 0x014c){
print "i386\n";
}
elsif ($machine == 0x0200){
print "IA64\n";
}
elsif ($machine == 0x8664){
print "AMD64\n";
}
else{
printf("Unknown machine type 0x%lx\n", $machine);
}
}
}
close(EXE);
In SQL SERVER you do it like this:
SELECT *
INTO A
FROM dbo.myView
This will create a new table A
with the contents of your view.
See here for more info.
If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
Invalid Example:
function findAll() {
$query=<<<SQL
SELECT * FROM `table_1`;
SQL;
// ... omitted
}
This will throw an exception that resembles the following:
<br />
<b>Parse error</b>: syntax error, unexpected end of file in <b>[...][...]</b> on line <b>5</b><br />
where number 5 might be the last line number of your file.
According to php manual:
Warning It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including macOS. The closing delimiter must also be followed by a newline.
TLDR: Closing identifiers should NOT be indented.
Valid Example:
function findAll() {
$query=<<<SQL
SELECT * FROM `table_1`;
SQL;
// closing identifier should not be indented, although it might look ugly
// ... omitted
}
There is an open-source library that has such a function, and it has cross-platform implementations: https://github.com/OpenHFT/Java-Thread-Affinity
It may be overkill just to get the PID, but if you want other things like CPU and thread id, and specifically thread affinity, it may be adequate for you.
To get the current thread's PID, just call Affinity.getAffinityImpl().getProcessId()
.
This is implemented using JNA (see arcsin's answer).
If your trying to fade the backgound image but leave the foreground text/images you could use css to separate the background image into a new div and position it over the div containing the text/images then fade the background div.
Maybe my response quite late, but it covers API below and above 21 level.
To add headers we should intercept every request and create new one with required headers.
So we need to override shouldInterceptRequest method called in both cases: 1. for API until level 21; 2. for API level 21+
webView.setWebViewClient(new WebViewClient() {
// Handle API until level 21
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return getNewResponse(url);
}
// Handle API 21+
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
return getNewResponse(url);
}
private WebResourceResponse getNewResponse(String url) {
try {
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url.trim())
.addHeader("Authorization", "YOU_AUTH_KEY") // Example header
.addHeader("api-key", "YOUR_API_KEY") // Example header
.build();
Response response = httpClient.newCall(request).execute();
return new WebResourceResponse(
null,
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
} catch (Exception e) {
return null;
}
}
});
If response type should be processed you could change
return new WebResourceResponse(
null, // <- Change here
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
to
return new WebResourceResponse(
getMimeType(url), // <- Change here
response.header("content-encoding", "utf-8"),
response.body().byteStream()
);
and add method
private String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
switch (extension) {
case "js":
return "text/javascript";
case "woff":
return "application/font-woff";
case "woff2":
return "application/font-woff2";
case "ttf":
return "application/x-font-ttf";
case "eot":
return "application/vnd.ms-fontobject";
case "svg":
return "image/svg+xml";
}
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
Lodash _.isEqual
allows you to do that:
var_x000D_
remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"},_x000D_
localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"};_x000D_
_x000D_
console.log( _.isEqual(remoteJSON, localJSON) );
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
match_parent
(Full width):
SizedBox(
width: double.infinity, // <-- match_parent
child: RaisedButton(...)
)
Specific width:
SizedBox(
width: 100, // <-- Your width
child: RaisedButton(...)
)
Unfortunately DEBUG
is overloaded heavily. For instance, it's recommended to always generate and save a pdb file for RELEASE builds. Which means one of the -Zx
flags, and -DEBUG
linker option. While _DEBUG
relates to special debug versions of runtime library such as calls to malloc
and free
. Then NDEBUG
will disable assertions.
How about something like:
includes = $(wildcard include/*.h)
%.o: %.c ${includes}
gcc -Wall -Iinclude ...
You could also use the wildcards directly, but I tend to find I need them in more than one place.
Note that this only works well on small projects, since it assumes that every object file depends on every header file.
For Xamarin iOS
btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);
I fixed this by restarting VS.
I had opened a config file in another instance of VS and apparently sth went nuts...
when you operate 4500/1000 in python, result will be 4, because for default python asume as integer the result, logically: 4500/1000 = 4.5 --> int(4.5) = 4 and ceil of 4 obviouslly is 4
using 4500/1000.0 the result will be 4.5 and ceil of 4.5 --> 5
Using javascript you will recieve 4.5 as result of 4500/1000, because javascript asume only the result as "numeric type" and return a result directly as float
Good Luck!!
onCreate()
When we create DataBase at a first time (i.e Database is not exists) onCreate()
create database with version which is passed in
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
onCreate()
method is creating the tables you’ve defined and executing any other code you’ve written. However, this method will only be called if the SQLite file is missing in your app’s data directory (/data/data/your.apps.classpath/databases
).
This method will not be called if you’ve changed your code and relaunched in the emulator. If you want onCreate()
to run you need to use adb to delete the SQLite database file.
onUpgrade()
SQLiteOpenHelper
should call the super constructor.onUpgrade()
method will only be called when the version integer is larger than the current version running in the app.onUpgrade()
method to be called, you need to increment the version number in your code.A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.
The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.
EDIT 2019:
The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:
CREATE TABLE Source
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)
SELECT *,
ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
newid() as GroupKey,
CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;
UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 GroupKey
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID = sup.DepartmentID AND
NOT EXISTS
(
SELECT *
FROM #RankedData bot
WHERE bot.EmployeeID = sup.EmployeeID AND
bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
bot.DepartmentID <> sup.DepartmentID
)
ORDER BY DateStarted ASC
) beginDate (GroupKey);
UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 DateStarted
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID <> sup.DepartmentID AND
sub.EntryRank > sup.EntryRank
ORDER BY EntryRank ASC
) nextGroup (DateStarted);
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;
DROP TABLE #RankedData
DROP TABLE Source
I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.
What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;
If you do go down the inline-block route then you may have to consider my favorite IE hack.
width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only
Happy Coding :)
While sourceSets
allows you to include entire directory structures, there's no way to exclude parts of it in Android Studio (as of version 1.2), as described here: Android Studio Exclude Class from build?
Until Android Studio gets updated to support include/exclude directives for Android sources, Symlinks work quite well. If you're using Windows, native tools such as junction
or mklink
can accomplish the equivalent of Un*x symlinks. CygWin can also create these with a little coersion. See: Git Symlinks in Windows and How to make symbolic link with cygwin in Windows 7
You need to seed your PRNG so it starts with a different value each time.
A simple but low quality seed is to use the current time:
srand(time(0));
This will get you started but is considered low quality (i.e. for example, don't use that if you are trying to generate RSA keys).
Background. Pseudo-random number generators do not create true random number sequences but just simulate them. Given a starting point number, a PRNG will always return the same sequence of numbers. By default, they start with the same internal state so will return the same sequence.
To not get the same sequence, you change the internal state. The act of changing the internal state is called "seeding".
you may forgot to wrap your object with $()
var tableChild = children[i];
tableChild.val("my Value");// this is wrong
and the ccorrect one is
$(tableChild).val("my Value");// this is correct
As the documentation states [docs],
In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.
Note that although the main stated use case this error is the indication of abstract methods that should be implemented on inherited classes, you can use it anyhow you'd like, like for indication of a TODO
marker.
You can also use Array.from
.
var m = "Hello world!";
console.log(Array.from(m))
_x000D_
This method has been introduced in ES6.
For windows eclipse using java: Windows -> Preferences -> Java -> Editor -> Folding
Unfortunately this will not allow for collapsing code, however if it turns off you can re-enable it to get rid of long comments and imports.
i tend to use simple forward code as much as i can ,below code worked fine with me
using System;
using System.IO;
using System.Text.RegularExpressions;
/// <summary>
/// Replaces text in a file.
/// </summary>
/// <param name="filePath">Path of the text file.</param>
/// <param name="searchText">Text to search for.</param>
/// <param name="replaceText">Text to replace the search text.</param>
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
StreamReader reader = new StreamReader( filePath );
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace( content, searchText, replaceText );
StreamWriter writer = new StreamWriter( filePath );
writer.Write( content );
writer.Close();
}
For saving a file as .htaccess, when using windows, you have to open notepad and then saveas .htaccess as windows does not create files starting with a dot. That should get your .htaccess working and it'll clear up the issue.
By the way, in order to receive specific error messages set Configure::write('debug', 0); to '2' in app/config/core.php
for development purposes.
Simple command to check keras version:
(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)
>>> import keras
Using TensorFlow backend.
>>> keras.__version__
'2.2.4'
If you plan on getting a random value a lot, you might want to define a function for it.
First, put this in your code somewhere:
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
Now:
[1,2,3,4].sample() //=> a random element
Code released into the public domain under the terms of the CC0 1.0 license.
GET:
with JSON:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" http://hostname/resource
with XML:
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
POST:
For posting data:
curl --data "param1=value1¶m2=value2" http://hostname/resource
For file upload:
curl --form "[email protected]" http://hostname/resource
RESTful HTTP Post:
curl -X POST -d @filename http://hostname/resource
For logging into a site (auth):
curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/
If you want to do this to an inline svg that is, for example, a background image in your css:
background: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='rgba(31,159,215,1)' viewBox='...'/%3E%3C/svg%3E");
_x000D_
of course, replace the ... with your inline image code
Once you are quite good in Java SE (lets say you are able to pass SCJP), I'd suggest you get junior Java programmer job and improve yourself on real world problems
However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...
IMHO, this is similar to saying "If you can prove that your program will never have any bugs in the future, then go ahead..."
In all seriousness, forcing the GC is useful for debugging/testing purposes. If you feel like you need to do it at any other times, then either you are mistaken, or your program has been built wrong. Either way, the solution is not forcing the GC...
http://skeletoncoder.blogspot.com/2006/09/java-tutorials-why-no-unsigned.html
This guy says because the C standard defines operations involving unsigned and signed ints to be treated as unsigned. This could cause negative signed integers to roll around into a large unsigned int, potentially causing bugs.
glob.glob
or os.listdir
will do it.
For those stuck with "The requested resource is not available" in Java EE 7 and dynamic web module 3.x, maybe this could help: the "Create Servlet" wizard in Eclipse (tested in Mars) doesn't create the @Path annotation for the servlet class, but I had to include it to access successfuly to the public methods exposed.
add following lines in gitignore, from all undesirable files
/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
!
is non-null assertion operator (post-fix expression) - it just saying to type checker that you're sure that a
is not null
or undefined
.
the operation
a!
produces a value of the type ofa
withnull
andundefined
excluded
Optional chaining finally made it to typescript (3.7)
The optional chaining operator
?.
permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The?.
operator functions similarly to the.
chaining operator, except that instead of causing an error if a reference is nullish (null
orundefined
), the expression short-circuits with a return value ofundefined
. When used with function calls, it returnsundefined
if the given function does not exist.
Syntax:
obj?.prop // Accessing object's property
obj?.[expr] // Optional chaining with expressions
arr?.[index] // Array item access with optional chaining
func?.(args) // Optional chaining with function calls
Pay attention:
Optional chaining is not valid on the left-hand side of an assignment
const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment
This assumes SQL Server 2005+ and your definition of "last" is the max PK for a given email
WITH CTE AS
(
SELECT ID,
Email,
ProductName,
ProductModel,
ROW_NUMBER() OVER (PARTITION BY Email ORDER BY ID DESC) AS RowNumber
FROM Products
)
SELECT ID,
Email,
ProductName,
ProductModel
FROM CTE
WHERE RowNumber = 1
To bring more prominence to the useful comment by @johanvdw:
If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile
file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/"
somewhere in the file.
When Cygwin starts, it'll search directories in PATH and this one for executable files to run.
Best guess:
var cur_value = $('#select-id').children('option:selected').text();
I like children better in this case because you know you're only going one branch down the DOM tree...
Yes, you can.
this.formGroup.get('name of you control').value
Ruby automatically converts integers to a large integer class when they overflow, so there's (practically) no limit to how big they can be.
If you are looking for the machine's size, i.e. 64- or 32-bit, I found this trick at ruby-forum.com:
machine_bytes = ['foo'].pack('p').size
machine_bits = machine_bytes * 8
machine_max_signed = 2**(machine_bits-1) - 1
machine_max_unsigned = 2**machine_bits - 1
If you are looking for the size of Fixnum objects (integers small enough to store in a single machine word), you can call 0.size
to get the number of bytes. I would guess it should be 4 on 32-bit builds, but I can't test that right now. Also, the largest Fixnum is apparently 2**30 - 1
(or 2**62 - 1
), because one bit is used to mark it as an integer instead of an object reference.
you could disable transaction via "set_isolation_level(0)"
This is similar to xunil154's answer, except that a string is made a char array and a linked hashmap is used to maintain the insertion order of the characters.
String text = "aasjjikkk";
char[] charArray = text.toCharArray();
Map<Character, Integer> freqList = new LinkedHashMap<Character, Integer>();
for(char key : charArray) {
if(freqList.containsKey(key)) {
freqList.put(key, freqList.get(key) + 1);
} else
freqList.put(key, 1);
}
From SQL Server 2016 you can just use
DROP TABLE IF EXISTS ##CLIENTS_KEYWORD
On previous versions you can use
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You could also consider truncating the table instead rather than dropping and recreating.
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
I am sharing my understanding of Monads, which may not be theoretically perfect. Monads are about Context propagation. Monad is, you define some context for some data (or data type(s)), and then define how that context will be carried with the data throughout its processing pipeline. And defining context propagation is mostly about defining how to merge multiple contexts (of same type). Using Monads also means ensuring these contexts are not accidentally stripped off from the data. On the other hand, other context-less data can be brought into a new or existing context. Then this simple concept can be used to ensure compile time correctness of a program.
The most important thing is, the action created must return partial view, see below.
public ActionResult _YourPartialViewSection()
{
return PartialView();
}
Save yourself the headache of trying to find a "built-in" solution.
There isn't a good answer, and the hugely upvoted answer in this thread is wrong.
npm install is-number
In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:
console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+' '); //=> 0
console.log(typeof NaN); //=> 'number'
I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.
I found a hint in the following question - Python: Histogram with area normalized to something other than 1
But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data
If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.
import matplotlib.pyplot as plt
# Let X be the array whose histogram needs to be plotted.
nx, xbins, ptchs = plt.hist(X, bins=20)
plt.clf() # Get rid of this histogram since not the one we want.
nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
width = xbins[1] - xbins[0] # Width of each bin.
x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
y = np.ravel(zip(nx_frac,nx_frac))
plt.plot(x,y,linestyle="dashed",label="MyLabel")
#... Further formatting.
This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.
Just thought I'd share my experience. Thank you.
In visual studio, go to help | about and look at the version of Visual Studio that you're using to compile your app.
A small note about the efficiency of abovementioned methods:
library(microbenchmark)
microbenchmark(
which("Feb" == month.abb)[[1]],
which(month.abb %in% "Feb"))
Unit: nanoseconds
min lq mean median uq max neval
891 979.0 1098.00 1031 1135.5 3693 100
1052 1175.5 1339.74 1235 1390.0 7399 100
So, the best one is
which("Feb" == month.abb)[[1]]
You are referring to the section "2.3.5 Deploying the demo app" of this "Ruby on Rails Tutorial ":
In section 2.3.1 Planning the application, note that they did:
$ git remote add origin [email protected]:<username>/demo_app.git
$ git push origin master
That is why a simple git push
worked (using here an ssh address).
Did you follow that step and made that first push?
www.github.com/levelone/demo_app
wouldn't be a writable URI for pushing to a GitHub repo.
https://[email protected]/levelone/demo_app.git
should be more appropriate.
Check what git remote -v returns, and if you need to replace the remote address, as described in GitHub help page, use git remote --set-url
.
git remote set-url origin https://[email protected]/levelone/demo_app.git
or
git remote set-url origin [email protected]:levelone/demo_app.git
You can use nested elements and padding to get a left and right edge on the toolbar. The default width of a div
element is auto
, which means that it uses the available width. You can then add padding to the element and it still keeps within the available width.
Here is an example that you can use for putting images as left and right rounded corners, and a center image that repeats between them.
The HTML:
<div class="Header">
<div>
<div>This is the dynamic center area</div>
</div>
</div>
The CSS:
.Header {
background: url(left.gif) no-repeat;
padding-left: 30px;
}
.Header div {
background: url(right.gif) top right no-repeat;
padding-right: 30px;
}
.Header div div {
background: url(center.gif) repeat-x;
padding: 0;
height: 30px;
}
By HTML specifications, browsers are required to canonicalize line breaks in user input to CR LF (\r\n
), and I don’t think any browser gets this wrong. Reference: clause 17.13.4 Form content types in the HTML 4.01 spec.
In HTML5 drafts, the situation is more complicated, since they also deal with the processes inside a browser, not just the data that gets sent to a server-side form handler when the form is submitted. According to them (and browser practice), the textarea
element value exists in three variants:
Based on this blog, one could share a docker image without a docker registry by executing:
docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0
Once this command has been completed, one could copy the image to a server and import it as follows:
docker load --input latestversion-1.0.0.tar
Keep in mind that display will depend on culture. And while in most cases all other answers are correct, it did not work for me. Culture issue will also cause different problems with jQuery datepicker, if attached.
If you wish to force the format escape /
in the following manner:
@Html.TextBoxFor(model => model.dtArrivalDate, "{0:MM\\/dd\\/yyyy}")
If not escaped for me it show 08-01-2010
vs. expected 08/01/2010
.
Also if not escaped jQuery datepicker will select different defaultDate, in my instance it was May 10, 2012
.
There is a command-line utility xcodebuild
and you can run shell command within xcode.
So, if you don't mind using custom script, this script may help you.
#Configurations.
#This script designed for Mac OS X command-line, so does not use Xcode build variables.
#But you can use it freely if you want.
TARGET=sns
ACTION="clean build"
FILE_NAME=libsns.a
DEVICE=iphoneos3.2
SIMULATOR=iphonesimulator3.2
#Build for all platforms/configurations.
xcodebuild -configuration Debug -target ${TARGET} -sdk ${DEVICE} ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO
xcodebuild -configuration Debug -target ${TARGET} -sdk ${SIMULATOR} ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO
xcodebuild -configuration Release -target ${TARGET} -sdk ${DEVICE} ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO
xcodebuild -configuration Release -target ${TARGET} -sdk ${SIMULATOR} ${ACTION} RUN_CLANG_STATIC_ANALYZER=NO
#Merge all platform binaries as a fat binary for each configurations.
DEBUG_DEVICE_DIR=${SYMROOT}/Debug-iphoneos
DEBUG_SIMULATOR_DIR=${SYMROOT}/Debug-iphonesimulator
DEBUG_UNIVERSAL_DIR=${SYMROOT}/Debug-universal
RELEASE_DEVICE_DIR=${SYMROOT}/Release-iphoneos
RELEASE_SIMULATOR_DIR=${SYMROOT}/Release-iphonesimulator
RELEASE_UNIVERSAL_DIR=${SYMROOT}/Release-universal
rm -rf "${DEBUG_UNIVERSAL_DIR}"
rm -rf "${RELEASE_UNIVERSAL_DIR}"
mkdir "${DEBUG_UNIVERSAL_DIR}"
mkdir "${RELEASE_UNIVERSAL_DIR}"
lipo -create -output "${DEBUG_UNIVERSAL_DIR}/${FILE_NAME}" "${DEBUG_DEVICE_DIR}/${FILE_NAME}" "${DEBUG_SIMULATOR_DIR}/${FILE_NAME}"
lipo -create -output "${RELEASE_UNIVERSAL_DIR}/${FILE_NAME}" "${RELEASE_DEVICE_DIR}/${FILE_NAME}" "${RELEASE_SIMULATOR_DIR}/${FILE_NAME}"
Maybe looks inefficient(I'm not good at shell script), but easy to understand. I configured a new target running only this script. The script is designed for command-line but not tested in :)
The core concept is xcodebuild
and lipo
.
I tried many configurations within Xcode UI, but nothing worked. Because this is a kind of batch processing, so command-line design is more suitable, so Apple removed batch build feature from Xcode gradually. So I don't expect they offer UI based batch build feature in future.
Just to show another way of doing it:
def mock_isdir(path):
return path in ['/var/log', '/var/log/apache2', '/var/log/tomcat']
with mock.patch('os.path.isdir') as os_path_isdir:
os_path_isdir.side_effect = mock_isdir
Simple you can cast int to enum
public enum DaysOfWeeks
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7,
}
var day= (DaysOfWeeks)5;
Console.WriteLine("Day is : {0}", day);
Console.ReadLine();
The well-described answer is already there, but I went through this SHORTER recipe:
$ brew install glfw
cd /home/linuxbrew/.linuxbrew/Cellar/glfw/X.X/include
sudo cp -R GLFW /usr/include
Explanation: We manage to build GLFW by CMAKE which is done by Linuxbrew (Linux port of beloved Homebrew). Then copy the header files to where Linux reads from (/usr/include
).
Should be AND instead of OR
select *
from MyTable
where CAST(Created as time) >= '23:00:00'
AND CAST(Created as time) < '07:00:00'
This will call methods from dictionary
This is python switch statement with function calling
Create few modules as per the your requirement. If want to pass arguments then pass.
Create a dictionary, which will call these modules as per requirement.
def function_1(arg):
print("In function_1")
def function_2(arg):
print("In function_2")
def function_3(fileName):
print("In function_3")
f_title,f_course1,f_course2 = fileName.split('_')
return(f_title,f_course1,f_course2)
def createDictionary():
dict = {
1 : function_1,
2 : function_2,
3 : function_3,
}
return dict
dictionary = createDictionary()
dictionary[3](Argument)#pass any key value to call the method
Something like this:
<?php
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/js/yourscript.js');
$cs->registerCssFile($baseUrl.'/css/yourcss.css');
?>
This solution doesn't need web.config file changes or catch-all routes.
First, create a controller like this;
public class ErrorController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Regular Error";
return View();
}
public ActionResult NotFound404()
{
ViewBag.Title = "Error 404 - File not Found";
return View("Index");
}
}
Then create the view under "Views/Error/Index.cshtml" as;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>We're sorry, page you're looking for is, sadly, not here.</p>
Then add the following in the Global asax file as below:
protected void Application_Error(object sender, EventArgs e)
{
// Do whatever you want to do with the error
//Show the custom error page...
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
{
routeData.Values["action"] = "Index";
}
else
{
// Handle 404 error and response code
Response.StatusCode = 404;
routeData.Values["action"] = "NotFound404";
}
Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
IController errorsController = new ErrorController();
HttpContextWrapper wrapper = new HttpContextWrapper(Context);
var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
errorsController.Execute(rc);
Response.End();
}
If you still get the custom IIS error page after doing this, make sure the following sections are commented out(or empty) in the web config file:
<system.web>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<httpErrors>
</httpErrors>
</system.webServer>
Your code gets the DirectorySecurity
for a given directory, and handles an exception (due to your not having access to the security info) correctly. However, in your sample you don't actually interrogate the returned object to see what access is allowed - and I think you need to add this in.
In newer JavaScript standards like ES5 and ES6 you can just say
> Boolean(0) //false
> Boolean(null) //false
> Boolean(undefined) //false
all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say
if (Boolean(myvar)){
// Do something
}
here "null" or "empty string" or "undefined" will be handled efficiently.
I do prefer this one (from solutions above):
truncate -s 0 /var/lib/docker/containers/*/*-json.log
However I'm running several systems (Ubuntu 18.x Bionic for example), where this path does not work as expected. Docker is installed through Snap, so the path to containers is more like:
truncate -s 0 /var/snap/docker/common/var-lib-docker/containers/*/*-json.log
I've had this error on and off for around two years in a several XLSM files (which is most annoying as when it occurs there is nothing wrong with the file! - I suspect orphaned Excel processes are part of the problem)
The most efficient solution I had found has been to use Python with oletools
https://github.com/decalage2/oletools/wiki/Install
and extract the VBA code all the modules and save in a text file.
Then I simply rename the file to zip file (backup just in case!), open up this zip file and delete the xl/vbaProject.bin file. Rename back to XLSX and should be good to go.
Copy in the saved VBA code (which will need cleaning of line breaks, comments and other stuff. Will also need to add in missing libraries.
This has saved me when other methods haven't.
YMMV.
Programatically this can be achieved with SCHTASKS:
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat"
In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> sum(l)
6
>>> sum = 0 # oops! shadowed a builtin!
>>> sum(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> import sys
>>> sum = sys.modules['__builtin__'].sum # -- fixing sum
>>> sum(l)
6
This also comes in handy if you happened to assign a value to any other builtin, like dict
or list
When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify()
.
Here is a working example:
var fs = require('fs');
var originalNote = {
title: 'Meeting',
description: 'Meeting John Doe at 10:30 am'
};
var originalNoteString = JSON.stringify(originalNote);
fs.writeFileSync('notes.json', originalNoteString);
var noteString = fs.readFileSync('notes.json');
var note = JSON.parse(noteString);
console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);
Hope it could help.
GET is visible to anyone (even the one on your shoulder now) and is saved on cache, so is less secure of using post, btw post without some cryptographics routine is not sure, for a bit of security you've to use SSL (https)
You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.
So, instead of simply calling addWord("someWord")
, you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();
), and then call the method using that (i.e. list.addWord("someWord");
.
However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord()
static, or change the methods in the Words class so that they're not static.
My bad with the above paragraph - however you might want to reconsider ProcessInput()
being a static method - does it really need to be?
in my case i was using compile sdk 23
and build tools 25.0.0
just changed compile sdk
to 25 and done..
More points regarding File Descriptor
:
File Descriptors
(FD) are non-negative integers (0, 1, 2, ...)
that are associated with files that are opened.
0, 1, 2
are standard FD's that corresponds to STDIN_FILENO
, STDOUT_FILENO
and STDERR_FILENO
(defined in unistd.h
) opened by default on behalf of shell when the program starts.
FD's are allocated in the sequential order, meaning the lowest possible unallocated integer value.
FD's for a particular process can be seen in /proc/$pid/fd
(on Unix based systems).
Constructor overloading is like method overloading. Constructors can be overloaded to create objects in different ways.
The compiler differentiates constructors based on how many arguments are present in the constructor and other parameters like the order in which the arguments are passed.
For further details about java constructor, please visit https://tecloger.com/constructor-in-java/
I find that there are 3 package-based solutions to solve the problem. They are pyenchant, wordnet and corpus(self-defined or from ntlk). Pyenchant couldn't installed easily in win64 with py3. Wordnet doesn't work very well because it's corpus isn't complete. So for me, I choose the solution answered by @Sadik, and use 'set(words.words())' to speed up.
First:
pip3 install nltk
python3
import nltk
nltk.download('words')
Then:
from nltk.corpus import words
setofwords = set(words.words())
print("hello" in setofwords)
>>True
A bit unrelated answer to OP but for people like me with a somewhat similar problem.
Use Case: Ubuntu (C, Clion, Auto-completion):
I had the same error,
CMake Error: Cannot determine link language for target "hello".
set_target_properties(hello PROPERTIES LINKER_LANGUAGE C)
help fixes that problem but the headers aren't included to the project and the autocompletion wont work.
This is what i had
cmake_minimum_required(VERSION 3.5)
project(hello)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES ./)
add_executable(hello ${SOURCE_FILES})
set_target_properties(hello PROPERTIES LINKER_LANGUAGE C)
No errors but not what i needed, i realized including a single file as source will get me autocompletion as well as it will set the linker to C
.
cmake_minimum_required(VERSION 3.5)
project(hello)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES ./1_helloworld.c)
add_executable(hello ${SOURCE_FILES})
You'll probably want to try textContent
instead of innerHTML
.
Given innerHTML
will return DOM content as a String
and not exclusively the "text" in the div
. It's fine if you know that your div
contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent
instead of innerHTML
For example, considering the following markup:
<div id="test">
Some <span class="foo">sample</span> text.
</div>
You'll get the following result:
var node = document.getElementById('test'),
htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."
textContent = node.textContent;
// textContent = "Some sample text."
See MDN for more details:
I have Samsung Galaxy S3 and it was not showing in the "Remote devices" tab nor in chrome://inspect. The device did show in Windows's Device Manager as GT-I9300, though. What worked for me was:
cmd.exe
cd "C:\Program Files (x86)\ClockworkMod\Universal Adb Driver"
adb devices
I'm not sure if it affected the whole flow somehow, but at some point I've installed, and later uninstalled the drivers from Samsung: http://www.samsung.com/us/support/downloads/ > Mobile > Phones > Galaxy S > S III > Unlocked > http://www.samsung.com/us/support/owners/product/galaxy-s-iii-unlocked#downloads
I wanted to replicate Unix/Linux's cp -r
as closely as possible. I came up with the following:
xcopy /e /k /h /i srcdir destdir
Flag explanation:
/e
Copies directories and subdirectories, including empty ones.
/k
Copies attributes. Normal Xcopy will reset read-only attributes.
/h
Copies hidden and system files also.
/i
If destination does not exist and copying more than one file, assume destination is a directory.
I made the following into a batch file (cpr.bat
) so that I didn't have to remember the flags:
xcopy /e /k /h /i %*
Usage: cpr srcdir destdir
You might also want to use the following flags, but I didn't:
/q
Quiet. Do not display file names while copying.
/b
Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o
Copies directory and file ACLs. (requires UAC admin)
You might miss @author and inside of @param you need to explain what's that parameter for, how to use it, etc.
Crazy idea...
You could play around with some pseudo elements, and create up/down arrows of css content hex codes. The only challange will be to precise the positioning of the arrow, but it may work:
input[type="number"] {_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.number-wrapper {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.number-wrapper:hover:after {_x000D_
content: "\25B2";_x000D_
position: absolute;_x000D_
color: blue;_x000D_
left: 100%;_x000D_
margin-left: -17px;_x000D_
margin-top: 12%;_x000D_
font-size: 11px;_x000D_
}_x000D_
_x000D_
.number-wrapper:hover:before {_x000D_
content: "\25BC";_x000D_
position: absolute;_x000D_
color: blue;_x000D_
left: 100%;_x000D_
bottom: 0;_x000D_
margin-left: -17px;_x000D_
margin-bottom: -14%;_x000D_
font-size: 11px;_x000D_
}
_x000D_
<span class='number-wrapper'>_x000D_
<input type="number" />_x000D_
</span>
_x000D_
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
if ((ModifierKeys == Keys.Control) && ((e.KeyChar & (char)Keys.F) != 0))
{
// CTRL+F pressed !
}
If you want a method like public void doSomething([Object implements Serializable])
you can just type it like this public void doSomething(Serializable serializableObject)
. You can now pass it any object that implements Serializable but using the serializableObject
you only have access to the methods implemented in the object from the Serializable interface.
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
Write-Warning "This is only a test warning." -WarningAction Inquire
Use $ne
-- $not
should be followed by the standard operator:
An examples for $ne
, which stands for not equal:
use test
switched to db test
db.test.insert({author : 'me', post: ""})
db.test.insert({author : 'you', post: "how to query"})
db.test.find({'post': {$ne : ""}})
{ "_id" : ObjectId("4f68b1a7768972d396fe2268"), "author" : "you", "post" : "how to query" }
And now $not
, which takes in predicate ($ne
) and negates it ($not
):
db.test.find({'post': {$not: {$ne : ""}}})
{ "_id" : ObjectId("4f68b19c768972d396fe2267"), "author" : "me", "post" : "" }
In the MySQL interactive client you can type:
source yourfile.sql
Alternatively you can pipe the data into mysql from the command line:
mysql < yourfile.sql
If the file doesn't specify a database then you will also need to add that:
mysql db_name < yourfile.sql
See the documentation for more details:
Just Reinstall JDK 1.7 it will work.
See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:
...
vector::iterator iterator1;
iterator1= vec1.begin();
vec1.insert ( iterator1+i , vec2[i] );
// This means that at position "i" from the beginning it will insert the value from vec2 from position i
Your first approach was replacing the values from vec1[i] with the values from vec2[i]
I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.
_kbhit()
and _getwch()
from msvcrt.dll.tcsetattr()
to switch the console to non-canonical mode, System.in.available()
to check whether data is available and System.in.read()
to read bytes from the console. A CharsetDecoder
is used to convert bytes to characters.It supports non-blocking input and mixing raw mode and normal line mode input.
There are two reasons to pass an argument by reference: (1) for performance (in which case you want to pass by const reference) and (2) because you need the ability to change the value of the argument inside the function.
I highly doubt that passing an unsigned long on modern architectures is slowing you down too much. So I'm assuming that you're intending to change the value of State
inside the method. The compiler is complaining because the constant 0
cannot be changed, as it's an rvalue ("non-lvalue" in the error message) and unchangeable (const
in the error message).
Simply put, you want a method that can change the argument passed, but by default you want to pass an argument that can't change.
To put it another way, non-const
references have to refer to actual variables. The default value in the function signature (0
) is not a real variable. You're running into the same problem as:
struct Foo {
virtual ULONG Write(ULONG& State, bool sequence = true);
};
Foo f;
ULONG s = 5;
f.Write(s); // perfectly OK, because s is a real variable
f.Write(0); // compiler error, 0 is not a real variable
// if the value of 0 were changed in the function,
// I would have no way to refer to the new value
If you don't actually intend to change State
inside the method you can simply change it to a const ULONG&
. But you're not going to get a big performance benefit from that, so I would recommend changing it to a non-reference ULONG
. I notice that you are already returning a ULONG
, and I have a sneaky suspicion that its value is the value of State
after any needed modifications. In which case I would simply declare the method as so:
// returns value of State
virtual ULONG Write(ULONG State = 0, bool sequence = true);
Of course, I'm not quite sure what you're writing or to where. But that's another question for another time.
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
# -*- coding: utf-8 -*-
is a Python 2 thing. In Python 3+, the default encoding of source files is already UTF-8 and that line is useless.
See: Should I use encoding declaration in Python 3?
pyupgrade
is a tool you can run on your code to remove those comments and other no-longer-useful leftovers from Python 2, like having all your classes inherit from object
.
Implement the Serializable
interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable
object might reference an instance of your class.
Serializable
classes are useful when you want to persist instances of them or send them over a wire.
Instances of Serializable
classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's Effective Java.
In many circumstances they are different names for the same thing, but in some contexts they are quite different. So it depends. Terminology is not applied in a totally consistent way across the whole software industry.
For example in the classic sockets API, a non-blocking socket is one that simply returns immediately with a special "would block" error message, whereas a blocking socket would have blocked. You have to use a separate function such as select
or poll
to find out when is a good time to retry.
But asynchronous sockets (as supported by Windows sockets), or the asynchronous IO pattern used in .NET, are more convenient. You call a method to start an operation, and the framework calls you back when it's done. Even here, there are basic differences. Asynchronous Win32 sockets "marshal" their results onto a specific GUI thread by passing Window messages, whereas .NET asynchronous IO is free-threaded (you don't know what thread your callback will be called on).
So they don't always mean the same thing. To distil the socket example, we could say:
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );
This is not exactly an answer, rather sharing my findings, and hopefully getting some critical argument for/against it, as specifically I am not aware how efficient it is.
I recently had a need to do this for my project. I did this using Object.assign
, more precisely it is done something like this:Object.assign(new Person(...), anObjectLikePerson)
.
Here is link to my JSFiddle, and also the main part of the code:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.getFullName = function() {
return this.lastName + ' ' + this.firstName;
}
}
var persons = [{
lastName: "Freeman",
firstName: "Gordon"
}, {
lastName: "Smith",
firstName: "John"
}];
var stronglyTypedPersons = [];
for (var i = 0; i < persons.length; i++) {
stronglyTypedPersons.push(Object.assign(new Person("", ""), persons[i]));
}
In case you use fastlane, additional flags can be passed with
gradle(
...
flags: "{your flags}"
)
More information here
No you can't pass parameters to the run()
method. The signature tells you that (it has no parameters). Probably the easiest way to do this would be to use a purpose-built object that takes a parameter in the constructor and stores it in a final variable:
public class WorkingTask implements Runnable
{
private final Object toWorkWith;
public WorkingTask(Object workOnMe)
{
toWorkWith = workOnMe;
}
public void run()
{
//do work
}
}
//...
Thread t = new Thread(new WorkingTask(theData));
t.start();
Once you do that - you have to be careful of the data integrity of the object you pass into the 'WorkingTask'. The data will now exist in two different threads so you have to make sure it is Thread Safe.
with UnionTable as
(
SELECT a.id, a.time FROM dbo.a
UNION
SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id
The most important thing is to avoid creating a problem
, so I believe that you should use a direct relation to avoid having a cycle.
As @markmywords said, #include "fritzl.h".
Finally I have to say recheck your data structure
. Maybe something is going wrong over there (maybe a bidirectional linked list solves your problem).
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
Seeing the answers I have nothing else to add but one more thing:
in your test.html file you have written
link rel="stylesheet" type="css/text" href="test.css"/
see where you have written
type="css/text"
there you need to change into
type="text/css"
so it will look like that
link rel="stylesheet" type="text/css" href="test.css"/
and in this case the CSS file will be linked to HTML file
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
Personally, I do the following:
session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();
That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy
).
LocalDate date = LocalDate.now();
DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
try {
Date utilDate= formatter.parse(date.toString());
} catch (ParseException e) {
// handle exception
}
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
The other issue here lies under Code Signing Identity under the Build Settings. Be sure that it contains the Code Signing Identity: "iOS Developer" as opposed to "Don't Code Sign." This will allow you to deploy it to your iOS device. Especially, if you have downloaded a GitHub example or something to this effect.
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
I have seen that happening several times, with broken links (symlinks that point to files that do not exist), grep tries to search on the target file, which does not exist (hence the correct and accurate error message).
I normally don't bother while doing sysadmin tasks over the console, but from within scripts I do look for text files with "find", and then grep each one:
find /etc -type f -exec grep -nHi -e "widehat" {} \;
Instead of:
grep -nRHi -e "widehat" /etc
Using "groupby" and list comprehension:
Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.
DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]
accessing the separated DF like this:
ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF
accessing the column value of the separated DF like this:
ansI_chr=ans[i].chr
var $button = $('.increment-btn');
var $counter = $('.counter');
$button.click(function(){
$counter.val( parseInt($counter.val()) + 1 ); // `parseInt` converts the `value` from a string to a number
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="1" class="counter"/>
<button type="button" class="increment-btn">Increment</button>
_x000D_
var $button = document.querySelector('.increment-btn');
var $counter = document.querySelector('.counter');
$button.addEventListener('click', function(){
$counter.value = parseInt($counter.value) + 1; // `parseInt` converts the `value` from a string to a number
}, false);
_x000D_
<input type="text" class="counter" value="1"/>
<button type="button" class="increment-btn">Increment</button>
_x000D_
interesting, datepicker default date is current date as I found,
but you can set date by
$("#yourinput").datepicker( "setDate" , "7/11/2011" );
don't forget to check you system date :)
In my case the issue didn't resolve by following any of the above methods. I had all the paths in my package config correct and the dll's were in place as referred, I was still getting run time error for System.Web.WebPages.Razor. I changed the localhost port number and this worked
I am not sure of why I had the issue and why changing the port number resolved it. Just posting this as I feel this might be useful for someone out there.
Use Like this:
Uri uri = Uri.parse(URL); //Declare your url here.
VideoView mVideoView = (VideoView)findViewById(R.id.videoview)
mVideoView.setMediaController(new MediaController(this));
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();
Another Method:
String LINK = "type_here_the_link";
VideoView mVideoView = (VideoView) findViewById(R.id.videoview);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri video = Uri.parse(LINK);
mVideoView.setMediaController(mc);
mVideoView.setVideoURI(video);
mVideoView.start();
If you are getting this error Couldn't open file on client side, trying server side Error in Android. and also Refer this. Hope this will give you some solution.
(This is already answered in comments, but since it lacks an actual answer, I'm writing this.)
This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are using different versions of the CRT (the C RunTime library.)
To correct this error, you need to go into your Project Properties
(and/or those of the libraries you are using,) then into C/C++
, then Code Generation
, and check the value of Runtime Library
; this should be exactly the same for all the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)
There are currently four options for this setting:
Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug DLL" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.
Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.
For (some) more information, you can see these (linked from a comment above):
UPDATE: (This is in response to a comment that asks for the reason that this much care must be taken.)
If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless great care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)
The most important part of the problem is this: having the same idea about the size of objects on either side of a function call.
Consider for example that the above two pieces of code are called A
and B
. A is compiled against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a FILE
object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)
Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)
The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.
All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)
This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.
What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!
cd venv
source bin/activate
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
python
\>\> import sys
\>\> sys.path
Replace
xmlns:android="http://schemas.android.com/apk/res/android"
with
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
then Rebuild Project
print
For your own classes, just def a __str__
method
Historically a \n
was used to move the carriage down, while the \r
was used to move the carriage back to the left side of the page.
You can export the query results to a text file (or insert statements, or even pdf) by right-clicking on Query Result row (any row) and choose Export
using Sql Developer 3.0
See SQL Developer downloads for latest versions
<div id='element_123_wrapper_text'>My sample DIV</div>
The Operator ^ - Match elements that starts with given value
div[id^="element_123"] {
}
The Operator $ - Match elements that ends with given value
div[id$="wrapper_text"] {
}
The Operator * - Match elements that have an attribute containing a given value
div[id*="wrapper_text"] {
}
In order to append to a file you'll need to use a slightly different approach. You can still redirect an individual process' standard error and standard output to a file, but in order to append it to a file you'll need to do one of these things:
Start-Process
&
The first way would look like this:
$myLog = "C:\File.log"
$stdErrLog = "C:\stderr.log"
$stdOutLog = "C:\stdout.log"
Start-Process -File myjob.bat -RedirectStandardOutput $stdOutLog -RedirectStandardError $stdErrLog -wait
Get-Content $stdErrLog, $stdOutLog | Out-File $myLog -Append
The second way would look like this:
& myjob.bat 2>&1 >> C:\MyLog.txt
Or this:
& myjob.bat 2>&1 | Out-File C:\MyLog.txt -Append
The third way:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "myjob.bat"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$output = $p.StandardOutput.ReadToEnd()
$output += $p.StandardError.ReadToEnd()
$output | Out-File $myLog -Append
Select
cast(replace(convert(decimal(15,2),acs_daily_debit), '.', ',') as varchar(20))
from acs_balance_details
You can break up long lines with the caret ^
as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. (More on that below.)
Example:
copy file1.txt file2.txt
would be written as:
copy file1.txt^
file2.txt
Adding in the following code works.
The problem is iPhones dont raise click events. They raise "touch" events. Thanks very much apple. Why couldn't they just keep it standard like everyone else? Anyway thanks Nico for the tip.
Credit to: http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript
$(document).ready(function () {
init();
$(document).click(function (e) {
fire(e);
});
});
function fire(e) { alert('hi'); }
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch(event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type = "mousemove"; break;
case "touchend": type = "mouseup"; break;
default: return;
}
//initMouseEvent(type, canBubble, cancelable, view, clickCount,
// screenX, screenY, clientX, clientY, ctrlKey,
// altKey, shiftKey, metaKey, button, relatedTarget);
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init()
{
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.
Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.
Sub Loop3()
Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String
Application.ScreenUpdating = False
'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row 'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column 'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead)) 'assigns range for automation
ReDim frmlas(1) 'array assigned to formula strings
'VOL column formula
frmlas(0) = "VOL FORMULA"
'CAPACITY column formula
frmlas(1) = "CAP FORMULA"
For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then 'checks for volume formula column
For j = 1 To rng.Rows.count
rng(j, i).Formula= frmlas(0) 'inserts volume formula
Next j
ElseIf rng(0, i).Value = "Cap" Then 'checks for capacity formula column
For j = 1 To rng.Rows.count
rng(j, i).Formula = frmlas(1) 'inserts capacity formula
Next j
End If
Next i
Application.ScreenUpdating = True
End Sub
In my case, it was working fine in Chrome and IE was calling the .click()
twice. if that was your issue, then I fixed it by return false, after calling the .click()
event
$("#txtChat").keypress(function(event) {
if (event.which == 13) {
$('#btnChat').click();
$('#txtChat').val('');
return false;
}
});
If you use input property databinding with a JavaScript reference type (e.g., Object, Array, Date, etc.), then the parent and child will both have a reference to the same/one object. Any changes you make to the shared object will be visible to both parent and child.
In the parent's template:
<child [aList]="sharedList"></child>
In the child:
@Input() aList;
...
updateList() {
this.aList.push('child');
}
If you want to add items to the list upon construction of the child, use the ngOnInit()
hook (not the constructor(), since the data-bound properties aren't initialized at that point):
ngOnInit() {
this.aList.push('child1')
}
This Plunker shows a working example, with buttons in the parent and child component that both modify the shared list.
Note, in the child you must not reassign the reference. E.g., don't do this in the child: this.aList = someNewArray;
If you do that, then the parent and child components will each have references to two different arrays.
If you want to share a primitive type (i.e., string, number, boolean), you could put it into an array or an object (i.e., put it inside a reference type), or you could emit()
an event from the child whenever the primitive value changes (i.e., have the parent listen for a custom event, and the child would have an EventEmitter
output property. See @kit's answer for more info.)
Update 2015/12/22: the heavy-loader
example in the Structural Directives guides uses the technique I presented above. The main/parent component has a logs
array property that is bound to the child components. The child components push()
onto that array, and the parent component displays the array.
1. Create a class
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s[] = {"app","amm","abb","akk","all"};
doForAllTabs(s);
}
public static void doForAllTabs(String[] tablist){
for(int i = 0; i<tablist.length;i++){
System.out.println(tablist[i]);
}
}
}
2. Right click on left side of System.out.println(tablist[i]); in Eclipse --> select Toggle Breakpoint
3. Right click on toggle point --> select Breakpoint properties
4. Check the Conditional Check Box --> write tablist[i].equalsIgnoreCase("amm") in text field --> Click on OK
5. Right click on class --> Debug As --> Java Application
See ?assign
.
> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
[1] 5
They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.
If you are dealing with an Azure WebJob - I had to remove the following after upgrading to the latest 4.6.1.
<compilation debug="true" targetFramework="4.6.1">
<assemblies>
<add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</assemblies>
</compilation>
Hope this helps.
You can get Hive version
hive --version
if you want to know hive version and its related package versions.
rpm -qa|grep hive
Output will be like below.
libarchive2-2.5.5-5.19
hive-0.13.0.2.1.2.2-516
perl-Archive-Zip-1.24-2.7
hive-jdbc-0.13.0.2.1.2.2-516
webhcat-tar-hive-0.13.0.2.1.2.2_516-2
hive-webhcat-0.13.0.2.1.2.2-516
hive-hcatalog-0.13.0.2.1.2.2-516
Latter gives better understanding of hive and its dependents. Nevertheless rpm needs to be present.
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
1) The result of repr('foo')
is the string 'foo'
. In your Python shell, the result of the expression is expressed as a representation too, so you're essentially seeing repr(repr('foo'))
.
2) eval
calculates the result of an expression. The result is always a value (such as a number, a string, or an object). Multiple variables can refer to the same value, as in:
x = 'foo'
y = x
x and y now refer to the same value.
3) I have no idea what you meant here. Can you post an example, and what you'd like to see?
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
You can call bash directly within your Makefile instead of using the default shell:
bash -c "ls -al"
instead of:
ls -al
An array can be initialized by using the new Object {}
syntax.
For example, an array of String
can be declared by either:
String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};
Primitives can also be similarly initialized either by:
int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};
Or an array of some Object
:
Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};
All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.
These posts helped me get past a couple of issues I had creating a CLR Stored Procedure with Restful API call against Infor M3 API.
The XML Result from these API's look like this for my code below:
miResult xmlns="http://lawson.com/m3/miaccess">
<Program>MMS200MI</Program>
<Transaction>Get</Transaction>
<Metadata>...</Metadata>
<MIRecord>
<RowIndex>0</RowIndex>
<NameValue>
<Name>STAT</Name>
<Value>20</Value>
</NameValue>
<NameValue>
<Name>ITNO</Name>
<Value>ITEM123</Value>
</NameValue>
<NameValue>
<Name>ITDS</Name>
<Value>ITEM DESCRIPTION 123 </Value>
</NameValue>
...
The CLR C# Code to accomplish listing out the Resultset from the API works as shown below:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void CallM3API_Test1()
{
SqlPipe pipe_msg = SqlContext.Pipe;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://M3Server.domain.com:12345/m3api-rest/execute/MMS200MI/Get?ITNO=ITEM123");
request.Method = "Get";
request.ContentLength = 0;
request.Credentials = new NetworkCredential("[email protected]", "MyPassword");
request.ContentType = "application/xml";
request.Accept = "application/xml";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream receiveStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
string strContent = readStream.ReadToEnd();
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(strContent);
try
{
SqlPipe pipe = SqlContext.Pipe;
//Define Output Columns and Max Length of each Column in the Resultset
SqlMetaData[] cols = new SqlMetaData[2];
cols[0] = new SqlMetaData("Name", SqlDbType.NVarChar, 50);
cols[1] = new SqlMetaData("Value", SqlDbType.NVarChar, 120);
SqlDataRecord record = new SqlDataRecord(cols);
pipe.SendResultsStart(record);
XmlNodeList nodeList = xdoc.GetElementsByTagName("NameValue");
//List ALL Output Names + Values
foreach (XmlNode nodeRes in nodeList)
{
record.SetSqlString(0, nodeRes["Name"].InnerText);
record.SetSqlString(1, nodeRes["Value"].InnerText);
pipe.SendResultsRow(record);
}
pipe.SendResultsEnd();
}
catch (Exception ex)
{
SqlContext.Pipe.Send("Error (readStream): " + ex.Message);
}
}
}
}
}
catch (Exception ex)
{
SqlContext.Pipe.Send("Error (CallM3API_Test1): " + ex.Message);
}
}
}
Hopefully this provides helpful.
You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :
df[df['a']==1]['b'].sum()
or you can also try :
sum(df[df['a']==1]['b'])
Another way could be to use the numpy library of python :
import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())
public List<DealsCategory> DealCategory { get; set; }
int categoryid = Convert.ToInt16(dealsModel.DealCategory.Select(x => x.Id));
String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);
I do this, and it worked.
When you call for i in a:
, you are getting the actual elements, not the indexes. When we reach the last element, that is 3
, b.append(a[i+1]-a[i])
looks for a[4]
, doesn't find one and then fails. Instead, try iterating over the indexes while stopping just short of the last one, like
for i in range(0, len(a)-1): Do something
Your current code won't work yet for the do something part though ;)
I created a github project Json2Java that does this. https://github.com/inder123/json2java
Json2Java provides customizations such as renaming fields, and creating inheritance hierarchies.
I have used the tool to create some relatively complex APIs:
Gracenote's TMS API: https://github.com/inder123/gracenote-java-api
Google Maps Geocoding API: https://github.com/inder123/geocoding
If you need subsecond precision, you need to use system-specific extensions, and will have to check with the documentation for the operating system. POSIX supports up to microseconds with gettimeofday, but nothing more precise since computers didn't have frequencies above 1GHz.
If you are using Boost, you can check boost::posix_time.
This kind of query should work - after rewriting with explicit JOIN
syntax:
SELECT something
FROM master parent
JOIN master child ON child.parent_id = parent.id
LEFT JOIN second parentdata ON parentdata.id = parent.secondary_id
LEFT JOIN second childdata ON childdata.id = child.secondary_id
WHERE parent.parent_id = 'rootID'
The tripping wire here is that an explicit JOIN
binds before "old style" CROSS JOIN
with comma (,
). I quote the manual here:
In any case
JOIN
binds more tightly than the commas separatingFROM
-list items.
After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.
Just to make my point, this would work, too:
SELECT something
FROM master parent
LEFT JOIN second parentdata ON parentdata.id = parent.secondary_id
, master child
LEFT JOIN second childdata ON childdata.id = child.secondary_id
WHERE child.parent_id = parent.id
AND parent.parent_id = 'rootID'
But explicit JOIN
syntax is generally preferable, as your case illustrates once again.
And be aware that multiple (LEFT
) JOIN
can multiply rows:
I have found the solution else where:
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)
Though I am very late in this discussion, I thought this may be useful for some one in future.
I had faced similar situation. The easiest workaround for those who doesn't mind unsetting and resetting the variable is to do so. I am pretty sure the reason why this is not working is clear from the other answers and from the php.net manual. The simplest workaround worked for me is
Assumption:
$object
is the object with overloaded __get
and __set
from the base class, which I am not in the freedom to modify.shippingData
is the array I want to modify a field of for e.g. :- phone_number
// First store the array in a local variable.
$tempShippingData = $object->shippingData;
unset($object->shippingData);
$tempShippingData['phone_number'] = '888-666-0000' // what ever the value you want to set
$object->shippingData = $tempShippingData; // this will again call the __set and set the array variable
unset($tempShippingData);
Note: this solution is one of the quick workaround possible to solve the problem and get the variable copied. If the array is too humungous, it may be good to force rewrite the __get
method to return a reference rather expensive copying of big arrays.
Shows all your disks; total, used and free capacity. You can alter the output by various command-line options.
You can get it from http://www.paulsadowski.com/WSH/cmdprogs.htm, http://unxutils.sourceforge.net/ or somewhere else. It's a standard unix-util like du.
df -h
will show all your drive's used and available disk space. For example:
M:\>df -h
Filesystem Size Used Avail Use% Mounted on
C:/cygwin/bin 932G 78G 855G 9% /usr/bin
C:/cygwin/lib 932G 78G 855G 9% /usr/lib
C:/cygwin 932G 78G 855G 9% /
C: 932G 78G 855G 9% /cygdrive/c
E: 1.9T 1.3T 621G 67% /cygdrive/e
F: 1.9T 201G 1.7T 11% /cygdrive/f
H: 1.5T 524G 938G 36% /cygdrive/h
M: 1.5T 524G 938G 36% /cygdrive/m
P: 98G 67G 31G 69% /cygdrive/p
R: 98G 14G 84G 15% /cygdrive/r
Cygwin is available for free from: https://www.cygwin.com/ It adds many powerful tools to the command prompt. To get just the available space on drive M (as mapped in windows to a shared drive), one could enter in:
M:\>df -h | grep M: | awk '{print $4}'
INSERT .. WHERE NOT EXISTS is good approach. And race conditions can be avoided by transaction "envelope":
BEGIN;
LOCK TABLE hundred IN SHARE ROW EXCLUSIVE MODE;
INSERT ... ;
COMMIT;
As ghills had already mentioned
inp = int(input("Enter a number:"))
n = 0
for i in str(inp):
n = n + int(i);
print n
When you are looping through something, keyword is "IN", just always think of it as a list of something. You cannot loop through a plain integer. Therefore, it is not iterable.
If you simply want some output, you want to use $(info)
by itself. You can do that anywhere in a Makefile, and it will show when that line is evaluated:
$(info VAR="$(VAR)")
Will output VAR="<value of VAR>"
whenever make processes that line. This behavior is very position dependent, so you must make sure that the $(info)
expansion happens AFTER everything that could modify $(VAR)
has already happened!
A more generic option is to create a special rule for printing the value of a variable. Generally speaking, rules are executed after variables are assigned, so this will show you the value that is actually being used. (Though, it is possible for a rule to change a variable.) Good formatting will help clarify what a variable is set to, and the $(flavor)
function will tell you what kind of a variable something is. So in this rule:
print-% : ; $(info $* is a $(flavor $*) variable set to [$($*)]) @true
$*
expands to the stem that the %
pattern matched in the rule.$($*)
expands to the value of the variable whose name is given by by $*
.[
and ]
clearly delineate the variable expansion.
You could also use "
and "
or similar.$(flavor $*)
tells you what kind of variable it is. NOTE: $(flavor)
takes a variable name, and not its expansion.
So if you say make print-LDFLAGS
, you get $(flavor LDFLAGS)
,
which is what you want.$(info text)
provides output.
Make prints text
on its stdout as a side-effect of the expansion.
The expansion of $(info)
though is empty.
You can think of it like @echo
,
but importantly it doesn't use the shell,
so you don't have to worry about shell quoting rules.@true
is there just to provide a command for the rule.
Without that,
make will also output print-blah is up to date
. I feel @true
makes it more clear that it's meant to be a no-op.Running it, you get
$ make print-LDFLAGS
LDFLAGS is a recursive variable set to [-L/Users/...]
This works for me - i am using jackson 2.0.4
ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);
Associative array in PHP actually considered as a dictionary.
An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.
We could not uninstall a program, stuck with the "Windows error 2 cannot load Java VM". Added the Java path to the PATH variable, uninstalled and re-installed Java 8, the problem would not go away.
Then I found this solution online and it worked for us on the first shot: - Uninstall Java 8 - Install Java 6
Whatever the reason, with Java 6, the error went away, we uninstalled the program, and re-installed Java 8.
I run into this error when I tried to install Python 3.7.3 in Ubuntu 18.04 with next command: $ pyenv install 3.7.3
.
Installation succeeded after running $ sudo apt-get update && sudo apt-get install libffi-dev
(as suggested here).
The issue was solved there.
Consider this to get a fully unique jar file:
I'm a total beginner in Python, and my programming at the moment is crude and dirty to say the least, but my solution was to use a combination of the basic commands I learnt in early tutorials:
some_list = [1,2,3,4,5,6,7,8,10]
rem = [0,5,7]
for i in rem:
some_list[i] = '!' # mark for deletion
for i in range(0, some_list.count('!')):
some_list.remove('!') # remove
print some_list
Obviously, because of having to choose a "mark-for-deletion" character, this has its limitations.
As for the performance as the size of the list scales, I'm sure that my solution is sub-optimal. However, it's straightforward, which I hope appeals to other beginners, and will work in simple cases where some_list
is of a well-known format, e.g., always numeric...
There are many ways it can be achieved. The tool you use mostly depends on your own preference or experience.
Using tr command:
tr '\n' ',' < somefile
Using awk:
awk -F'\n' '{if(NR == 1) {printf $0} else {printf ","$0}}' somefile
To print the address of a variable, you need to use the %p
format. %d
is for signed integers. For example:
#include<stdio.h>
void main(void)
{
int a;
printf("Address is %p:",&a);
}
I encountered the same issues: In a relative layout parentView, I have 2 children childView1 and childView2. At first, I put childView1 above childView2 and I want childView1 to be on top of childView2. Changing the order of children views did not solve the problem for me. What worked for me is to set android:clipChildren="false" on parentView and in the code I set:
childView1.bringToFront();
parentView.invalidate();
I have 2 tables like this:
> SELECT * FROM table_a;
+------+------+
| id | name |
+------+------+
| 1 | row1 |
| 2 | row2 |
+------+------+
> SELECT * FROM table_b;
+------+------+------+
| id | name | aid |
+------+------+------+
| 3 | row3 | 1 |
| 4 | row4 | 1 |
| 5 | row5 | NULL |
+------+------+------+
INNER JOIN cares about both tables
INNER JOIN cares about both tables, so you only get a row if both tables have one. If there is more than one matching pair, you get multiple rows.
> SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id | name | id | name | aid |
+------+------+------+------+------+
| 1 | row1 | 3 | row3 | 1 |
| 1 | row1 | 4 | row4 | 1 |
+------+------+------+------+------+
It makes no difference to INNER JOIN if you reverse the order, because it cares about both tables:
> SELECT * FROM table_b b INNER JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id | name | aid | id | name |
+------+------+------+------+------+
| 3 | row3 | 1 | 1 | row1 |
| 4 | row4 | 1 | 1 | row1 |
+------+------+------+------+------+
You get the same rows, but the columns are in a different order because we mentioned the tables in a different order.
LEFT JOIN only cares about the first table
LEFT JOIN cares about the first table you give it, and doesn't care much about the second, so you always get the rows from the first table, even if there is no corresponding row in the second:
> SELECT * FROM table_a a LEFT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id | name | id | name | aid |
+------+------+------+------+------+
| 1 | row1 | 3 | row3 | 1 |
| 1 | row1 | 4 | row4 | 1 |
| 2 | row2 | NULL | NULL | NULL |
+------+------+------+------+------+
Above you can see all rows of table_a even though some of them do not match with anything in table b, but not all rows of table_b - only ones that match something in table_a.
If we reverse the order of the tables, LEFT JOIN behaves differently:
> SELECT * FROM table_b b LEFT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id | name | aid | id | name |
+------+------+------+------+------+
| 3 | row3 | 1 | 1 | row1 |
| 4 | row4 | 1 | 1 | row1 |
| 5 | row5 | NULL | NULL | NULL |
+------+------+------+------+------+
Now we get all rows of table_b, but only matching rows of table_a.
RIGHT JOIN only cares about the second table
a RIGHT JOIN b
gets you exactly the same rows as b LEFT JOIN a
. The only difference is the default order of the columns.
> SELECT * FROM table_a a RIGHT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id | name | id | name | aid |
+------+------+------+------+------+
| 1 | row1 | 3 | row3 | 1 |
| 1 | row1 | 4 | row4 | 1 |
| NULL | NULL | 5 | row5 | NULL |
+------+------+------+------+------+
This is the same rows as table_b LEFT JOIN table_a
, which we saw in the LEFT JOIN section.
Similarly:
> SELECT * FROM table_b b RIGHT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id | name | aid | id | name |
+------+------+------+------+------+
| 3 | row3 | 1 | 1 | row1 |
| 4 | row4 | 1 | 1 | row1 |
| NULL | NULL | NULL | 2 | row2 |
+------+------+------+------+------+
Is the same rows as table_a LEFT JOIN table_b
.
No join at all gives you copies of everything
If you write your tables with no JOIN clause at all, just separated by commas, you get every row of the first table written next to every row of the second table, in every possible combination:
> SELECT * FROM table_b b, table_a;
+------+------+------+------+------+
| id | name | aid | id | name |
+------+------+------+------+------+
| 3 | row3 | 1 | 1 | row1 |
| 3 | row3 | 1 | 2 | row2 |
| 4 | row4 | 1 | 1 | row1 |
| 4 | row4 | 1 | 2 | row2 |
| 5 | row5 | NULL | 1 | row1 |
| 5 | row5 | NULL | 2 | row2 |
+------+------+------+------+------+
(This is from my blog post Examples of SQL join types)
There is a simple way as well, we can use the reshape function in a different way:
A_reshape = A.reshape(No_of_rows, No_of_columns)
Layout
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="300dp"
android:gravity="center"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:background="@drawable/rounded_edge">
</LinearLayout>
Drawable folder rounded_edge.xml
<shape
xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="@android:color/darker_gray">
</solid>
<stroke
android:width="0dp"
android:color="#424242">
</stroke>
<corners
android:topLeftRadius="100dip"
android:topRightRadius="100dip"
android:bottomLeftRadius="100dip"
android:bottomRightRadius="100dip">
</corners>
</shape>
The Starter Trade-offs sheet of my comparison spreadsheet has comprehensive one-on-one comparisons between each generator. So no more need to distortedly cherry-pick great things to say about your favorite.
Here is the one between generator-angular-fullstack and MEAN.js. The percentages are values for each benefit based on my personal weightings, where a perfect generator would be 100%
generator- angular- fullstack offers 8% that MEANJS.org doesn't
MeanJS.org. offers 9% that generator-angular-fullstack doesn't
Here is the one between MEAN.io and MEAN.js in a more readable format
<table border="1" cellpadding="10"><tbody><tr><td valign="top" width="33%"><br><br><h1>MeanJS.org. provides these benefits that MEAN.io. doesn't</h1><br><br><b>Help</b>:<br> * Dedicated/searchable user group for questions, using github issues<br> * There's a book about it<br><b>File Organization</b>:<br> * Basic sourcecode organization, module(->submodule)->side<br> * Module directories hold directives<br><b>Code Modularization</b>:<br> * Approach to AngularJS modules, Only one module definition per file<br> * Approach to AngularJS modules, Don’t alter a module other than where it is defined<br><b>Model</b>:<br> * Object-relational mapping<br> * Server-side validation, server-side example<br> * Client side validation, using Angular 1.3<br><b>View</b>:<br> * Approach to AngularJS views, Directives start with "data-"<br> * Approach to data readiness, Use ng-init<br><b>Control</b>:<br> * Approach to frontend routing or state changing, URLs start with '#!'<br> * Approach to frontend routing or state changing, Use query parameters to store route state<br><b>Support for things</b>:<br> * Languages, LESS<br> * Languages, SASS<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Don't use "new"<br><b>Testing</b>:<br> * Testing, using Mocha<br> * End-to-end tests<br> * End-to-end tests, using Protractor<br> * Continuous integration (CI), using Travis<br><b>Development and debugging</b>:<br> * Command line interface (CLI), using Yeoman<br><b>Build</b>:<br> * Build configurations file(s)<br> * Deployment automation, using Azure<br> * Deployment automation, using Digital Ocean, screencast of it<br> * Deployment automation, using Heroku, screencast of it<br><b>Code Generation</b>:<br> * Input application profile<br> * Quick install?<br> * Options for making subcomponents<br> * config generator<br> * controller (client side) generator<br> * directive generator<br> * filter generator<br> * route (client side) generator<br> * service (client side) generator<br> * test - client side<br> * view or view partial generator<br> * controller (server side) generator<br> * model (server side) generator<br> * route (server side) generator<br> * test (server side) generator<br><b>Implemented Functionality</b>:<br> * Account Management, Forgotten Password with Resetting<br> * Chat<br> * CSV processing<br> * E-mail sending system<br> * E-mail sending system, using Nodemailer<br> * E-mail sending system, using its own e-mail implementation<br> * Menus system, state-based<br> * Paypal integration<br> * Responsive design<br> * Social connections management page<br><b>Performance</b>:<br> * Creates a favicon<br><b>Security</b>:<br> * Safe from IP Spoofing<br> * Authorization, Access Contol List (ACL)<br> * Authentication, Cookie<br> * Websocket and RESTful http share security policies<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. provides these benefits that MeanJS.org. doesn't</h1><br><br><b>Quality</b>:<br> * Sponsoring company<br><b>Help</b>:<br> * Docs with flatdoc<br><b>Code Modularization</b>:<br> * Share code between projects<br> * Module manager<br><b>View</b>:<br> * Approach to data readiness, Use state.resolve()<br><b>Control</b>:<br> * Approach to frontend code loading, Use AMD with Require.js<br> * Approach to frontend code loading, using wiredep<br> * Approach to error handling, Server-side logging<br><b>Client/Server Communication</b>:<br> * Centralized event handling<br> * Approach to XHR calls, using $http and $q<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Wrap code in an IIFE (SEAF, SIAF)<br><b>Development and debugging</b>:<br> * API introspection report and testing interface, using Swagger<br> * Command line interface (CLI), using Independent command line interface<br><b>Build</b>:<br> * Development build, add IIFEs (SEAF, SIAF) to executable copies of code<br> * Deployment automation<br> * Deployment automation, using Heroku<br><b>Code Generation</b>:<br> * Scaffolding undo (mean package -d <name>)<br> * FEATURE (a.k.a. module, entity) generator, Menu items added for new features<br><b>Implemented Functionality</b>:<br> * Admin page for users and roles<br> * Content Management System (Use special data-bound directives in your templates.<br>Switch to edit mode and you can edit the values right where you see them)<br> * File Upload<br> * i18n, localization<br> * Menus system, submenus<br> * Search<br> * Search, actually works with backend API<br> * Search, using Elastic Search<br> * Styles, using Bootstrap, using UI Bootstrap AngularJS directives<br> * Text (WYSIWYG) Editor<br> * Text (WYSIWYG) Editor, using medium-editor<br><b>Performance</b>:<br> * Instrumentation, server-side<br><b>Security</b>:<br> * Serverside authenticated route restriction<br> * Authentication, using Oauth, Link multiple Oauth strategies to one account<br> * Authentication, JSON Web Token (JWT)<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. and MeanJS.org. both provide these benefits</h1><br><br><b>Quality</b>:<br> * Version Control, using git<br><b>Platforms</b>:<br> * Client-side JS Framework, using AngularJS<br> * Frontend Server/ Framework, using Node.JS<br> * Frontend Server/ Framework, using Node.JS, using Express<br> * API Server/ Framework, using NodeJS<br> * API Server/ Framework, using NodeJS, using Express<br><b>Help</b>:<br> * Dedicated/searchable user group for questions<br> * Dedicated/searchable user group for questions, using Google Groups<br> * Dedicated/searchable user group for questions, using Facebook<br> * Dedicated/searchable user group for questions, response time mostly under a day<br> * Example application<br> * Tutorial screencast in English<br> * Tutorial screencast in English, using Youtube<br> * Dedicated chatroom<br><b>File Organization</b>:<br> * Basic sourcecode organization, module(->submodule)->side, with type subfolders<br> * Module directories hold controllers<br> * Module directories hold services<br> * Module directories hold templates<br> * Module directories hold unit tests<br> * Separate route configuration files for each module<br><b>Code Modularization</b>:<br> * Modularized Functionality<br> * Approach to AngularJS modules, No global 'app' module variable<br> * Approach to AngularJS modules, No global 'app' module variable without an IIFE<br><b>Model</b>:<br> * Setup of persistent storage<br> * Setup of persistent storage, using NoSQL db<br> * Setup of persistent storage, using NoSQL db, using MongoDB<br><b>View</b>:<br> * No XHR calls in controllers<br> * Templates, using Angular directives<br> * Approach to data readiness, prevents Flash of Unstyled/compiled Content (FOUC)<br><b>Control</b>:<br> * Approach to frontend routing or state changing, example of it<br> * Approach to frontend routing or state changing, State-based routing<br> * Approach to frontend routing or state changing, State-based routing, using ui-router<br> * Approach to frontend routing or state changing, HTML5 Mode<br> * Approach to frontend code loading, using angular.bootstrap()<br><b>Client/Server Communication</b>:<br> * Serve status codes only as responses<br> * Accept nested, JSON parameters<br> * Add timer header to requests<br> * Support for signed and encrypted cookies<br> * Serve URLs based on the route definitions<br> * Can serve headers only<br> * Approach to XHR calls, using JSON<br> * Approach to XHR calls, using $resource (angular-resource)<br><b>Support for things</b>:<br> * Languages, JavaScript (server side)<br> * Languages, Swig<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Use 'use strict'<br><b>Tool Configuration/customization</b>:<br> * Separate runtime configuration profiles<br><b>Testing</b>:<br> * Testing, using Jasmine<br> * Testing, using Karma<br> * Client-side unit tests<br> * Continuous integration (CI)<br> * Automated device testing, using Live Reload<br> * Server-side integration & unit tests<br> * Server-side integration & unit tests, using Mocha<br><b>Development and debugging</b>:<br> * Command line interface (CLI)<br><b>Build</b>:<br> * Build-time Dependency Management, using npm<br> * Build-time Dependency Management, using bower<br> * Build tool / Task runner, using Grunt<br> * Build tool / Task runner, using gulp<br> * Development build, script<br> * Development build, reload build script file upon change<br> * Development build, copy assets to build or dist or target folder<br> * Development build, html page processing<br> * Development build, html page processing, inject references by searching directories<br> * Development build, html page processing, inject references by searching directories, injects js references<br> * Development build, html page processing, inject references by searching directories, injects css references<br> * Development build, LESS/SASS/etc files are linted, compiled<br> * Development build, JavaScript style checking<br> * Development build, JavaScript style checking, using jshint or jslint<br> * Development build, run unit tests<br> * Production build, script<br> * Production build, concatenation (aggregation, globbing, bundling) (If you add debug:true to your config/env/development.js the will not be <br>uglified)<br> * Production build, minification<br> * Production build, safe pre-minification, using ng-annotate<br> * Production build, uglification<br> * Production build, make static pages for SEO<br><b>Code Generation</b>:<br> * FEATURE (a.k.a. module, entity) generator (README.md<br>feature css<br>routes<br>controller<br>view<br>additional menu item)<br><b>Implemented Functionality</b>:<br> * 404 Page<br> * 500 Page<br> * Account Management<br> * Account Management, register/login/logout<br> * Account Management, is password manager friendly<br> * Front-end CRUD<br> * Full-stack CRUD<br> * Full-stack CRUD, with Read<br> * Full-stack CRUD, with Create, Update and Delete<br> * Google Analytics<br> * Menus system<br> * Realtime data sync<br> * Realtime data sync, using socket.io<br> * Styles, using Bootstrap<br><b>Performance</b>:<br> * Javascript performance thing<br> * Javascript performance thing, using lodash<br> * One event-loop thread handles all requests<br> * Configurable response caching (Express plugin<br><b>https</b>://www.npmjs.org/package/apicache)<br> * Clustered HTTP sessions<br><b>Security</b>:<br> * JavaScript obfuscation<br> * https<br> * Authentication, using Oauth<br> * Authentication, Basic (With Passport or others)<br> * Authentication, Digest (With Passport or others)<br> * Authentication, Token (With Passport or others)<br></td></tr></tbody></table>
_x000D_
The following Swift 5 Playground code shows a possible way to solve your problem using JSONSerialization
and URLSession
:
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let url = URL(string: "http://localhost:8080/new")!
let jsonDict = ["firstName": "Jane", "lastName": "Doe"]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDict, options: [])
var request = URLRequest(url: url)
request.httpMethod = "post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("error:", error)
return
}
do {
guard let data = data else { return }
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
print("json:", json)
} catch {
print("error:", error)
}
}
task.resume()
fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
fs.writeSync(fd, 'contents to append')
fs.closeSync(fd)
array_splice($array, 0, 1);
Run:
pip list
You should get a list of packages (including panda) and their versions, e.g.:
beautifulsoup4 (4.5.1)
cycler (0.10.0)
jdcal (1.3)
matplotlib (1.5.3)
numpy (1.11.1)
openpyxl (2.2.0b1)
pandas (0.18.1)
pip (8.1.2)
pyparsing (2.1.9)
python-dateutil (2.2)
python-nmap (0.6.1)
pytz (2016.6.1)
requests (2.11.1)
setuptools (20.10.1)
six (1.10.0)
SQLAlchemy (1.0.15)
xlrd (1.0.0)
MySQL support is simple to add. In your DATABASES
dictionary, you will have an entry like this:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB_NAME',
'USER': 'DB_USER',
'PASSWORD': 'DB_PASSWORD',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES
array like so:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/path/to/my.cnf',
},
}
}
You also need to create the /path/to/my.cnf
file with similar settings from above
[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8
With this new method of connecting in Django 1.7, it is important to know the order connections are established:
1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.
In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.
If you are just testing your application on your local machine, you can use
python manage.py runserver
Adding the ip:port
argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook
Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:
CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin
If you are using Oracle's MySQL connector your ENGINE
line should look like this:
'ENGINE': 'mysql.connector.django',
Note that you will first need to install mysql on your OS.
brew install mysql (MacOS)
Also, the mysql client package has changed for python 3 (MySQL-Client
works only for python 2)
pip3 install mysqlclient
The WM_CONCAT
function (if included in your database, pre Oracle 11.2) or LISTAGG
(starting Oracle 11.2) should do the trick nicely. For example, this gets a comma-delimited list of the table names in your schema:
select listagg(table_name, ', ') within group (order by table_name)
from user_tables;
or
select wm_concat(table_name)
from user_tables;
#nav ul {
display: inline-block;
list-style-type: none;
}
It should work, I tested it in your site.
Using Pauan's response, it's mostly possible. Ex.
<head>
<script type="text/javascript">
function OnSearch(input) {
if(input.value == "") {
alert("You either clicked the X or you searched for nothing.");
}
else {
alert("You searched for " + input.value);
}
}
</script>
</head>
<body>
Please specify the text you want to find and press ENTER!
<input type="search" name="search" onsearch="OnSearch(this)"/>
</body>
$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');
foreach($foo as $key => $item) {
echo $item.' is begin with ('.$key.')';
}
For yarn users:
yarn add package_name@version_number
If you want to delete lines 5 through 10 and 12:
sed -e '5,10d;12d' file
This will print the results to the screen. If you want to save the results to the same file:
sed -i.bak -e '5,10d;12d' file
This will back the file up to file.bak
, and delete the given lines.
Note: Line numbers start at 1. The first line of the file is 1, not 0.
A more concise--but not necessarily faster--method is to use DataFrame.isin()
and DataFrame.any()
In [27]: n = 10
In [28]: df = DataFrame(randint(4, size=(n, 2)), columns=list('ab'))
In [29]: df
Out[29]:
a b
0 0 0
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
7 3 0
8 1 1
9 2 2
[10 rows x 2 columns]
In [30]: df.isin([1, 2])
Out[30]:
a b
0 False False
1 True True
2 True True
3 True False
4 True False
5 False True
6 True True
7 False False
8 True True
9 True True
[10 rows x 2 columns]
In [31]: df.isin([1, 2]).any(1)
Out[31]:
0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 True
9 True
dtype: bool
In [32]: df.loc[df.isin([1, 2]).any(1)]
Out[32]:
a b
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
8 1 1
9 2 2
[8 rows x 2 columns]
Create a linked server to your document
http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm
Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.
You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.
Use String#toLowerCase()
or String#equalsIgnoreCase()
methods
Some examples:
String abc = "Abc".toLowerCase();
boolean isAbc = "Abc".equalsIgnoreCase("ABC");
What I would suggest you do is create a custom ARGB color in your colors.xml file such as :
<resources>
<color name="translucent_black">#80000000</color>
</resources>
then set your button background to that color :
android:background="@android:color/translucent_black"
Another thing you can do if you want to play around with the shape of the button is to create a Shape drawable resource where you set up the properties what the button should look like :
file: res/drawable/rounded_corner_box.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#80000000"
android:endColor="#80FFFFFF"
android:angle="45"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<corners android:radius="8dp" />
</shape>
Then use that as the button background :
android:background="@drawable/rounded_corner_box"
delete
will only delete current object record from db but not its associated children records from db.
destroy
will delete current object record from db and also its associated children record from db.
Their use really matters:
If your multiple parent objects share common children objects, then calling destroy
on specific parent object will delete children objects which are shared among other multiple parents.
View.GONE makes the view invisible without the view taking up space in the layout. View.INVISIBLE makes the view just invisible still taking up space.
You are first using GONE and then INVISIBLE on the same view.Since, the code is executed sequentially, first the view becomes GONE then it is overridden by the INVISIBLE type still taking up space.
You should add button listener on the button and inside the onClick() method make the views visible. This should be the logic according to me in your onCreate() method.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
final Button btn2 = (Button) findViewById(R.id.btnDate2);
final Button btn3 = (Button) findViewById(R.id.btnVisibility);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.INVISIBLE);
bt3.setOnClickListener(new View.OnCLickListener(){
@Override
public void onClick(View view)
{
dp2.setVisibility(View.VISIBLE);
bt2.setVisibility(View.VISIBLE);
}
});
}
I think this should work easily. Hope this helps.
You cat try with below command
cat log|grep -e word1 -e word2
Angular 7 Service:
this.http.post(environment.urlRest + '/my-operation',body, { headers: headers, observe: 'response'});Component:
this.myService.myfunction().subscribe( (res: HttpResponse) => { console.log(res.headers.get('x-token')); } , error =>{ })